Compare commits

..
Author SHA1 Message Date
Tunglies a987ea9f6d refactor(subscription): keep profile writes outside proxy fallback 2026-12-02 02:10:09 +08:00
Tunglies e290a7946d refactor(backup): extract backup ZIP writing 2026-12-02 02:10:09 +08:00
Tunglies 59e315abeb refactor(task): move retry primitives into the task crate 2026-12-02 02:10:09 +08:00
Tunglies 87b3cf6561 docs(agents): define dependencies between capability crates 2026-12-02 02:10:09 +08:00
Tunglies 0010659329 refactor(profile): extract selected node recovery rules 2026-12-02 02:10:09 +08:00
Tunglies e30f1b0e47 refactor(subscription): decode deep links in the subscription crate 2026-12-02 02:10:09 +08:00
Tunglies c3c65bb418 refactor(profile): separate subscription refresh and scheduling policy
Separate download and scheduling policy from the subscription use case while retaining the existing write path.
2026-12-02 02:10:09 +08:00
Tunglies 9de413db1e refactor(profile): extract profile models and index rules
Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error.
2026-12-02 02:10:09 +08:00
Tunglies 0605236489 refactor(subscription): extract response decoding
Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid.
2026-12-02 02:10:09 +08:00
Tunglies b5b939ce03 refactor(logging): use typed logger errors
Expose crate-owned logger errors and preserve the underlying error sources.
2026-12-02 02:10:09 +08:00
Tunglies 6fdbea3748 refactor(draft): type async publication conflicts
Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates.
2026-12-02 02:10:09 +08:00
Tunglies 12b2e340ca docs(agents): define Rust backend architecture boundaries
Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.
2026-12-02 02:10:09 +08:00
Tunglies 4cc3a2fd0c chore(clippy): scope crate lint policy
Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.
2026-12-02 02:10:09 +08:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 37ff669436 chore(deps): update dependency tldts to v7.6.4 (#8805)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 17:56:26 +00:00
❤是纱雾酱哟~ b45f12a21e chore(deps): upgrade 4 npm dependencies in a batch (#8803)
- Bump eslint from ^10.11.0 to ^10.16.0
- Bump eslint-plugin-import-x from ^4.17.1 to ^4.18.1
- Bump typescript-eslint from ^8.70.0 to ^8.74.0
- Bump vitest from ^5.0.1 to ^5.0.3

Assisted-by: Copilot Fusion (Standard), actually GPT-6.1 Terra

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-01 16:53:50 +00:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 81e62504a6 build(deps): bump cross-spawn (#8799)
Bumps the npm_and_yarn group with 1 update in the / directory: [cross-spawn](https://github.com/moxystudio/node-cross-spawn).


Updates `cross-spawn` from 7.0.6 to 7.1.2
- [Release notes](https://github.com/moxystudio/node-cross-spawn/releases)
- [Changelog](https://github.com/moxystudio/node-cross-spawn/blob/master/CHANGELOG.md)
- [Commits](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.6...v7.1.2)

---
updated-dependencies:
- dependency-name: cross-spawn
  dependency-version: 7.1.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-01 14:17:43 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 251fb0e12e chore(deps): update dependency pnpm to v12.25.1 (#8798)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 13:44:59 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 623f568116 chore(deps): update dependency react-router to v8.5.1 [security] (#8792)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 07:34:16 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4d387243e8 chore(deps): update node.js to v26.14.0 (#8793)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 07:34:13 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 074aaee18c chore(deps): update dependency tldts to v7.6.3 (#8785)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-30 14:12:28 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
6d1069abd4 chore(deps): update github/gh-aw-actions action to v1.4.2 (#8773)
* chore(deps): update github/gh-aw-actions action to v1.4.2

* chore(gh-aw): bump agentic workflows from 1.4.1 to 1.4.2

- Version bump via `gh aw upgrade`

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

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-30 13:58:27 +00:00
Jeferson Araujo b484a8f24c fix(i18n): translate the connection rule dialog to pt-BR (#8771) 2026-11-30 08:30:04 +00:00
81 changed files with 3645 additions and 5987 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1",
"pnpmVersion": "12.23.0"
"version": "26.14.0",
"pnpmVersion": "12.25.1"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1",
+65 -263
View File
@@ -1,275 +1,77 @@
---
name: Agentic Workflows
description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing.
description: Routes GitHub Agentic Workflows tasks to focused authoring, debugging, and reference guidance.
disable-model-invocation: true
---
# GitHub Agentic Workflows Agent
This agent helps you work with **GitHub Agentic Workflows (gh-aw)**, a CLI extension for creating AI-powered workflows in natural language using markdown files.
Dispatch gh-aw tasks to the matching prompt or reference. Load only what the task
needs; follow its instructions and the target repository's `.github/aw/instructions.md`
when present. Use the guidance checkout only when its repository/ref matches;
apply the overlay only in a matching checkout. The target repository's overlay
overrides conflicting guidance. Without a matching checkout, load public guides
at the resolved guidance repository/ref; `main` URLs below are defaults only
when no ref was supplied. Do not create or edit workflows unless requested.
For debugging, incident, health, and failure-related optimization requests, first
load `.github/aw/debug-bootstrap.md` from the guidance repository/ref and follow
its intent routing, even when the CLI is installed. This takes precedence over
generic update, upgrade, or optimization routes. Preserve that guidance ref for
all debugging links and public raw fallbacks; URLs showing `main` below are
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
The intent index is `.github/aw/debug-scenarios.md`; load only the selected
specialized route, not every debugging reference.
## Execution and safety
## Repository Instructions Overlay
Load the target repository's `.github/aw/instructions.md`, if present.
Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute
a guidance-repository overlay.
Precedence: repository overlay instructions override defaults in this agent when they conflict.
- For incident, health, and failure-related optimization requests,
use intent routing before generic update, upgrade, or optimization routes.
First load
[debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md)
from the resolved guidance repository/ref, even when the CLI is installed.
Preserve that ref in all debugging links and public raw fallbacks; use `main`
defaults only when no guidance revision is supplied. Reuse already-loaded guides.
Then load only the selected route in
[.github/aw/debug-scenarios.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-scenarios.md).
- Do not dispatch workflows to obtain evidence. Compile is not execution
authorization. Follow [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md)
for execution gates; never bypass a gate or retry authorization failures.
- Use `gh aw` for authoring and compilation; `copilot` is a separate runtime.
Compile Markdown workflows before Actions can execute them.
- Bash is enabled by default; do not restrict commands unnecessarily.
- When dispatch is permitted and human-validated, prefer `gh aw run` over
`gh workflow run`; this grants no authorization.
- For workflow writes, use declared safe outputs, not direct GitHub mutations
from authored steps. Load [safe-outputs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/safe-outputs.md)
for write behavior and configuration.
- Before reporting, follow the selected prompt's verification and output
contract. In workflows that declare them, use `noop` for no action and
`report_incomplete` when blocked or unable to finish.
- Use only authorized tools and credentials. Never expose secret values.
- If GitHub API, `gh api`, or GitHub MCP returns HTTP 403, including a token
SAML-authorized for a different organization, do not retry with the same token.
For public `github/gh-aw` content only, fetch without authentication:
`curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/<path>'`.
Preserve the repository-relative path, including `.github/`; never send an Authorization header or token to the raw URL. Apply this fallback to
referenced instructions and `SKILL.md` files. If fetching fails, report that error.
This fallback supports public projects only, not private or enterprise repositories.
## What This Agent Does
This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task:
- **Creating new workflows**: Routes to `create` prompt
- **Updating existing workflows**: Routes to `update` prompt
- **Diagnosis, patching, and active debugging**: Routes to `debug-agentic-workflow` for the local-first strategy, evidence triage and live gates
- **Repository-wide debugging or run analysis**: Routes to `analyzing-runs` for existing-run failure clustering before selecting a workflow; supplied run/failure scope takes precedence
- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt
- **Creating report-generating workflows**: Routes to `report` prompt — consult this whenever the workflow posts status updates, audits, analyses, or any structured output as issues, discussions, or comments
- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt
- **Fixing Dependabot PRs**: Routes to `dependabot` prompt — use this when Dependabot opens PRs that modify generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`). Never merge those PRs directly; instead update the source `.md` files and rerun `gh aw compile --dependabot` to bundle all fixes
- **Analyzing test coverage**: Routes to `test-coverage` prompt — consult this whenever the workflow reads, analyzes, or reports on test coverage data from PRs or CI runs
- **Rendering ASCII charts in markdown**: Routes to `asciicharts` guide — consult this whenever the workflow needs compact charts that render reliably in GitHub issues, comments, or discussions
- **CLI commands and triggering workflows**: Routes to `cli-commands` guide — consult this whenever the user asks how to run, compile, debug, or manage workflows from the command line, or when they need the MCP tool equivalent of a `gh aw` command
- **Reducing token consumption / cost optimization**: Routes to `token-optimization` guide — consult this whenever the user asks how to reduce token usage, lower costs, speed up workflows, or measure the impact of prompt changes with experiments
- **Choosing workflow architectures and design patterns**: Routes to `patterns` guide — consult this whenever the user asks for strategy, architecture, operating models, or pattern selection for agentic workflows
- **Git-backed work queues**: Routes to `work-queue` instructions for producers, dispatchers, workers, observers, deployment and recovery
- **Third-party repository setup/configuration**: Routes to `connectors` instructions; inspect editable declarations, normal local/pinned imports, `import-schema`, credential/authentication XML and matching golden consumers. Use `gh aw connector <id> setup --file PATH` for phase-specific credential names/scopes and external acquisition/renewal guidance. Supply exact approved resources and secret names only through `with`; never secret values. Importing enables no capabilities, native methods, write credentials, broad grants or live webhook ingress. Select reads and staged safe outputs separately and derive network hosts from the contract, not a built-in provider catalog. Token acquisition/refresh and provider permissions remain external.
- **Local SDLC issue bootstrap**: Follow `.github/aw/squad.md`.
Workflows may optionally include:
- **Project tracking / monitoring** (GitHub Projects updates, status reporting)
- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows)
## Files This Applies To
- Workflow files: `.github/workflows/*.md` and `.github/workflows/**/*.md`
- Workflow lock files: `.github/workflows/*.lock.yml`
- Shared components: `.github/workflows/shared/*.md`
- Configuration: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md`
## Problems This Solves
- **Workflow Creation**: Design secure, validated agentic workflows with proper triggers, tools, and permissions
- **Diagnosis and Patching**: Analyze evidence and produce regression-backed fixes without requiring live runs
- **Active Debugging**: Run bounded edit/test/run/audit loops where permitted, stopping on dispatch 403 responses
- **Version Upgrades**: Migrate workflows to new gh-aw versions, apply codemods, fix breaking changes
- **Component Design**: Create reusable shared workflow components that wrap MCP servers
## How to Use
When you interact with this agent, it will:
1. **Understand your intent** - Determine what kind of task you're trying to accomplish
2. **Route to the right prompt** - Load the specialized prompt file for your task
3. **Execute the task** - Follow the detailed instructions in the loaded prompt
## Available Prompts
> **Note**: The prompt and reference files below are from [`github/gh-aw`](https://github.com/github/gh-aw). Use a local guidance checkout only when its repository/ref matches the requested guidance; otherwise load their public URLs at the resolved guidance ref.
If GitHub API, `gh api`, or GitHub MCP downloads return HTTP 403 (including a token SAML-authorized for a different organization), do not retry with the same token. Fetch the public file without authentication from `https://raw.githubusercontent.com/github/gh-aw/main/<path>` instead, preserving its repository-relative path (including `.github/`). For example: `curl --fail --silent --show-error --location 'https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md'`. Use the same fallback for referenced instructions and `SKILL.md` files; never send an Authorization header or token to the raw URL. If the public download fails, report that error rather than proceeding without the required instructions. This fallback is for public `github/gh-aw` content only, not private or enterprise repositories.
### Create New Workflow
**Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md`
**Use cases**:
- "Create a workflow that triages issues"
- "I need a workflow to label pull requests"
- "Design a weekly research automation"
### Update Existing Workflow
**Load when**: User wants to modify, improve, or refactor an existing workflow
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md`
**Use cases**:
- "Add web-fetch tool to the issue-classifier workflow"
- "Update the PR reviewer to use discussions instead of issues"
- "Improve the prompt for the weekly-research workflow"
### Diagnose, Patch, or Debug a Workflow
**Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md`
The shared strategy distinguishes diagnosis/patching from permitted active debug
loops using explicit live gates and includes existing-run evidence triage.
For CLI setup or run-URL scoping in a fresh session, first load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md`; it bootstraps
this same strategy rather than a separate debug procedure.
**Use cases**:
- "Why is this workflow failing?"
- "Analyze the logs for workflow X"
- "Investigate missing tool calls in run #12345"
### Analyze Existing Runs or Repository-Wide Failures
**Load when**: User asks to debug or optimize agentic workflows generally, without a specific run/failure scope
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md`
Start with repository-wide existing-run failure clustering, not an arbitrary
workflow or a request to pick one. Supplied workflow/run/failure scope takes
precedence. Use the shared debugging strategy for subsequent fixes; never
dispatch workflows to obtain evidence.
### Upgrade Agentic Workflows
**Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md`
**Use cases**:
- "Upgrade all workflows to the latest version"
- "Fix deprecated fields in workflows"
- "Apply breaking changes from the new release"
### Create a Report-Generating Workflow
**Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md`
**Use cases**:
- "Create a weekly CI health report"
- "Post a daily security audit to Discussions"
- "Add a status update comment to open PRs"
### Create Shared Agentic Workflow
**Load when**: User wants to create a reusable workflow component or wrap an MCP server
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md`
**Use cases**:
- "Create a shared component for Notion integration"
- "Wrap the Slack MCP server as a reusable component"
- "Design a shared workflow for database queries"
### Fix Dependabot PRs
**Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`)
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md`
**Use cases**:
- "Fix the open Dependabot PRs for npm dependencies"
- "Bundle and close the Dependabot PRs for workflow dependencies"
- "Update @playwright/test to fix the Dependabot PR"
### Analyze Test Coverage
**Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy.
**Prompt file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md`
**Use cases**:
- "Create a workflow that comments coverage on PRs"
- "Analyze coverage trends over time"
- "Add a coverage gate that blocks PRs below a threshold"
### CLI Commands Reference
**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
**Use cases**:
- "How do I trigger workflow X on the main branch?"
- "What's the MCP equivalent of `gh aw logs`?"
- "I'm in Copilot Cloud — how do I compile a workflow?"
- "Show me all available gh aw commands"
### Token Consumption Optimization
**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md`
**Use cases**:
- "How do I reduce the token cost of this workflow?"
- "My workflow is too expensive — how do I optimize it?"
- "How do I compare token usage between two runs?"
- "Should I use gh-proxy or the MCP server?"
- "How do I use sub-agents to reduce costs?"
- "How do I measure the impact of a prompt change?"
### Workflow Pattern Selection
**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows.
**Reference file**: `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md`
**Use cases**:
- "Which pattern should I use for multi-repo rollout?"
- "How should I structure this workflow architecture?"
- "What pattern fits slash-command triage?"
- "Should this be DispatchOps or DailyOps?"
## Instructions
### Work Queue
For queue design, deployment, inspection or recovery, load
`https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md`.
Also load it after the primary create/update/debug/upgrade prompt whenever a
workflow uses `tools.work-queue`. Load linked developer docs and specifications
only when needed; do not substitute lightweight WorkQueueOps backlog guidance
for the Git-backed protocol.
When a user interacts with you:
1. **Identify the task type** from the user's request
2. **Load the appropriate prompt** from the URLs listed above
3. **Follow the loaded prompt's instructions** exactly
4. **If uncertain**, ask clarifying questions to determine the right prompt
## Quick Reference
```bash
# Initialize repository for agentic workflows
gh aw init
# Generate the lock file for a workflow
gh aw compile [workflow-name]
# Only where permitted and human-validated under debug-agentic-workflow.md:
gh aw run <workflow-name> --ref REVIEWED_REF
# Debug workflow runs
gh aw logs [workflow-name] --repo HOST/OWNER/REPO
gh aw audit <run-url> # preserve host/repository and any job/step scope
gh aw compile <workflow-name> --dry-run # first test of workflow changes
# Upgrade workflows
gh aw fix --write
gh aw compile --validate
```
## Key Features of gh-aw
- **Natural Language Workflows**: Write workflows in markdown with YAML frontmatter
- **AI Engine Support**: Copilot, Claude, Codex, or custom engines
- **MCP Server Integration**: Connect to Model Context Protocol servers for tools
- **Safe Outputs**: Structured communication between AI and GitHub API
- **Strict Mode**: Security-first validation and sandboxing
- **Shared Components**: Reusable workflow building blocks
- **Repo Memory**: Persistent git-backed storage for agents
- **Sandboxed Execution**: All workflows run in the Agent Workflow Firewall (AWF) sandbox, enabling full `bash` and `edit` tools by default
## Important Notes
- For complete documentation, load `.github/aw/github-agentic-workflows.md` from the resolved guidance repository/ref.
- Use gh-aw MCP tools only when exposed and authorized; otherwise use available CLI, cached evidence or static source through the CLI/MCP reference.
- Workflows must be compiled to `.lock.yml` files before running in GitHub Actions
- **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF
- Follow security best practices: minimal permissions, explicit network access, no template injection
- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/network.md` for the full list of valid ecosystem identifiers and domain patterns.
- **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself.
- **Triggering runs**: Only where permitted and human-validated under `debug-agentic-workflow.md`, prefer `gh aw run <workflow-name>` over `gh workflow run <file>.lock.yml` for workflow resolution, input validation and run-tracking. Use the reviewed remote ref; explicit no-dispatch rules override user requests.
- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see `https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md`
- **Creating new workflows**: [create-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-agentic-workflow.md)
- **Updating workflows**: [update-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/update-agentic-workflow.md)
- **Diagnosing, patching, or debugging a workflow**: use the debugging route above, then [debug-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-agentic-workflow.md).
- **Analyzing existing runs or repository-wide failures**: [analyzing-runs.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/analyzing-runs.md). Start with failure clustering; supplied workflow/run scope takes precedence.
- **Upgrading workflows**: [upgrade-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md)
- **Creating report-generating workflows**: [report.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md)
- **Creating shared components**: [create-shared-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md)
- **Fixing Dependabot workflow-manifest PRs**: [dependabot.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/dependabot.md); never merge manifest-only PRs, update source Markdown, and compile with `--dependabot`.
- **Analyzing test coverage**: [test-coverage.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md)
- **CLI commands or restricted environments**: [cli-commands.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/cli-commands.md). For logs, use `gh aw logs [workflow-name] --repo HOST/OWNER/REPO`.
- **Reducing token use or cost**: [token-optimization.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md)
- **Selecting workflow architecture or patterns**: [patterns.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md)
- **Designing, deploying, inspecting, or recovering work queues**: [work-queue.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/work-queue.md). Also load it after the primary create/update/debug/upgrade prompt when `tools.work-queue` is used.
- **Compact Markdown/ASCII charts**: [asciicharts.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/asciicharts.md) for charts rendered directly in issues or comments.
- **Third-party integrations**: [connectors.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/connectors.md); inspect the selected declaration and its schema/docs. Bind approved resources and secret names only; importing grants no capabilities or credentials.
- **Local SDLC issue bootstrap**: [squad.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/squad.md)
Workflows may optionally include project tracking or coordination; consult the
selected design prompt.
For general workflow authoring, load
[github-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md).
Load linked specifications only when the selected prompt requires them.
<!-- instruction-prefix-end -->
+32 -7
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.4.1": {
"github/gh-aw-actions/setup@v1.4.2": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.4.1",
"sha": "367d4dc4e89caf85422092845006e4a4a660d926"
"version": "v1.4.2",
"sha": "d7852d91d5d1d13e7848771edab8bd1792a08651"
}
},
"containers": {
@@ -52,6 +52,11 @@
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22",
"digest": "sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -92,6 +97,11 @@
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22",
"digest": "sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -112,6 +122,11 @@
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22",
"digest": "sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -127,6 +142,11 @@
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.22",
"digest": "sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -167,10 +187,15 @@
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.15": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
"ghcr.io/github/gh-aw-firewall/squid:0.29.22": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22",
"digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.16": {
"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"
},
"ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node",
@@ -100,6 +100,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/charts.md`
- `.github/aw/cli-commands.md`
- `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md`
- `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.md`
@@ -148,6 +149,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/maintainer.md`
- `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md`
- `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md`
+5 -5
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install dependencies
run: pnpm install --frozen-lockfile
@@ -182,7 +182,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -262,7 +262,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -395,7 +395,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6.1.1
name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
uses: github/gh-aw-actions/setup-cli@d7852d91d5d1d13e7848771edab8bd1792a08651 # v1.4.2
with:
version: v1.4.1
version: v1.4.2
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Install frontend dependencies
env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+1 -1
View File
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
if: github.event.action != 'closed'
+8 -8
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Validate source and publish the approved snapshot
id: source
env:
@@ -231,7 +231,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -330,7 +330,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -461,7 +461,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
with:
run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Install pnpm
uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- name: Sync Mihomo version
id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node
uses: actions/setup-node@v7
with:
node-version: '26.13.1'
node-version: '26.14.0'
- uses: pnpm/action-setup@v6
name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.23.0
nodejs 26.14.0
pnpm 12.25.1
rust 1.100.1
Generated
+1 -70
View File
@@ -1089,20 +1089,16 @@ dependencies = [
"async-trait",
"backon",
"base64 0.23.1",
"boa_engine",
"bytes",
"chrono",
"clash-verge-backup-archive",
"clash-verge-config-render",
"clash-verge-draft",
"clash-verge-i18n",
"clash-verge-limiter",
"clash-verge-logging",
"clash-verge-media-unlock",
"clash-verge-profile",
"clash-verge-profile-script",
"clash-verge-profile-store",
"clash-verge-proxy-view",
"clash-verge-runtime-bundle",
"clash-verge-signal",
"clash-verge-subscription",
"clash-verge-task",
@@ -1159,7 +1155,6 @@ dependencies = [
"tauri-plugin-wdio-webdriver",
"tauri-plugin-window-state",
"tauri-specta",
"tempfile",
"tokio",
"tokio-rustls",
"tokio-util",
@@ -1182,19 +1177,6 @@ dependencies = [
"zip",
]
[[package]]
name = "clash-verge-config-render"
version = "0.1.0"
dependencies = [
"clash-verge-logging",
"log",
"serde",
"serde_json",
"serde_yaml_ng",
"tokio",
"tristr",
]
[[package]]
name = "clash-verge-draft"
version = "0.1.0"
@@ -1255,57 +1237,6 @@ dependencies = [
"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-profile-store"
version = "0.1.0"
dependencies = [
"clash-verge-profile",
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.20",
"windows-sys 0.61.2",
]
[[package]]
name = "clash-verge-proxy-view"
version = "0.1.0"
dependencies = [
"serde",
"specta",
"tristr",
]
[[package]]
name = "clash-verge-runtime-bundle"
version = "0.1.0"
dependencies = [
"clash-verge-logging",
"hex",
"log",
"serde_yaml_ng",
"sha2 0.11.2",
"thiserror 2.0.20",
"tokio",
"tristr",
]
[[package]]
name = "clash-verge-signal"
version = "0.1.0"
-14
View File
@@ -10,12 +10,7 @@ members = [
"crates/clash-verge-i18n",
"crates/clash-verge-limiter",
"crates/clash-verge-subscription",
"crates/clash-verge-runtime-bundle",
"crates/clash-verge-config-render",
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
"crates/clash-verge-profile-store",
"crates/clash-verge-backup-archive",
]
resolver = "2"
@@ -60,8 +55,6 @@ split-debuginfo = "unpacked"
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
[workspace.dependencies]
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
@@ -70,12 +63,8 @@ clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-profile-store = { path = "crates/clash-verge-profile-store" }
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" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
@@ -86,7 +75,6 @@ parking_lot = "0.13.0"
anyhow = "1.0.105"
thiserror = "2.0.20"
zip = "9.9.0"
boa_engine = "0.22.0"
futures = "0.3.34"
chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] }
@@ -111,8 +99,6 @@ serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" }
sha2 = "0.11.2"
tempfile = "3.27.0"
specta = "=2.0.0-rc.26"
socket2 = "0.6.5"
+1
View File
@@ -33,6 +33,7 @@
- 修复检测更新后又发布新版时,应用内更新失败
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
- 修复服务端文件名无效时导入的订阅名称为空
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
+2 -6
View File
@@ -40,7 +40,6 @@ pub struct ValidatedBackup<R: Read + Seek> {
}
impl<R: Read + Seek> ValidatedBackup<R> {
/// Checks the archive layout. Extract into staging to validate file contents before restore.
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
for index in 0..zip.len() {
@@ -61,15 +60,12 @@ impl<R: Read + Seek> ValidatedBackup<R> {
return Err(ArchiveError::ReservedEntry);
}
}
// ZIP extraction skips directory payloads.
if entry.is_dir() {
io::copy(&mut entry, &mut io::sink())?;
}
io::copy(&mut entry, &mut io::sink())?;
}
Ok(Self { zip })
}
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
pub fn extract_to(mut self, destination: &Path) -> Result<(), ArchiveError> {
self.zip.extract(destination)?;
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());
}
}
@@ -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,28 +0,0 @@
[package]
name = "clash-verge-profile-store"
version = "0.1.0"
edition = "2024"
[features]
test-support = []
[dependencies]
thiserror = { workspace = true }
clash-verge-profile = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
[lints]
workspace = true
[dev-dependencies]
tempfile = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_System_WindowsProgramming",
] }
@@ -1,76 +0,0 @@
use std::{io, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error(transparent)]
Io(#[from] io::Error),
#[error("{operation} {}", path.display())]
PathIo {
operation: &'static str,
path: PathBuf,
#[source]
source: io::Error,
},
#[error(transparent)]
IndexYaml(#[from] serde_yaml_ng::Error),
#[error(transparent)]
SerializeDecision(#[from] serde_json::Error),
#[error("invalid refresh decision")]
InvalidDecision(#[source] serde_json::Error),
#[error(transparent)]
ProfileNotFound(#[from] clash_verge_profile::ProfileNotFound),
#[error("index and body must share a filesystem")]
DifferentVolumes,
#[cfg(windows)]
#[error("profile recovery requires a supported NTFS volume")]
UnsupportedVolume,
#[error("profile UID is shared")]
SharedUid,
#[error("profile is missing from the on-disk index")]
ProfileMissingFromDisk,
#[error("profile source is ambiguous")]
AmbiguousProfile,
#[error("profile must be remote")]
NotRemote,
#[error("body filename changed")]
FilenameChanged,
#[error("body filename is shared")]
SharedFilename,
#[error("new body path already exists")]
ExistingBodyPath,
#[error("decision is oversized")]
OversizedDecision,
#[error("unknown refresh decision version")]
UnknownDecisionVersion,
#[error("refresh decision target does not match the staged index")]
DecisionTargetMismatch,
#[error("staged content checksum mismatch")]
StagedChecksumMismatch,
#[error("refresh marker is missing for an inconsistent pair")]
InconsistentUnmarkedPair,
#[error("journal is not a directory")]
InvalidJournal,
#[error("decision is not a regular file")]
InvalidDecisionFile,
#[error("invalid profile filename")]
InvalidFilename,
#[cfg(windows)]
#[error("invalid Windows profile filename")]
InvalidWindowsFilename,
#[error("missing profile filename")]
MissingFilename,
#[error("UID or filename is shared")]
SharedUidOrFilename,
#[error("profile body is hard linked")]
HardLinkedBody,
#[error("profile file has a filesystem alias")]
AliasedBody,
#[error("live content changed outside the refresh transaction: {}", .0.display())]
LiveContentChanged(PathBuf),
#[error("expected directory {}", .0.display())]
ExpectedDirectory(PathBuf),
#[error("expected regular file {}", .0.display())]
ExpectedRegularFile(PathBuf),
#[error("missing {}", .0.display())]
MissingFile(PathBuf),
}
-650
View File
@@ -1,650 +0,0 @@
//! Recoverable replacement of one subscription body and the profile index.
#![cfg(any(unix, windows))]
mod error;
mod platform;
pub use error::StoreError;
use clash_verge_profile::IProfiles;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use std::{
fs::{self, File, Permissions},
io::{self, Write as _},
path::{Path, PathBuf},
};
pub const RECOVERY_JOURNAL_NAME: &str = ".profile-refresh";
pub const RECOVERY_ENTRY_NAMES: &[&str] = &[RECOVERY_JOURNAL_NAME, RECOVERY_LOCK_NAME];
const RECOVERY_LOCK_NAME: &str = ".profile-refresh.lock";
const DECISION: &str = "decision";
const MAX_DECISION_BYTES: u64 = 4096;
const PROFILES: &str = "profiles";
const INDEX: &str = "profiles.yaml";
const BODY_NEXT: &str = "body.next";
const INDEX_NEXT: &str = "index.next";
const DECISION_NEXT: &str = "decision.next";
const DECISION_BUILDING: &str = "decision.building";
const APPLY: &str = "body.apply";
type Result<T> = std::result::Result<T, StoreError>;
type Checkpoint<'a> = dyn FnMut(&'static str) -> Result<()> + 'a;
#[derive(Debug)]
pub enum CommitOutcome {
Committed,
CommittedCleanupPending(StoreError),
Retryable(StoreError),
RetryCleanupFailed(StoreError),
NeedsRecovery(StoreError),
}
enum InstallOutcome {
Installed,
Reverted(StoreError),
}
pub struct Session {
root: PathBuf,
_lock: File,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Decision {
version: u32,
uid: String,
file: String,
old_body_digest: Option<[u8; 32]>,
old_index_digest: [u8; 32],
body_digest: [u8; 32],
index_digest: [u8; 32],
}
impl Session {
pub fn open(root: &Path) -> Result<Self> {
Self::open_with_checkpoint(root, &mut |_| Ok(()))
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn open_observed(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
Self::open_with_checkpoint(root, checkpoint)
}
fn open_with_checkpoint(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
let root = root.canonicalize()?;
let root_metadata = directory(&root)?;
let profiles = root.join(PROFILES);
let profile_metadata = directory(&profiles)?;
if platform::volume(&root, &root_metadata)? != platform::volume(&profiles, &profile_metadata)? {
return Err(StoreError::DifferentVolumes);
}
#[cfg(windows)]
if !platform::supports_redo(&root)? {
return Err(StoreError::UnsupportedVolume);
}
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
lock.lock()?;
let session = Self { root, _lock: lock };
session.recover(checkpoint)?;
Ok(session)
}
fn journal(&self) -> PathBuf {
self.root.join(RECOVERY_JOURNAL_NAME)
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn snapshot(&self, uid: &str) -> Result<(IProfiles, Vec<u8>)> {
let profiles = serde_yaml_ng::from_slice(&fs::read(self.root.join(INDEX))?)?;
let file = body_filename(&profiles, uid)?;
let body = fs::read(self.root.join(PROFILES).join(file))?;
Ok((profiles, body))
}
pub fn commit_refresh(self, uid: &str, candidate: &IProfiles, body: &[u8]) -> CommitOutcome {
let outcome = self.commit_with_checkpoint(uid, candidate, body, &mut |_| Ok(()));
self.finish_commit(outcome)
}
fn finish_commit(&self, outcome: CommitOutcome) -> CommitOutcome {
match outcome {
CommitOutcome::Retryable(error) => match self.recover(&mut |_| Ok(())) {
Ok(()) => CommitOutcome::Retryable(error),
Err(cleanup) => CommitOutcome::RetryCleanupFailed(cleanup),
},
CommitOutcome::CommittedCleanupPending(error) => match self.recover(&mut |_| Ok(())) {
Ok(()) => CommitOutcome::Committed,
Err(_) => CommitOutcome::CommittedCleanupPending(error),
},
outcome => outcome,
}
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn commit_observed(
self,
uid: &str,
candidate: &IProfiles,
body: &[u8],
checkpoint: &mut Checkpoint<'_>,
) -> CommitOutcome {
self.commit_with_checkpoint(uid, candidate, body, checkpoint)
}
fn commit_with_checkpoint(
&self,
uid: &str,
candidate: &IProfiles,
body: &[u8],
checkpoint: &mut Checkpoint<'_>,
) -> CommitOutcome {
let before = self.prepare(uid, candidate, body, checkpoint);
if let Err(error) = before {
return CommitOutcome::Retryable(error);
}
let journal = self.journal();
if let Err(error) = fs::hard_link(journal.join(DECISION_NEXT), journal.join(DECISION)) {
return CommitOutcome::Retryable(error.into());
}
let published = (|| {
checkpoint("decision-created")?;
platform::sync_dir(&journal)?;
checkpoint("decision-synced")?;
self.install(checkpoint)
})();
let installed = match published {
Ok(installed) => installed,
Err(error) => return CommitOutcome::NeedsRecovery(error),
};
match (installed, self.disarm_and_clean(checkpoint)) {
(InstallOutcome::Installed, Ok(())) => CommitOutcome::Committed,
(InstallOutcome::Installed, Err(error)) => CommitOutcome::CommittedCleanupPending(error),
(InstallOutcome::Reverted(rejection), Ok(())) => CommitOutcome::Retryable(rejection),
(InstallOutcome::Reverted(_), Err(error)) => CommitOutcome::NeedsRecovery(error),
}
}
fn prepare(&self, uid: &str, candidate: &IProfiles, body: &[u8], checkpoint: &mut Checkpoint<'_>) -> Result<()> {
// Check directory flush access before creating a Windows journal.
#[cfg(windows)]
{
platform::sync_dir(&self.root)?;
platform::sync_dir(&self.root.join(PROFILES))?;
}
let index_path = self.root.join(INDEX);
let old_index = fs::read(&index_path)?;
let current: IProfiles = serde_yaml_ng::from_slice(&old_index)?;
let file = body_filename(candidate, uid)?;
let new_item = candidate.get_item(uid)?;
let mut exact = current
.items
.iter()
.flatten()
.filter(|item| item.uid.as_deref() == Some(uid));
let old_item = if let Some(item) = exact.next() {
if exact.next().is_some() {
return Err(StoreError::SharedUid);
}
item
} else {
// Loading an old index may assign a UID without rewriting the file.
let mut legacy = current.items.iter().flatten().filter(|item| {
item.uid.is_none()
&& item.itype.as_deref() == Some("remote")
&& item.url == new_item.url
&& item.file.as_deref().is_none_or(|old| old == file)
});
let item = legacy.next().ok_or(StoreError::ProfileMissingFromDisk)?;
if legacy.next().is_some() {
return Err(StoreError::AmbiguousProfile);
}
item
};
if old_item.itype.as_deref() != Some("remote") {
return Err(StoreError::NotRemote);
}
if let Some(old_file) = old_item.file.as_deref()
&& old_file != file
{
return Err(StoreError::FilenameChanged);
}
if !current
.items
.iter()
.flatten()
.all(|item| std::ptr::eq(item, old_item) || item.file.as_deref() != Some(file))
{
return Err(StoreError::SharedFilename);
}
let profiles_dir = self.root.join(PROFILES);
let metadata = unshared_body(&profiles_dir, &current, file)?;
unshared_body(&profiles_dir, candidate, file)?;
let index_permissions = regular(&index_path)?.permissions();
let old_body_digest = optional_file_digest(&profiles_dir.join(file))?;
if old_item.file.is_none() && old_body_digest.is_some() {
return Err(StoreError::ExistingBodyPath);
}
let index = format!(
"# Profiles Config for Clash Verge\n\n{}",
serde_yaml_ng::to_string(candidate)?
);
let decision = Decision {
version: 1,
uid: uid.into(),
file: file.into(),
old_body_digest,
old_index_digest: Sha256::digest(&old_index).into(),
body_digest: Sha256::digest(body).into(),
index_digest: Sha256::digest(index.as_bytes()).into(),
};
let decision = serde_json::to_vec(&decision)?;
if decision.len() as u64 > MAX_DECISION_BYTES {
return Err(StoreError::OversizedDecision);
}
let journal = self.journal();
platform::create_dir(&journal)?;
platform::sync_dir(&self.root)?;
checkpoint("journal-created")?;
write_new(&journal.join(BODY_NEXT), body, metadata.map(|meta| meta.permissions()))?;
checkpoint("body-staged")?;
write_new(&journal.join(INDEX_NEXT), index.as_bytes(), Some(index_permissions))?;
checkpoint("index-staged")?;
write_new(&journal.join(DECISION_BUILDING), &decision, None)?;
platform::replace(journal.join(DECISION_BUILDING), journal.join(DECISION_NEXT))?;
// A decision that survives interruption must only reference already-synced inputs.
platform::sync_dir(&journal)?;
checkpoint("prepared")
}
fn install(&self, checkpoint: &mut Checkpoint<'_>) -> Result<InstallOutcome> {
let journal = self.journal();
let decision = read_decision(&journal.join(DECISION))?;
let index_next = journal.join(INDEX_NEXT);
let (index, index_permissions) = verified(&index_next, decision.index_digest)?;
let candidate: IProfiles = serde_yaml_ng::from_slice(&index)?;
if body_filename(&candidate, &decision.uid)? != decision.file {
return Err(StoreError::DecisionTargetMismatch);
}
let profiles_dir = self.root.join(PROFILES);
let body_path = profiles_dir.join(&decision.file);
let index_path = self.root.join(INDEX);
let apply = journal.join(APPLY);
let body_installed = verify_live(&body_path, decision.old_body_digest, decision.body_digest)?;
let index_installed = verify_live(&index_path, Some(decision.old_index_digest), decision.index_digest)?;
let can_revert_new_body = decision.old_body_digest.is_none()
&& (!index_installed || decision.old_index_digest == decision.index_digest);
if !can_revert_new_body {
unshared_body(&profiles_dir, &candidate, &decision.file)?;
}
let body_next = journal.join(BODY_NEXT);
if body_installed {
if file_digest(&body_next)? != decision.body_digest {
return Err(StoreError::StagedChecksumMismatch);
}
// Equality alone does not establish durability of a prior in-place edit.
platform::sync_file(&body_path)?;
} else {
remove_file_if_exists(&apply)?;
copy_verified(&body_next, &apply, decision.body_digest)?;
platform::replace(&apply, &body_path).map_err(|source| StoreError::PathIo {
operation: "replace",
path: body_path.clone(),
source,
})?;
}
checkpoint("body-replaced")?;
if can_revert_new_body {
// Native aliases of a missing file only resolve once the file exists.
let check = (|| {
unshared_body(&profiles_dir, &candidate, &decision.file)?;
if !index_installed {
let (index, _) = verified(&index_path, decision.old_index_digest)?;
let current = serde_yaml_ng::from_slice(&index)?;
unshared_body(&profiles_dir, &current, &decision.file)?;
}
Ok(())
})();
if let Err(error) = check {
match error {
StoreError::AliasedBody | StoreError::InvalidFilename => {}
#[cfg(windows)]
StoreError::InvalidWindowsFilename => {}
_ => return Err(error),
}
fs::remove_file(&body_path)?;
platform::sync_dir(&profiles_dir)?;
return Ok(InstallOutcome::Reverted(error));
}
}
if index_installed {
platform::sync_file(&index_path)?;
} else {
// The body rename consumed the scratch file. Replay can discard it at either step.
remove_file_if_exists(&apply)?;
write_new(&apply, &index, Some(index_permissions))?;
platform::replace(&apply, &index_path).map_err(|source| StoreError::PathIo {
operation: "replace",
path: index_path,
source,
})?;
}
checkpoint("index-replaced")?;
platform::sync_dir(&profiles_dir)?;
checkpoint("body-synced")?;
platform::sync_dir(&self.root)?;
checkpoint("index-synced")?;
Ok(InstallOutcome::Installed)
}
fn disarm_and_clean(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
let journal = self.journal();
fs::remove_file(journal.join(DECISION))?;
checkpoint("decision-removed")?;
platform::sync_dir(&journal)?;
checkpoint("disarmed")?;
self.remove_journal()?;
checkpoint("journal-removed")
}
fn remove_journal(&self) -> Result<()> {
let journal = self.journal();
for name in [
DECISION_NEXT,
DECISION_BUILDING,
BODY_NEXT,
INDEX_NEXT,
APPLY,
"index.apply", // Older v1 journals used a separate scratch file for the index.
] {
remove_file_if_exists(&journal.join(name))?;
}
fs::remove_dir(&journal)?;
Ok(platform::sync_dir(&self.root)?)
}
fn check_unmarked_pair(&self, intent: &Decision) -> Result<()> {
let body = optional_file_digest(&self.root.join(PROFILES).join(&intent.file))?;
let index = file_digest(&self.root.join(INDEX))?;
let old_pair = body == intent.old_body_digest && index == intent.old_index_digest;
let new_pair = body == Some(intent.body_digest) && index == intent.index_digest;
if !old_pair && !new_pair {
return Err(StoreError::InconsistentUnmarkedPair);
}
Ok(())
}
fn recover(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
let journal = self.journal();
match fs::symlink_metadata(&journal) {
Ok(metadata) => {
if !metadata.is_dir() || platform::is_reparse(&metadata) {
return Err(StoreError::InvalidJournal);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
}
match fs::symlink_metadata(journal.join(DECISION)) {
Ok(metadata) => {
if !metadata.is_file() || platform::is_reparse(&metadata) {
return Err(StoreError::InvalidDecisionFile);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
// A previous process may have unlinked the decision before its directory sync.
platform::sync_dir(&journal)?;
let intent = journal.join(DECISION_NEXT);
match fs::symlink_metadata(&intent) {
Ok(_) => self.check_unmarked_pair(&read_decision(&intent)?)?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
return self.remove_journal();
}
Err(error) => return Err(error.into()),
}
// A visible decision may have survived a process interruption before its directory sync.
platform::sync_dir(&journal)?;
self.install(checkpoint)?;
self.disarm_and_clean(checkpoint)
}
}
fn read_decision(path: &Path) -> Result<Decision> {
if regular(path)?.len() > MAX_DECISION_BYTES {
return Err(StoreError::OversizedDecision);
}
let decision: Decision = serde_json::from_slice(&fs::read(path)?).map_err(StoreError::InvalidDecision)?;
if decision.version != 1 {
return Err(StoreError::UnknownDecisionVersion);
}
validate_filename(&decision.file)?;
Ok(decision)
}
fn validate_filename(file: &str) -> Result<()> {
if file.is_empty() || matches!(file, "." | "..") || file.contains(['/', '\\', ':', '\0']) {
return Err(StoreError::InvalidFilename);
}
#[cfg(windows)]
{
let stem = file
.split('.')
.next()
.unwrap_or_default()
.trim_end_matches(' ')
.to_ascii_uppercase();
let is_port_device = ["COM", "LPT"].iter().any(|prefix| {
stem.strip_prefix(prefix).is_some_and(|suffix| {
matches!(
suffix,
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
)
})
});
if file.ends_with([' ', '.'])
|| file.contains(['<', '>', '"', '|', '?', '*'])
|| file.bytes().any(|byte| byte < 32)
|| matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| is_port_device
{
return Err(StoreError::InvalidWindowsFilename);
}
}
Ok(())
}
fn body_filename<'a>(profiles: &'a IProfiles, uid: &str) -> Result<&'a str> {
let item = profiles.get_item(uid)?;
if item.itype.as_deref() != Some("remote") {
return Err(StoreError::NotRemote);
}
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
validate_filename(file)?;
let owners = profiles
.items
.iter()
.flatten()
.filter(|item| item.uid.as_deref() == Some(uid) || item.file.as_deref() == Some(file))
.count();
if owners != 1 {
return Err(StoreError::SharedUidOrFilename);
}
Ok(file)
}
fn unshared_body(dir: &Path, profiles: &IProfiles, file: &str) -> Result<Option<fs::Metadata>> {
let path = dir.join(file);
let target = optional_regular(&path)?;
let identity = target
.as_ref()
.map(|metadata| platform::file_identity(&path, metadata))
.transpose()?;
if identity.as_ref().is_some_and(|identity| identity.links != 1) {
return Err(StoreError::HardLinkedBody);
}
for other in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
if other == file {
continue;
}
// Other entries may use native filenames, but they must stay in this directory.
let mut components = Path::new(other).components();
if !matches!(
(components.next(), components.next()),
(Some(std::path::Component::Normal(name)), None) if name == other
) || other.contains('\0')
{
return Err(StoreError::InvalidFilename);
}
#[cfg(windows)]
validate_filename(other)?;
let other = dir.join(other);
match fs::metadata(&other) {
Ok(metadata) => {
if let Some(identity) = &identity
&& platform::file_identity(&other, &metadata)? == *identity
{
return Err(StoreError::AliasedBody);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
}
Ok(target)
}
fn file_digest(path: &Path) -> Result<[u8; 32]> {
regular(path)?;
transfer_digest(File::open(path)?, io::sink())
}
fn optional_file_digest(path: &Path) -> Result<Option<[u8; 32]>> {
optional_regular(path)?
.map(|_| transfer_digest(File::open(path)?, io::sink()))
.transpose()
}
fn transfer_digest(mut input: impl io::Read, mut output: impl io::Write) -> Result<[u8; 32]> {
let mut digest = Sha256::new();
let mut buffer = [0; 16 * 1024];
loop {
let len = match input.read(&mut buffer) {
Ok(0) => return Ok(digest.finalize().into()),
Ok(len) => len,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error.into()),
};
digest.update(&buffer[..len]);
output.write_all(&buffer[..len])?;
}
}
fn copy_verified(from: &Path, to: &Path, expected: [u8; 32]) -> Result<()> {
let permissions = regular(from)?.permissions();
let mut output = platform::create_new(to)?;
let actual = transfer_digest(File::open(from)?, &mut output)?;
if actual != expected {
return Err(StoreError::StagedChecksumMismatch);
}
output.set_permissions(permissions)?;
output.sync_all()?;
Ok(())
}
fn verify_live(path: &Path, old: Option<[u8; 32]>, new: [u8; 32]) -> Result<bool> {
let actual = optional_file_digest(path)?;
if actual != old && actual != Some(new) {
return Err(StoreError::LiveContentChanged(path.to_owned()));
}
Ok(actual == Some(new))
}
fn verified(path: &Path, digest: [u8; 32]) -> Result<(Vec<u8>, Permissions)> {
let permissions = regular(path)?.permissions();
let bytes = fs::read(path)?;
let actual: [u8; 32] = Sha256::digest(&bytes).into();
if actual != digest {
return Err(StoreError::StagedChecksumMismatch);
}
Ok((bytes, permissions))
}
fn directory(path: &Path) -> Result<fs::Metadata> {
let metadata = fs::symlink_metadata(path).map_err(|source| StoreError::PathIo {
operation: "inspect",
path: path.to_owned(),
source,
})?;
if !metadata.is_dir() || platform::is_reparse(&metadata) {
return Err(StoreError::ExpectedDirectory(path.to_owned()));
}
Ok(metadata)
}
fn regular(path: &Path) -> Result<fs::Metadata> {
optional_regular(path)?.ok_or_else(|| StoreError::MissingFile(path.to_owned()))
}
fn optional_regular(path: &Path) -> Result<Option<fs::Metadata>> {
match fs::symlink_metadata(path) {
Ok(metadata) => {
if !metadata.is_file() || platform::is_reparse(&metadata) {
return Err(StoreError::ExpectedRegularFile(path.to_owned()));
}
Ok(Some(metadata))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(StoreError::PathIo {
operation: "inspect",
path: path.to_owned(),
source,
}),
}
}
fn write_new(path: &Path, bytes: &[u8], permissions: Option<Permissions>) -> Result<()> {
let mut file = platform::create_new(path).map_err(|source| StoreError::PathIo {
operation: "create",
path: path.to_owned(),
source,
})?;
file.write_all(bytes)?;
if let Some(permissions) = permissions {
file.set_permissions(permissions)?;
}
file.sync_all()?;
Ok(())
}
fn remove_file_if_exists(path: &Path) -> Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
/// Replays a saved decision before the application creates or loads its index.
pub fn recover_pending(root: &Path) -> Result<()> {
match fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
Ok(_) => Session::open(root).map(drop),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
#[cfg(windows)]
pub fn supports_redo(root: &Path) -> Result<bool> {
Ok(platform::supports_redo(root)?)
}
@@ -1,209 +0,0 @@
#[cfg(windows)]
pub(crate) use native::supports_redo;
pub(crate) use native::{create_dir, create_new, file_identity, is_reparse, open_lock, sync_dir, sync_file, volume};
pub(crate) use std::fs::rename as replace;
pub(crate) struct FileIdentity {
volume: u64,
id: u64,
pub(crate) links: u64,
}
impl PartialEq for FileIdentity {
fn eq(&self, other: &Self) -> bool {
self.volume == other.volume && self.id == other.id
}
}
#[cfg(unix)]
mod native {
use super::FileIdentity;
use std::{
fs::{DirBuilder, File, Metadata, OpenOptions},
io,
os::unix::fs::{DirBuilderExt as _, MetadataExt as _, OpenOptionsExt as _},
path::Path,
};
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
pub(crate) fn volume(_: &Path, metadata: &Metadata) -> io::Result<u64> {
Ok(metadata.dev())
}
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
pub(crate) fn file_identity(_: &Path, metadata: &Metadata) -> io::Result<FileIdentity> {
Ok(FileIdentity {
volume: metadata.dev(),
id: metadata.ino(),
links: metadata.nlink(),
})
}
pub(crate) const fn is_reparse(_: &Metadata) -> bool {
false
}
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
DirBuilder::new().mode(0o700).create(path)
}
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(path)
}
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
}
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
File::open(path)?.sync_all()
}
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
File::open(path)?.sync_all()
}
}
#[cfg(windows)]
mod native {
use super::FileIdentity;
use std::{
fs::{self, File, Metadata, OpenOptions},
io,
os::windows::{
ffi::OsStrExt as _,
fs::{MetadataExt as _, OpenOptionsExt as _},
io::AsRawHandle as _,
},
path::Path,
};
use windows_sys::Win32::{
Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, GetDriveTypeW, GetFileInformationByHandle,
GetVolumeInformationByHandleW, GetVolumePathNameW,
},
System::WindowsProgramming::DRIVE_FIXED,
};
fn path_wide(path: &Path) -> io::Result<Vec<u16>> {
let mut wide: Vec<_> = path.as_os_str().encode_wide().collect();
if wide.contains(&0) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path contains a NUL"));
}
wide.push(0);
Ok(wide)
}
fn open_attributes(path: &Path) -> io::Result<File> {
// Follow a named alias for identity checks. Managed paths are separately checked with symlink_metadata.
OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)
}
fn file_info(path: &Path) -> io::Result<BY_HANDLE_FILE_INFORMATION> {
let file = open_attributes(path)?;
let mut info = BY_HANDLE_FILE_INFORMATION::default();
// The output buffer and file handle remain valid for the call.
let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &raw mut info) };
if ok == 0 {
return Err(io::Error::last_os_error());
}
Ok(info)
}
pub(crate) fn volume(path: &Path, _: &Metadata) -> io::Result<u64> {
Ok(u64::from(file_info(path)?.dwVolumeSerialNumber))
}
pub(crate) fn file_identity(path: &Path, _: &Metadata) -> io::Result<FileIdentity> {
let info = file_info(path)?;
// The full NTFS file ID fits in 64 bits. ReFS is excluded by supports_redo.
Ok(FileIdentity {
volume: u64::from(info.dwVolumeSerialNumber),
id: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
links: u64::from(info.nNumberOfLinks),
})
}
pub(crate) fn is_reparse(metadata: &Metadata) -> bool {
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
}
pub(crate) fn supports_redo(root: &Path) -> io::Result<bool> {
let path = path_wide(root)?;
let mut volume = vec![0u16; 32_768];
// The input is NUL-terminated and the output buffer is writable for the stated length.
let ok = unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) };
if ok == 0 {
return Err(io::Error::last_os_error());
}
// GetVolumePathNameW returned a NUL-terminated volume root.
if unsafe { GetDriveTypeW(volume.as_ptr()) } != DRIVE_FIXED {
return Ok(false);
}
let file = open_attributes(root)?;
let mut filesystem = [0u16; 16];
// The handle remains live. Optional outputs are omitted, except for the writable filesystem buffer.
let ok = unsafe {
GetVolumeInformationByHandleW(
file.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
filesystem.as_mut_ptr(),
filesystem.len() as u32,
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
// MS-FSA 2.1.5.7 documents directory persistence on NTFS. Other filesystems can silently succeed.
Ok(filesystem.starts_with(&[u16::from(b'N'), u16::from(b'T'), u16::from(b'F'), u16::from(b'S'), 0]))
}
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
fs::create_dir(path)
}
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
}
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?
.sync_all()
}
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?
.sync_all()
}
}
@@ -1,97 +0,0 @@
#![cfg(any(unix, windows))]
use clash_verge_profile::IProfiles;
use clash_verge_profile_store::{CommitOutcome, Session};
use std::fs;
#[test]
fn refresh_creates_missing_body_for_legacy_index() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
fs::write(
root.join("profiles.yaml"),
"items:\n- {type: remote, url: 'https://example.invalid/sub'}\n",
)?;
let candidate = serde_yaml_ng::from_str(
"items:\n- {uid: assigned, type: remote, url: 'https://example.invalid/sub', file: 'Rnew.yaml', updated: 42}\n",
)?;
let body = b"# preserve comments\nproxies: []\n";
let outcome = Session::open(root)?.commit_refresh("assigned", &candidate, body);
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
let index: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
let stored_body = fs::read(root.join("profiles/Rnew.yaml"))?;
assert_eq!(index.get_item("assigned")?.updated, Some(42));
assert_eq!(index.get_item("assigned")?.file.as_deref(), Some("Rnew.yaml"));
assert_eq!(stored_body, body);
Ok(())
}
#[cfg(unix)]
#[test]
fn refresh_allows_an_unrelated_unix_filename() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
fs::write(root.join("profiles/r.yaml"), b"old")?;
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: 'office:old.yaml'}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
assert_eq!(fs::read(root.join("profiles/office:old.yaml"))?, b"local");
Ok(())
}
#[test]
fn refresh_rejects_legacy_path_alias_before_creating_body() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: './r.yaml'}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
assert!(matches!(
outcome,
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::InvalidFilename)
));
assert!(!root.join("profiles/r.yaml").exists());
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
Ok(())
}
#[cfg(all(unix, feature = "test-support"))]
#[test]
fn interrupted_creation_reverts_an_aliased_body() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
std::os::unix::fs::symlink("r.yaml", root.join("profiles/alias.yaml"))?;
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: alias.yaml}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |phase| {
if phase == "body-replaced" {
return Err(std::io::Error::other("interrupted after body replacement").into());
}
Ok(())
});
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)), "{outcome:?}");
assert_eq!(fs::read(root.join("profiles/r.yaml"))?, b"new");
let session = Session::open(root)?;
assert!(!root.join("profiles/r.yaml").exists());
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
let outcome = session.commit_refresh("r", &candidate, b"new");
assert!(matches!(
outcome,
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::AliasedBody)
));
Ok(())
}
-12
View File
@@ -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,
}
+6 -6
View File
@@ -78,7 +78,7 @@
"rehype-sanitize": "^6.0.0",
"swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
"tldts": "7.6.2",
"tldts": "7.6.4",
"types-pac": "^1.0.3",
"validator": "^13.15.35"
},
@@ -100,10 +100,10 @@
"cli-color": "^2.0.4",
"commander": "^15.0.0",
"cross-env": "^10.1.0",
"eslint": "^10.11.0",
"eslint": "^10.16.0",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-es-x": "^10.0.1",
"eslint-plugin-import-x": "^4.17.1",
"eslint-plugin-import-x": "^4.18.1",
"eslint-plugin-react-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
@@ -120,10 +120,10 @@
"terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0",
"typescript-eslint": "^8.74.0",
"vite": "^8.3.0",
"vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.1"
"vitest": "^5.0.3"
},
"lint-staged": {
"*.{ts,tsx,js,mjs}": [
@@ -135,5 +135,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.23.0"
"packageManager": "pnpm@12.25.1"
}
+893 -1043
View File
File diff suppressed because it is too large Load Diff
+7 -13
View File
@@ -22,7 +22,6 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"]
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
profile-store-windows = []
[package.metadata.bundle]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
@@ -31,7 +30,6 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
tauri-build = { version = "2.7.6", features = [] }
[dependencies]
tempfile = { workspace = true }
clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true }
@@ -39,10 +37,6 @@ clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true }
clash-verge-limiter = { workspace = true }
clash-verge-subscription = { workspace = true }
clash-verge-runtime-bundle = { workspace = true }
clash-verge-config-render = { workspace = true }
clash-verge-profile-script = { workspace = true }
clash-verge-proxy-view = { workspace = true }
clash-verge-profile = { workspace = true }
clash-verge-backup-archive = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true }
@@ -71,6 +65,7 @@ dirs = "7.0.0"
dunce = "1.0.5"
nanoid = "0.5"
chrono = { workspace = true }
boa_engine = "0.22.0"
http-body-util = "0.1.5"
percent-encoding = "2.3.2"
reqwest = { workspace = true }
@@ -84,11 +79,12 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = { workspace = true }
flate2 = "1.1.11"
reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" }
base64 = "0.23.1"
sha2 = { workspace = true }
sha2 = "0.11.2"
getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
@@ -99,7 +95,9 @@ tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
async-trait = "0.1.92"
clash_verge_service_ipc = { 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"
tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] }
@@ -107,13 +105,10 @@ webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
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"] }
specta-typescript = "=0.0.13"
[target.'cfg(any(unix, windows))'.dependencies]
clash-verge-profile-store = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2.191"
@@ -146,7 +141,6 @@ objc2-app-kit = { version = "0.3.2", features = [
] }
[target.'cfg(windows)'.dependencies]
zip = { workspace = true }
deelevate = { workspace = true }
quick-xml = "0.42.0"
runas = "=1.2.0"
+3 -3
View File
@@ -1,10 +1,10 @@
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
use crate::core::notify::NoticeStatus;
use crate::feat;
use crate::utils::dirs;
use crate::utils::{dirs, yaml_emitter};
use crate::{
cmd::StringifyErr as _,
config::{ClashInfo, Config, mihomo_yaml, profiles::profiles_save_file_safe},
config::{ClashInfo, Config, profiles::profiles_save_file_safe},
constants,
core::{
CoreManager, handle,
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
let yaml_str = 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()?;
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
+3 -11
View File
@@ -39,7 +39,6 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
#[specta::specta]
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
let draft = Config::profiles().await;
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let data = draft.data_arc();
Ok(data)
}
@@ -158,11 +157,8 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
pub async fn delete_profile(index: std::string::String) -> CmdResult {
let index: String = index.into();
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let profiles = Config::profiles().await;
let mut storage_guard = None;
let slot = &mut storage_guard;
let result = profiles
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
let original = candidate.clone();
@@ -181,13 +177,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
None
};
let current = candidate.current.clone();
*slot = Some(crate::config::profile_storage::write().await?);
cleanup_profile_files(plan.files).await;
Ok((candidate, Ok((should_update, current, guard))))
})
.await
.with_error_code("PROFILE_DELETE_FAILED")?;
drop(storage_guard);
let (should_update, current, config_update_guard) = match result {
Ok(result) => result,
Err(outcome) => {
@@ -220,9 +214,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
Config::profiles()
.await
.stringify_err()?;
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = profiles_save_file_safe().await {
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
@@ -396,7 +391,6 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
});
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let target_profile = profiles.current.as_ref();
@@ -464,7 +458,6 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
#[tauri::command]
#[specta::specta]
pub async fn view_profile(index: std::string::String) -> CmdResult {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
let file = profiles_ref
@@ -490,7 +483,6 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let file = {
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
+92 -10
View File
@@ -1,6 +1,14 @@
use super::CmdResult;
use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle};
use clash_verge_proxy_view::ProxyViewV1;
use crate::{
cmd::StringifyErr as _,
config::Config,
core::{
handle::Handle,
proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1},
},
};
use serde_yaml_ng::Mapping;
use std::collections::{BTreeMap, HashSet};
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
#[tauri::command]
@@ -19,16 +27,90 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
.stringify_err()
}
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
let mut seen = HashSet::new();
config
.and_then(|config| config.get("proxy-groups"))
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.get("name"))
.filter_map(|name| name.as_str())
.filter(|name| !name.is_empty() && *name != "GLOBAL")
.filter(|name| seen.insert(*name))
.map(str::to_owned)
.collect()
}
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope> {
let Some(config) = config else {
return BTreeMap::new();
};
let mut all_providers = config
.get("proxy-providers")
.and_then(|providers| providers.as_mapping())
.into_iter()
.flat_map(|providers| providers.keys())
.filter_map(|name| name.as_str())
.map(str::to_owned)
.collect::<Vec<_>>();
all_providers.sort();
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
config
.get("proxy-groups")
.and_then(|groups| groups.as_sequence())
.into_iter()
.flatten()
.filter_map(|group| group.as_mapping())
.filter_map(|group| {
let name = group.get("name")?.as_str()?.to_owned();
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
all_providers.clone()
} else {
group
.get("use")
.and_then(|providers| providers.as_sequence())
.into_iter()
.flatten()
.filter_map(|provider| provider.as_str())
.map(str::to_owned)
.collect()
};
let exclude_types = group
.get("exclude-type")
.and_then(|types| types.as_str())
.filter(|types| !types.is_empty())
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
Some((
name,
GroupScope {
providers,
exclude_types,
},
))
})
.collect()
}
#[tauri::command]
#[specta::specta]
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
let runtime = Config::runtime().await.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();
crate::feat::proxy_view::load_proxy_view(
runtime.config.as_ref(),
mihomo.get_proxies(),
mihomo.get_proxy_providers(),
)
.await
.stringify_err()
let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),);
let proxies = proxies.stringify_err()?;
Ok(ProxyViewBuilder::build(ProxyViewInput {
runtime_group_order,
group_scopes,
proxies,
providers: providers.ok(),
}))
}
+3 -7
View File
@@ -1,9 +1,5 @@
use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
config::{Config, mihomo_yaml},
core::CoreManager,
};
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager, utils::yaml_emitter};
use anyhow::{Context as _, anyhow};
use std::collections::HashMap;
use tristr::alias::String;
@@ -28,7 +24,7 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
let config = runtime.config.as_ref();
config
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
.and_then(|config| 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()
}
@@ -91,7 +87,7 @@ pub async fn get_runtime_proxy_chain_config(
config.insert("proxies".into(), proxies_chain);
mihomo_yaml::serialize_for_export(&config)
yaml_emitter::to_mihomo_config_string(&config)
.context("YAML generation failed")
.stringify_err()
} else {
+16 -30
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, profile_storage, profiles::PROFILE_WRITE_LOCK, read_profile_item_file},
config::{Config, IProfiles, read_profile_item_file},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
@@ -34,9 +34,6 @@ pub async fn save_profile_file(
_ => None,
};
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
let profile_guard = profile_storage::write().await.stringify_err()?;
// 在异步操作前获取必要元数据并释放锁
let (rel_path, is_merge_file, is_script_file, affects_runtime) = {
let profiles = Config::profiles().await;
@@ -68,18 +65,12 @@ pub async fn save_profile_file(
// 保存新的配置文件
fs::write(&file_path, &file_data).await.stringify_err()?;
drop(profile_guard);
let original = OriginalProfileFile {
content: &original_content,
existed: original_existed,
written: &file_data,
};
let changes_applied = handle_saved_profile_file(
&file_path_str,
&file_path,
&original,
&original_content,
original_existed,
is_merge_file,
is_script_file,
affects_runtime,
@@ -95,19 +86,13 @@ pub async fn save_profile_file(
Ok(changes_applied)
}
struct OriginalProfileFile<'a> {
content: &'a str,
existed: bool,
written: &'a str,
}
async fn restore_original(file_path: &std::path::Path, original: &OriginalProfileFile<'_>) -> CmdResult<()> {
let _guard = profile_storage::write().await.stringify_err()?;
if fs::read(file_path).await.stringify_err()? != original.written.as_bytes() {
return Err("profile file changed during validation".into());
}
if original.existed {
fs::write(file_path, original.content).await.stringify_err()
async fn restore_original(
file_path: &std::path::Path,
original_content: &str,
original_existed: bool,
) -> CmdResult<()> {
if original_existed {
fs::write(file_path, original_content).await.stringify_err()
} else {
fs::remove_file(file_path).await.stringify_err()
}
@@ -137,7 +122,8 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
async fn handle_saved_profile_file(
file_path_str: &str,
file_path: &std::path::Path,
original: &OriginalProfileFile<'_>,
original_content: &str,
original_existed: bool,
is_merge_file: bool,
is_script_file: bool,
affects_runtime: bool,
@@ -154,13 +140,13 @@ async fn handle_saved_profile_file(
Ok(outcome) if outcome.is_valid() => {}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
handle_validation_notice(&outcome, target, file_type);
return Ok(outcome);
}
Err(e) => {
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
return Err(e.to_string().into());
}
}
@@ -181,13 +167,13 @@ async fn handle_saved_profile_file(
}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
Ok(outcome)
}
Err(err) => {
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
Err(err.to_string().into())
}
}
+1 -4
View File
@@ -1,4 +1,3 @@
use super::mihomo_yaml;
use crate::constants::{network, tun as tun_const};
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
use crate::utils::{dirs, help};
@@ -151,9 +150,7 @@ impl IClashTemp {
}
pub async fn save_config(&self) -> Result<()> {
let path = dirs::clash_path()?;
let yaml = mihomo_yaml::serialize(&self.0)?;
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await
}
pub fn get_mixed_port(&self) -> u16 {
+9 -35
View File
@@ -1,10 +1,9 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{
prfitem::{build_merge_profile, build_script_profile},
profile_storage,
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles_unlocked},
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
runtime::IRuntime,
},
constants::{files, timing},
@@ -12,6 +11,7 @@ use crate::{
CoreManager,
handle::{self, Handle},
listener::MIXED_PORT_KEY,
runtime_bundle::resolve_provider_path_conflicts,
tray,
validate::CoreConfigValidator,
},
@@ -23,7 +23,6 @@ use anyhow::{Result, anyhow};
use backon::{ExponentialBuilder, Retryable as _};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
use serde_yaml_ng::{Mapping, Value};
use std::{collections::HashSet, path::PathBuf};
use tokio::sync::{Mutex, MutexGuard, OnceCell};
@@ -85,7 +84,6 @@ impl Config {
}
pub async fn init_config_before_window() -> Result<()> {
profile_storage::check()?;
Self::ensure_default_profile_items().await?;
let verge = Self::verge().await.latest_arc();
@@ -232,7 +230,7 @@ impl Config {
{
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)));
Ok(yaml_str)
})
@@ -247,24 +245,12 @@ impl Config {
}
pub async fn generate() -> Result<()> {
let profiles = Self::profiles().await;
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(&profiles.latest_arc()).await?
};
Self::generate_from_inputs(inputs).await
let profiles = Self::profiles().await.latest_arc();
Self::generate_with_profiles(&profiles).await
}
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(profiles).await?
};
Self::generate_from_inputs(inputs).await
}
async fn generate_from_inputs(inputs: enhance::ProfileRenderInputs) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(inputs).await;
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?;
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
sanitize_tunnels_proxy(&mut config);
@@ -327,20 +313,8 @@ impl Config {
let save_profiles_task = AsyncHandler::spawn(|| async {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await;
let mut storage_guard = None;
let slot = &mut storage_guard;
let draft = &profiles;
let result = profiles
.with_data_modify(|_| async move {
*slot = Some(profile_storage::write().await?);
let candidate = (**draft.latest_arc()).clone();
let saved = save_profiles_unlocked(&candidate).await;
draft.discard();
Ok((candidate, saved))
})
.await;
drop(storage_guard);
logging_error!(Type::Config, result.and_then(std::convert::identity));
profiles.apply();
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
});
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
+3 -3
View File
@@ -3,18 +3,18 @@ mod clash;
mod config;
pub(crate) mod dns;
mod encrypt;
pub(crate) mod mihomo_yaml;
mod mixed_port;
mod port;
mod prfitem;
pub(crate) mod profile_storage;
pub mod profiles;
pub mod runtime;
pub(crate) mod snapshot;
mod verge;
pub(crate) use self::config::Config;
pub(crate) use self::prfitem::{build_remote_profile, download_subscription, read_profile_item_file};
pub(crate) use self::prfitem::{
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};
-205
View File
@@ -1,205 +0,0 @@
use anyhow::{Result, anyhow};
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
use parking_lot::Mutex;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
enum StorageBlock {
Transaction(String),
Restore(String),
}
pub(crate) fn check() -> Result<()> {
match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
}
None => Ok(()),
}
}
pub(crate) fn block(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
}
}
pub(crate) fn block_restore(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Restore(format!("{error:#}")));
}
}
pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>, bool)> {
let guard = PROFILE_IO.write().await;
let retry = match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason)) => {
return Err(anyhow!("Profile storage requires recovery before use: {reason}"));
}
Some(StorageBlock::Restore(_)) => true,
None => false,
};
Ok((guard, retry))
}
pub(crate) fn finish_restore(_guard: &RwLockWriteGuard<'_, ()>) {
let mut blocked = BLOCKED.lock();
if matches!(*blocked, Some(StorageBlock::Restore(_))) {
*blocked = None;
}
}
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
let guard = PROFILE_IO.read().await;
check()?;
Ok(guard)
}
pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
let guard = PROFILE_IO.write().await;
check()?;
Ok(guard)
}
pub(crate) async fn recover_at_startup() -> Result<()> {
let _guard = write().await?;
let root = crate::utils::dirs::app_home_dir().inspect_err(block)?;
let result: Result<()> = async {
if !journal_exists(&root).await? {
return Ok(());
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root))
.await?
.map_err(Into::into);
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
return Err(anyhow!(
"restore the pending profile transaction with redo support enabled"
));
}
.await;
if let Err(error) = &result {
block(error);
}
result
}
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
match tokio::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)).await {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
pub(super) async fn commit_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return commit_recoverable_refresh(uid, candidate, body).await;
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
{
write_legacy_refresh(&uid, &candidate, body.as_bytes()).await?;
Ok(candidate)
}
}
#[cfg(not(unix))]
async fn write_legacy_refresh(uid: &str, candidate: &super::IProfiles, body: &[u8]) -> Result<()> {
use anyhow::Context as _;
let file = candidate
.get_item(uid)?
.file
.as_deref()
.context("missing profile filename")?;
let path = crate::utils::dirs::app_profiles_dir()?.join(file);
tokio::fs::write(path, body)
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
super::profiles::save_profiles_unlocked(candidate).await
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
async fn commit_recoverable_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
use clash_verge_profile_store::{CommitOutcome, Session};
let root = crate::utils::dirs::app_home_dir()?;
#[cfg(windows)]
{
let probe_root = root.clone();
let supported =
tokio::task::spawn_blocking(move || clash_verge_profile_store::supports_redo(&probe_root)).await??;
if !supported {
if journal_exists(&root).await? {
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
block(&error);
return Err(error);
}
write_legacy_refresh(&uid, &candidate, body.as_bytes()).await?;
return Ok(candidate);
}
}
let result = tokio::task::spawn_blocking(move || {
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
_ => block(error),
}
})?;
let item = candidate.get_item(&uid)?;
if let Some(file) = item.file.as_deref()
&& !file.contains(['/', '\\', ':', '\0'])
&& !matches!(file, "" | "." | "..")
{
let path = root.join("profiles").join(file);
match std::fs::symlink_metadata(&path) {
Ok(metadata) if metadata.is_file() => {
std::fs::OpenOptions::new().write(true).open(&path)?;
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
CommitOutcome::Committed => Ok(candidate),
CommitOutcome::CommittedCleanupPending(error) => {
block(&error.into());
Ok(candidate)
}
CommitOutcome::Retryable(error) => {
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
}
CommitOutcome::RetryCleanupFailed(error) => {
let error = anyhow::Error::from(error);
block(&error);
Err(error.context("failed to discard the incomplete profile refresh"))
}
CommitOutcome::NeedsRecovery(error) => {
let error = anyhow::Error::from(error);
block(&error);
Err(error.context("profile refresh requires recovery"))
}
}
})
.await;
match result {
Ok(result) => result,
Err(error) => {
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
block(&error);
Err(error)
}
}
}
+68 -112
View File
@@ -1,7 +1,6 @@
use super::{
PrfItem, PrfOption, PrfSelected, patch_opt_field,
prfitem::{DownloadedSubscription, RemoteProfileRefresh, build_profile, prepare_remote_refresh},
profile_storage,
prfitem::{RemoteProfileRefresh, build_profile},
};
use crate::core::notify::{Refresh, announce};
use crate::{
@@ -71,57 +70,52 @@ pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
}
pub(crate) async fn load_profiles() -> IProfiles {
match load_profiles_checked().await {
Ok(profiles) => profiles,
Err(error) => {
logging!(error, Type::Config, "failed to load profiles: {error:#}");
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return IProfiles::default();
}
};
match help::read_yaml::<IProfiles>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
profiles
}
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
IProfiles::default()
}
}
}
pub(crate) async fn load_profiles_checked() -> Result<IProfiles> {
profile_storage::check()?;
load_profiles_unlocked().await
}
pub(crate) async fn load_profiles_unlocked() -> Result<IProfiles> {
let mut profiles: IProfiles = help::read_yaml(&dirs::profiles_path()?).await?;
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles_unlocked(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
Ok(profiles)
}
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
let _guard = profile_storage::write().await?;
save_profiles_unlocked(profiles).await
}
pub(crate) async fn save_profiles_unlocked(profiles: &IProfiles) -> Result<()> {
help::save_yaml(
&dirs::profiles_path()?,
profiles,
@@ -183,7 +177,7 @@ async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Resu
bail!("failed to find the profile item \"uid:{uid}\"")
}
pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
@@ -199,22 +193,30 @@ pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
Ok(())
}
fn stage_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: &RemoteProfileRefresh) -> Result<()> {
/// Updates fields returned by a remote profile refresh.
async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> {
let _ = profiles.get_item(uid)?;
if let Some(item) = profiles
if let Some(each) = profiles
.items
.iter_mut()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
{
item.extra = refresh.extra;
item.updated = Some(refresh.updated);
item.home = refresh.home.clone();
item.option = PrfOption::merge(item.option.as_ref(), Some(&refresh.option));
item.file
each.extra = refresh.extra;
each.updated = Some(refresh.updated);
each.home = refresh.home;
each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option));
let file = each
.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
Ok(())
save_profiles(profiles).await
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
@@ -285,7 +287,6 @@ pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()>
pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
let _guard = profile_storage::write().await?;
append_item(&mut profiles, item).await?;
Ok((profiles, ()))
})
@@ -314,62 +315,17 @@ pub(crate) async fn profiles_save_file_safe() -> Result<()> {
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
fn check_refresh_source(profiles: &IProfiles, uid: &str, url: &str, file: Option<&String>) -> Result<()> {
let current = profiles.get_item(uid)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote")
&& current.url.as_deref() == Some(url)
&& current.file.as_ref() == file,
"profile source or filename changed during refresh"
);
Ok(())
}
pub(crate) async fn apply_remote_refresh_safe(
uid: &str,
url: &str,
file: Option<String>,
downloaded: DownloadedSubscription,
options: Option<PrfOption>,
) -> Result<()> {
let uid = uid.to_owned();
let url = url.to_owned();
// Dropping the caller must not separate an issued disk write from its Draft publication.
tokio::spawn(async move {
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
let draft = Config::profiles().await;
check_refresh_source(&draft.data_arc(), &uid, &url, file.as_ref())?;
let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?;
let mut storage_guard = None;
let mut persisted = false;
let result = {
let storage_guard = &mut storage_guard;
let persisted = &mut persisted;
draft
.with_data_modify(|mut candidate| async move {
*storage_guard = Some(profile_storage::write().await?);
check_refresh_source(&candidate, &uid, &url, file.as_ref())?;
stage_remote_refresh(&mut candidate, &uid, &refresh)?;
let candidate = profile_storage::commit_refresh(uid, candidate, refresh.body).await?;
*persisted = true;
Ok((candidate, ()))
})
.await
};
if let Err(error) = &result
&& persisted
{
profile_storage::block(error);
return Err(anyhow::anyhow!(
"Profile refresh is saved, but its Draft could not be published: {error:#}"
));
}
drop(storage_guard);
result?;
profile_storage::check().context("Profile refresh was saved")
pub(crate) async fn apply_remote_refresh_safe(index: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
let current = profiles.get_item(index)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
"profile source changed during refresh"
);
apply_remote_refresh(&mut profiles, index, refresh).await?;
Ok(profiles)
})
.await?
.await
}
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
+1 -1
View File
@@ -2,7 +2,7 @@ use serde_yaml_ng::{Mapping, Value};
use std::collections::{HashMap, HashSet};
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"];
+17
View File
@@ -64,5 +64,22 @@ pub mod files {
pub mod tun {
pub const DEFAULT_STACK: &str = "mips";
pub const DEFAULT_MTU: u16 = 1500;
pub const DNS_HIJACK: &[&str] = &["any:53"];
/// Saved dialog fields; `enable` belongs to the verge switch.
pub const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
}
+15 -15
View File
@@ -277,22 +277,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
let mut archive = BackupWriter::new(file)?;
let profile_guard = crate::config::profile_storage::read().await?;
let mut entries = fs::read_dir(dirs::app_profiles_dir()?).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let mut entry = archive.start_profile(file_name)?;
let file_content = fs::read(&path).await?;
entry.write_all(&file_content)?;
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let mut entry = archive.start_profile(file_name)?;
let file_content = fs::read(&path).await?;
entry.write_all(&file_content)?;
}
}
}
let profile_index = fs::read(dirs::profiles_path()?).await?;
drop(profile_guard);
archive
.start_file(dirs::CLASH_CONFIG)?
@@ -316,7 +314,9 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
.write_all(&fs::read(&dns_config_path).await?)?;
}
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
archive
.start_file(dirs::PROFILE_YAML)?
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
archive.finish()?;
Ok((zip_file_name, zip_path))
}
+2 -3
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
constants::timing,
core::{
handle,
@@ -170,8 +170,7 @@ impl CoreManager {
}
});
let yaml = mihomo_yaml::serialize(clash_config)?;
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice(status, message);
Ok(())
}
-2
View File
@@ -231,8 +231,6 @@ impl CoreManager {
pub async fn init(&self) -> Result<bool> {
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
crate::config::profile_storage::check()?;
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
}
+1 -2
View File
@@ -35,7 +35,6 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
#[cfg(target_os = "windows")]
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
use crate::config::mihomo_yaml;
use serde_yaml_ng::{Mapping, Value};
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
@@ -48,7 +47,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
tun.as_mapping_mut()
.context("invalid Sidecar TUN configuration")?
.insert(Value::from("enable"), Value::Bool(false));
Ok(mihomo_yaml::serialize(&config)?)
Ok(serde_yaml_ng::to_string(&config)?)
}
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
+2
View File
@@ -11,7 +11,9 @@ pub mod network_watch;
pub mod notify;
pub(crate) mod owner_identity;
pub mod proxy_control;
pub mod proxy_view;
pub mod runstate;
pub(crate) mod runtime_bundle;
pub mod service;
pub mod sysopt;
pub mod timer;
@@ -1,40 +1,15 @@
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::collections::{BTreeMap, BTreeSet};
use serde::Serialize;
use tristr::alias::String;
use tauri_plugin_mihomo::models::{
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
};
pub struct ProxyViewInput {
pub runtime_group_order: Vec<String>,
pub group_scopes: BTreeMap<String, GroupScope>,
pub proxies: HashMap<String, ProxySnapshot>,
pub providers: Option<HashMap<String, ProviderSnapshot>>,
}
pub struct ProxySnapshot {
pub name: String,
pub proxy_type: String,
pub all: Option<Vec<String>>,
pub fixed: Option<String>,
pub hidden: Option<bool>,
pub icon: Option<String>,
pub now: Option<String>,
pub test_url: Option<String>,
pub id: Option<String>,
pub history: Vec<DelayHistory>,
pub capabilities: ProxyCapabilities,
}
pub struct ProviderSnapshot {
pub vehicle_type: ProxyProviderVehicleType,
pub proxies: Vec<ProxySnapshot>,
pub updated_at: Option<String>,
pub subscription_info: Option<ProxySubscriptionInfo>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
pub proxies: Proxies,
pub providers: Option<ProxyProviders>,
}
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
@@ -87,7 +62,8 @@ pub struct ProxyCapabilities {
pub struct ProxyGroupView {
pub name: String,
#[serde(rename = "type")]
pub proxy_type: String,
#[specta(type = String)]
pub proxy_type: ProxyType,
#[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -98,6 +74,7 @@ pub struct ProxyGroupView {
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>,
#[serde(flatten)]
pub capabilities: ProxyCapabilities,
@@ -110,7 +87,9 @@ pub struct ProxyNodeView {
pub record_id: String,
pub name: String,
#[serde(rename = "type")]
pub proxy_type: String,
#[specta(type = String)]
pub proxy_type: ProxyType,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
@@ -221,13 +200,12 @@ impl<'a> MemberResolver<'a> {
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
.map(|(_, record_id)| record_id)
.filter(|record_id| {
scope.exclude_types.is_empty()
|| !self.records.get(*record_id).is_some_and(|node| {
scope
.exclude_types
.iter()
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
!self.records.get(*record_id).is_some_and(|node| {
scope
.exclude_types
.iter()
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
})
.collect()
}
@@ -292,7 +270,7 @@ impl ProxyViewBuilder {
let global = core_groups
.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 direct = core_node_ids.get("DIRECT").cloned();
let standalone = build_standalone(&core_node_ids);
@@ -311,13 +289,11 @@ impl ProxyViewBuilder {
}
}
fn partition_core(
proxies: HashMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) {
let mut groups = BTreeMap::new();
let mut nodes = BTreeMap::new();
for (name, proxy) in proxies {
for (name, proxy) in proxies.proxies {
if proxy.all.is_some() {
groups.insert(name, proxy);
} else {
@@ -329,13 +305,13 @@ fn partition_core(
}
fn build_core_records(
core_nodes: BTreeMap<String, ProxySnapshot>,
core_nodes: BTreeMap<String, Proxy>,
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
let mut records = BTreeMap::new();
let mut ids = BTreeMap::new();
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
let record_id: String = format!("c:{index}").into();
let record_id = format!("c:{index}");
ids.insert(name.clone(), record_id.clone());
records.insert(
record_id.clone(),
@@ -352,25 +328,32 @@ fn build_core_records(
}
fn build_provider_records(
providers: Option<HashMap<String, ProviderSnapshot>>,
providers: Option<ProxyProviders>,
records: &mut BTreeMap<String, ProxyNodeView>,
) -> (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 candidates = BTreeMap::new();
for (provider_name, provider) in providers {
let ProviderSnapshot {
let ProxyProvider {
vehicle_type,
proxies,
updated_at,
subscription_info,
..
} = provider;
let vehicle_type = match vehicle_type {
VehicleType::HTTP => ProxyProviderVehicleType::Http,
VehicleType::File => ProxyProviderVehicleType::File,
VehicleType::Inline => ProxyProviderVehicleType::Inline,
_ => continue,
};
let provider_index = views.len();
let mut proxy_record_ids = Vec::new();
for (member_index, proxy) in proxies.into_iter().enumerate() {
let record_id: String = format!("p:{provider_index}:{member_index}").into();
let record_id = format!("p:{provider_index}:{member_index}");
let proxy_name = proxy.name.clone();
let node_name = proxy.name.clone();
candidates
@@ -396,7 +379,12 @@ fn build_provider_records(
name: provider_name,
vehicle_type,
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,
});
}
@@ -404,8 +392,8 @@ fn build_provider_records(
(views, candidates)
}
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let ProxySnapshot {
fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let Proxy {
all,
fixed,
hidden,
@@ -413,7 +401,11 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
now,
test_url,
history,
capabilities,
udp,
xudp,
tfo,
mptcp,
smux,
proxy_type,
..
} = proxy;
@@ -441,19 +433,29 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
icon,
test_url,
history,
capabilities,
capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
members,
}
}
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
let ProxySnapshot {
fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView {
let Proxy {
id,
hidden,
icon,
test_url,
history,
capabilities,
udp,
xudp,
tfo,
mptcp,
smux,
proxy_type,
..
} = proxy;
@@ -467,13 +469,19 @@ fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: Pro
hidden,
icon,
test_url,
capabilities,
capabilities: ProxyCapabilities {
udp,
xudp,
tfo,
mptcp,
smux,
},
source,
}
}
fn build_ordered_groups(
mut core_groups: BTreeMap<String, ProxySnapshot>,
mut core_groups: BTreeMap<String, Proxy>,
runtime_group_order: Vec<String>,
resolver: &MemberResolver<'_>,
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
@@ -1,15 +1,12 @@
mod error;
pub use error::RuntimeBundleError;
use anyhow::{Context as _, Result, bail};
use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256};
use std::collections::{BTreeMap, HashSet};
use std::path::{Component, Path, PathBuf, Prefix};
use tristr::TriStr;
pub const GEO_ASSETS: &[&str] = &[
pub(crate) const GEO_ASSETS: &[&str] = &[
"Country.mmdb",
"ASN.mmdb",
"geoip.dat",
@@ -20,62 +17,42 @@ pub const GEO_ASSETS: &[&str] = &[
/// Provider identity used by the runtime config and core API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteProviderRef {
pub(crate) struct RemoteProviderRef {
pub section: &'static str,
pub name: String,
pub destination: TriStr,
pub url: String,
pub provider: RemoteProvider,
}
pub struct RuntimeAsset {
pub source: String,
pub destination: TriStr,
struct RuntimeParts {
config: Value,
assets: Vec<RuntimeAsset>,
remote_providers: Vec<RemoteProviderRef>,
}
pub struct RuntimeBundlePlan {
pub config: Value,
pub assets: Vec<RuntimeAsset>,
pub remote_providers: Vec<RemoteProviderRef>,
}
type Result<T> = std::result::Result<T, RuntimeBundleError>;
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> {
let yaml = tokio::fs::read_to_string(config_file)
.await
.map_err(|source| RuntimeBundleError::ReadConfig {
path: config_file.to_owned(),
source,
})?;
let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
path: config_file.to_owned(),
source,
})?;
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
collect_runtime_parts(config, config_root)
.with_context(|| format!("failed to read runtime config {config_file:?}"))?;
let config: Value =
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?;
let config_root = config_file
.parent()
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?;
let parts = collect_runtime_parts(config, config_root)?;
Ok(RuntimeBundle {
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?,
assets: parts.assets,
remote_providers: parts
.remote_providers
.into_iter()
.map(|declared| declared.provider)
.collect(),
core_path: core_path.to_string_lossy().into_owned(),
})
}
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
let config_root = std::fs::canonicalize(config_root)?;
let mut destinations = HashSet::new();
let mut remote_providers = Vec::new();
for section in ["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)
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
}
#[derive(Default)]
@@ -84,10 +61,10 @@ struct ProviderPathOwners {
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 mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
let mut paths = BTreeMap::<String, ProviderPathOwners>::new();
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect();
for section in ["proxy-providers", "rule-providers"] {
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
continue;
@@ -107,7 +84,6 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
let Ok(destination) = destination else {
continue;
};
let destination = TriStr::from(destination.as_str());
reserved.insert(destination.clone());
let owners = paths.entry(destination).or_default();
match (is_remote, provider.get("url").and_then(Value::as_str)) {
@@ -141,12 +117,12 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
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();
digest.update(destination.as_bytes());
digest.update([0]);
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 extension = path
.extension()
@@ -158,7 +134,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
.to_string_lossy()
.replace('\\', "/");
if reserved.insert(TriStr::from(candidate.as_str())) {
if reserved.insert(candidate.clone()) {
return candidate;
}
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 mut assets = Vec::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);
for filename in GEO_ASSETS {
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 {
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
destination: (*filename).into(),
destination: (*filename).to_string(),
});
}
}
Ok(RuntimeBundlePlan {
Ok(RuntimeParts {
config,
assets,
remote_providers,
@@ -212,7 +188,7 @@ fn collect_provider_assets(
config: &mut Value,
section: &'static str,
config_root: &Path,
destinations: &mut HashSet<TriStr>,
destinations: &mut HashSet<String>,
assets: &mut Vec<RuntimeAsset>,
remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<()> {
@@ -225,103 +201,80 @@ fn collect_provider_assets(
};
for (name, provider) in providers.iter_mut() {
if let Some(destination) = plan_provider(
section,
name,
provider,
config_root,
destinations,
Some(assets),
remote_providers,
)? && let Some(provider) = provider.as_mapping_mut()
{
provider.insert(Value::String("path".to_owned()), Value::String(destination));
}
}
Ok(())
}
fn plan_provider(
section: &'static str,
name: &Value,
provider: &Value,
config_root: &Path,
destinations: &mut HashSet<TriStr>,
assets: Option<&mut Vec<RuntimeAsset>>,
remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<Option<String>> {
let Some(raw_path) = provider
.as_mapping()
.and_then(|provider| provider.get("path"))
.and_then(Value::as_str)
else {
return Ok(None);
};
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Reserve remote destinations too; copied and downloaded files must not collide.
let reserved = TriStr::from(destination.as_str());
if destinations.insert(reserved.clone()) {
remote_providers.push(RemoteProviderRef {
section,
name: name.as_str().unwrap_or_default().to_owned(),
destination: reserved,
url: url.to_owned(),
});
} else {
let Some(provider) = provider.as_mapping_mut() else {
continue;
};
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else {
continue;
};
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str).map(str::to_owned);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Reserve remote destinations too; copied and downloaded files must not collide.
match remote_providers
.iter()
.find(|declared| declared.destination == destination)
.find(|declared| declared.provider.destination == destination)
{
Some(declared) if declared.url == url => {}
Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
Some(declared) if declared.provider.url == url => {}
Some(_) => {
bail!("runtime provider destination {destination:?} is declared for two different sources")
}
None => {
if !destinations.insert(destination.clone()) {
bail!("runtime provider destination {destination:?} is claimed more than once");
}
remote_providers.push(RemoteProviderRef {
section,
name: name.as_str().unwrap_or_default().to_owned(),
provider: RemoteProvider {
destination: destination.clone(),
url,
},
});
}
}
destination
}
destination
}
(true, None) => {
logging!(
warn,
Type::Config,
"remote provider {name:?} declares no url; leaving its path to the core"
);
return Ok(None);
}
(false, _) => {
let Ok(source) = local_provider_source(config_root, raw_path) else {
(true, None) => {
logging!(
warn,
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);
};
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,
});
continue;
}
destination
}
};
Ok(Some(destination))
(false, _) => {
let Ok(source) = local_provider_source(config_root, raw_path) else {
logging!(
warn,
Type::Config,
"local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
);
continue;
};
let destination = destination_below_root(config_root, &source)?;
if destinations.insert(destination.clone()) {
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.
fn collect_ssh_private_keys(
config: &mut Value,
config_root: &Path,
destinations: &mut HashSet<TriStr>,
destinations: &mut HashSet<String>,
assets: &mut Vec<RuntimeAsset>,
) {
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);
assets.push(RuntimeAsset {
source,
destination: TriStr::from(destination.as_str()),
destination: destination.clone(),
});
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)
};
let canonical_source =
std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
path: source,
source: error,
})?;
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?;
canonical_source
.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)
}
@@ -410,7 +360,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
.components()
.any(|component| matches!(component, Component::ParentDir))
{
return Err(RuntimeBundleError::DestinationOutsideRuntime);
bail!("runtime provider destination traverses outside the runtime");
}
if path.is_absolute() {
let normalized = canonicalize_with_missing_tail(path)?;
@@ -426,11 +376,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
while !ancestor.exists() {
let name = ancestor
.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());
ancestor = ancestor
.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)?;
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> {
let relative = path
.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)
}
@@ -452,11 +402,11 @@ fn normalized_destination(relative: &Path) -> Result<String> {
match component {
Component::Normal(component) => destination.push(component),
Component::CurDir => {}
_ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
_ => bail!("local runtime provider destination traverses outside the runtime"),
}
}
if destination.as_os_str().is_empty() {
return Err(RuntimeBundleError::EmptyDestination);
bail!("local runtime provider destination is empty");
}
Ok(destination.to_string_lossy().replace('\\', "/"))
}
@@ -466,8 +416,7 @@ mod tests {
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
#[tokio::test]
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
-> std::result::Result<(), Box<dyn std::error::Error>> {
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> {
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
std::fs::create_dir_all(&root)?;
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
@@ -484,7 +433,7 @@ mod tests {
resolve_provider_path_conflicts(&mut config, &root)?;
let config_file = root.join("config.yaml");
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
let bundle = collect_runtime_bundle(&config_file).await?;
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?;
let paths = &config["rule-providers"];
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
resolve_provider_path_conflicts(&mut reordered, &root)?;
@@ -499,14 +448,14 @@ mod tests {
"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)?;
assert_eq!(bundle.remote_providers.len(), 2);
for declared in readback {
assert!(bundle.remote_providers.contains(&declared));
assert!(bundle.remote_providers.contains(&declared.provider));
assert_eq!(
config[declared.section][&declared.name]["path"],
declared.destination.as_str()
declared.provider.destination
);
assert_eq!(
config[declared.section][&declared.name]["url"],
@@ -518,8 +467,7 @@ mod tests {
}
#[test]
fn allocated_provider_paths_do_not_claim_another_declared_path()
-> std::result::Result<(), Box<dyn std::error::Error>> {
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> {
let root = std::env::temp_dir();
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
@@ -541,8 +489,7 @@ mod tests {
}
#[test]
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
-> std::result::Result<(), Box<dyn std::error::Error>> {
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> {
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",
)?;
@@ -553,8 +500,7 @@ mod tests {
}
#[tokio::test]
async fn collects_only_local_providers_and_existing_geo_assets()
-> std::result::Result<(), Box<dyn std::error::Error>> {
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
std::fs::create_dir_all(root.join("providers"))?;
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
@@ -570,10 +516,12 @@ mod tests {
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!(
bundled_config["proxy-providers"]["local"]["path"].as_str(),
Some("providers/local.yaml")
@@ -582,7 +530,7 @@ mod tests {
bundled_config["proxy-providers"]["remote"]["path"].as_str(),
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!(
bundle
.assets
@@ -612,8 +560,7 @@ mod tests {
}
#[tokio::test]
async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
-> std::result::Result<(), Box<dyn std::error::Error>> {
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
// Identical repeats are one service-side file and are safe to fold.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
@@ -623,8 +570,10 @@ mod tests {
&config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config).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[0].destination, "rules/x.yaml");
@@ -633,7 +582,7 @@ mod tests {
}
#[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 _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?;
@@ -642,9 +591,11 @@ mod tests {
&config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config).await else {
return Err("two sources cannot own one file".into());
let Err(error) = collect_runtime_bundle(&config, &core).await else {
anyhow::bail!("two sources cannot own one file");
};
assert!(error.to_string().contains("two different sources"), "{error}");
@@ -653,8 +604,7 @@ mod tests {
}
#[tokio::test]
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
-> std::result::Result<(), Box<dyn std::error::Error>> {
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
// Odd providers accepted by mihomo must not block the rest of the bundle.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
@@ -664,8 +614,10 @@ mod tests {
&config,
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config).await?;
let bundle = collect_runtime_bundle(&config, &core).await?;
assert_eq!(
bundle.remote_providers.len(),
@@ -673,8 +625,9 @@ mod tests {
"only the provider that could be classified is declared"
);
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
assert_eq!(
bundle.config["rule-providers"]["nourl"]["path"].as_str(),
reserialized["rule-providers"]["nourl"]["path"].as_str(),
Some("./rules/nourl.yaml"),
"an unclassifiable provider keeps the path the core was given"
);
@@ -683,13 +636,13 @@ mod tests {
}
#[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()));
std::fs::create_dir_all(&root)?;
let config = root.join("config.yaml");
let outside = root
.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()));
std::fs::write(
&config,
@@ -698,9 +651,11 @@ mod tests {
outside.display()
),
)?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config).await else {
return Err("outside provider path must be rejected".into());
let Err(error) = collect_runtime_bundle(&config, &core).await else {
anyhow::bail!("outside provider path must be rejected");
};
assert!(error.to_string().contains("outside the config root"));
+11 -31
View File
@@ -1,7 +1,7 @@
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
use crate::{
config::{Config, mihomo_yaml, runtime::IRuntime},
config::{Config, runtime::IRuntime},
constants,
core::{
CoreManager,
@@ -13,6 +13,7 @@ use crate::{
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
},
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
tray::Tray,
},
process::AsyncHandler,
@@ -20,11 +21,10 @@ use crate::{
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
use clash_verge_service_ipc::{
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
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_path = service_core_path(&clash_core, bin_ext)?;
let plan = collect_runtime_bundle(config_file).await?;
Ok(RuntimeBundle {
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
assets: plan
.assets
.into_iter()
.map(|asset| RuntimeAsset {
source: asset.source,
destination: asset.destination.into(),
})
.collect(),
remote_providers: plan
.remote_providers
.into_iter()
.map(|provider| RemoteProvider {
destination: provider.destination.into(),
url: provider.url,
})
.collect(),
core_path: bin_path.to_string_lossy().into_owned(),
})
collect_runtime_bundle(config_file, &bin_path).await
}
/// 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 mut fetched = Vec::new();
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,
Err(error) => {
logging!(warn, Type::Service, "{error:#}");
@@ -976,7 +956,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
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 {
declared,
temp,
@@ -997,7 +977,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
warn,
Type::Service,
"failed to read provider cache {} into {}: {error:#}",
declared.destination,
declared.provider.destination,
temp.display()
);
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>> {
let applied = runtime.data_arc();
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()),
}
}
@@ -1137,7 +1117,7 @@ async fn publish_fetched(
};
let mut synced = 0;
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 {
remove_temp(&cache.temp).await;
continue;
@@ -1214,7 +1194,7 @@ async fn recheck_identity(
cache: &FetchedCache,
) -> Result<Fetch> {
let request = RuntimeFileRequest {
destination: cache.declared.destination.as_str().to_owned(),
destination: cache.declared.provider.destination.to_owned(),
offset: cache.len,
};
Ok(match read_chunk(credentials, session, &request).await? {
+19 -6
View File
@@ -16,7 +16,6 @@ use crate::core::handle;
use crate::singleton;
use crate::utils::{dirs, help};
use clash_verge_logging::{Type, logging};
use clash_verge_profile_script::MainDeclaration;
const SYNTAX_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
@@ -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)));
// 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| {
clash_verge_runtime_bundle::GEO_ASSETS
super::runtime_bundle::GEO_ASSETS
.iter()
.map(move |asset| dir.join(asset))
});
@@ -256,8 +255,22 @@ impl CoreConfigValidator {
};
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
let syntax =
crate::process::AsyncHandler::spawn_blocking(move || clash_verge_profile_script::validate(&content));
let has_main =
content.contains("function main") || content.contains("const main") || content.contains("let main");
// Boa parsing is pure CPU; keep it off the async worker, with a timeout.
let syntax = crate::process::AsyncHandler::spawn_blocking(move || {
use boa_engine::{Context, Source};
let mut context = Context::default();
let _ = context.eval(Source::from_bytes(
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){}});",
));
context
.eval(Source::from_bytes(&content))
.map(|_| ())
.map_err(|err| err.to_string())
});
let result = match tokio::time::timeout(SYNTAX_CHECK_TIMEOUT, syntax).await {
Ok(Ok(evaluated)) => evaluated,
Ok(Err(join_err)) => Err(format!("syntax check task failed: {join_err}")),
@@ -265,10 +278,10 @@ impl CoreConfigValidator {
};
match result {
Ok(main) => {
Ok(()) => {
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
if main == MainDeclaration::Missing {
if !has_main {
let error_msg = "Script must contain a main function";
logging!(warn, Type::Validate, "脚本缺少main函数: {}", path);
return Ok(ValidationOutcome::invalid_from_message(error_msg));
+18 -1
View File
@@ -1,14 +1,31 @@
use super::SeqMap;
use crate::{
config::PrfItem,
utils::{dirs, help},
};
use clash_verge_config_render::{ChainItem, ChainType, SeqMap};
use parking_lot::Mutex;
use serde_yaml_ng::Mapping;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock};
use std::time::SystemTime;
use tokio::fs;
use tristr::alias::String;
#[derive(Debug)]
pub struct ChainItem {
pub uid: String,
pub data: ChainType,
}
#[derive(Debug)]
pub enum ChainType {
Merge(Mapping),
Script(String),
Rules(SeqMap),
Proxies(SeqMap),
Groups(SeqMap),
}
struct CachedChain {
mtime: SystemTime,
@@ -18,21 +18,19 @@ pub const HANDLE_FIELDS: [&str; 12] = [
pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"];
fn lowercase_key(key: &str) -> Value {
let mut key = String::from(key);
key.make_ascii_lowercase();
Value::from(key.as_str())
}
pub fn use_lowercase(config: Mapping) -> Mapping {
let mut lowercased = Mapping::new();
for (key, value) in config {
let mut key = match key {
Value::String(key) => key,
key => {
let Some(key) = key.as_str() else {
continue;
};
key.to_owned()
}
};
key.make_ascii_lowercase();
lowercased.insert(Value::String(key), value);
if let Some(key_str) = key.as_str() {
lowercased.insert(lowercase_key(key_str), value);
}
}
lowercased
}
@@ -32,7 +32,7 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
}
#[test]
fn test_merge() -> Result<(), serde_yaml_ng::Error> {
fn test_merge() -> anyhow::Result<()> {
let merge = r"
prepend-rules:
- prepend
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 clash_verge_logging::{Type, logging};
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 SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// Script logs are retained when evaluation or result conversion fails.
pub type ScriptLogs = Vec<(String, String)>;
type ScriptResult = (Mapping, Vec<String>, Vec<(String, String)>);
type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>);
type EvalOutcome = (Result<Mapping, std::string::String>, ScriptLogs);
#[derive(Debug, PartialEq, Eq)]
pub enum MainDeclaration {
Present,
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![],
);
/// Never fails: exceptions are logged and the input config is returned unchanged.
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip.
if script == tmpl::ITEM_SCRIPT {
return (use_lowercase(config), vec![], vec![]);
}
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(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]),
Err(_) => (
Err(_elapsed) => (
Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")),
vec![],
),
};
match outcome {
Ok(result) => {
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
}
}
@@ -72,8 +91,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
let outputs_clone = Arc::clone(&outputs);
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), take_logs());
let bail = |reason: std::string::String| (Err(reason), outputs.lock().to_vec());
let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
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())
})?;
// 检查输出限制
if outputs_clone.lock().len() >= MAX_OUTPUTS {
return Err(boa_engine::JsError::from_opaque(
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}"));
}
// 仅处理 name 参数中的特殊字符
let safe_name = escape_js_string_for_single_quote(name);
if safe_name.len() > 1024 {
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) {
Ok(config) => (Ok(config), take_logs()),
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()),
Err(err) => {
logging!(
error,
@@ -220,29 +240,16 @@ fn json_approx_size(value: &serde_json::Value) -> usize {
}
}
// 安全地转义字符串
fn escape_js_string_for_single_quote(s: &str) -> String {
// 限制处理的字符串长度
if s.len() > 10240 {
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into();
}
s.replace('\\', "\\\\")
.replace('\'', "\\'")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\n', "\\n") // 添加换行符转义
.replace('\r', "\\r") // 添加回车转义
.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_yaml_ng::{Mapping, Sequence, Value};
use std::collections::HashSet;
use tristr::TriStr;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SeqMap {
@@ -10,11 +9,11 @@ pub struct SeqMap {
pub delete: Vec<String>,
}
fn collect_proxy_names(seq: &Sequence) -> Vec<TriStr> {
fn collect_proxy_names(seq: &Sequence) -> Vec<String> {
seq.iter()
.filter_map(|item| match item {
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(TriStr::from),
Value::String(name) => Some(TriStr::from(name.as_str())),
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned),
Value::String(name) => Some(name.to_owned()),
_ => None,
})
.collect()
@@ -41,7 +40,7 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
names
.into_iter()
.filter(|name| seen.insert(name.clone()))
.collect::<Vec<TriStr>>()
.collect::<Vec<String>>()
} else {
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 appended_to_selector = false;
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);
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));
@@ -45,20 +45,3 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
config
}
pub(super) const DEFAULT_MTU: u16 = 1500;
/// Saved dialog fields; `enable` belongs to the verge switch.
pub(super) const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
+49 -194
View File
@@ -1,29 +1,18 @@
use crate::{
config::{
Config, IClashTemp, IProfiles, IVerge, profile_storage,
profiles::{load_profiles_unlocked, validate_profile_file},
},
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{
PROFILE_YAML, PROFILES_DIR, PathBufExec as _, VERGE_CONFIG, app_home_dir, local_backup_dir, verge_path,
},
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
help,
},
};
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Result, anyhow};
use chrono::Utc;
use clash_verge_backup_archive::ValidatedBackup;
use clash_verge_draft::DraftConflict;
use clash_verge_logging::{Type, logging};
use clash_verge_profile_store::RECOVERY_ENTRY_NAMES;
use reqwest_dav::list_cmd::ListFile;
use serde::Serialize;
use std::{
fs::File,
path::{Path, PathBuf},
};
use std::path::PathBuf;
use tokio::fs;
use tristr::alias::String;
@@ -40,36 +29,16 @@ async fn finalize_restored_verge_config(
webdav_url: Option<String>,
webdav_username: Option<String>,
webdav_password: Option<String>,
archive: ValidatedBackup<File>,
) -> Result<()> {
let config_write = Config::lock_config_write().await;
let profiles_draft = Config::profiles().await;
let mut profile_guard = None;
let restored = {
let guard = &mut profile_guard;
let draft = &profiles_draft;
profiles_draft
.with_data_modify(|_| async move {
let (io_guard, retry) = profile_storage::write_for_restore().await?;
*guard = Some(io_guard);
let (profiles, mut restored) = restore_files(archive, retry).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
if let Err(error) = restored.save_file().await {
profile_storage::block_restore(&error);
return Err(error);
}
draft.discard();
Ok((profiles, restored))
})
.await
.inspect_err(|error: &anyhow::Error| {
if error.is::<DraftConflict>() {
profile_storage::block_restore(error);
}
})?
};
// A broken restored `verge.yaml` is a restore failure, not a reason to load defaults.
let mut restored = help::read_yaml::<IVerge>(&verge_path()?).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
restored.save_file().await?;
let restored_clash = IClashTemp::new().await;
let clash_draft = Config::clash().await;
clash_draft.edit_draft(|d| {
@@ -77,15 +46,18 @@ async fn finalize_restored_verge_config(
});
clash_draft.apply();
let restored_profiles = load_profiles().await;
let profiles_draft = Config::profiles().await;
profiles_draft.edit_draft(|d| {
*d = restored_profiles;
});
profiles_draft.apply();
let verge_draft = Config::verge().await;
verge_draft.edit_draft(|d| {
*d = restored.clone();
});
verge_draft.apply();
if let Some(guard) = &profile_guard {
profile_storage::finish_restore(guard);
}
drop(profile_guard);
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
@@ -160,85 +132,8 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
})
}
async fn restore_config_path(staged: &Path, home: &Path, name: &str, retry: bool) -> Result<PathBuf> {
let path = staged.join(name);
if !retry && !fs::try_exists(&path).await? {
return Ok(home.join(name));
}
Ok(path)
}
async fn validate_restore(
mut archive: ValidatedBackup<File>,
home_dir: &Path,
retry: bool,
) -> Result<ValidatedBackup<File>> {
let staging_root = home_dir.to_owned();
let (staged, archive) = AsyncHandler::spawn_blocking(move || -> Result<_> {
let staged = tempfile::tempdir_in(staging_root)?;
archive.extract_to(staged.path())?;
Ok((staged, archive))
})
.await
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
let validated: Result<()> = async {
let verge = restore_config_path(staged.path(), home_dir, VERGE_CONFIG, retry).await?;
let profiles_path = restore_config_path(staged.path(), home_dir, PROFILE_YAML, retry).await?;
help::read_yaml::<IVerge>(&verge).await?;
let profiles: IProfiles = help::read_yaml(&profiles_path).await?;
if retry {
let bodies = staged.path().join(PROFILES_DIR);
for file in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
validate_profile_file(file)?;
let body = fs::symlink_metadata(bodies.join(file))
.await
.with_context(|| format!("failed to inspect recovery backup profile body {file}"))?;
anyhow::ensure!(body.is_file(), "recovery backup profile body {file} is not a file");
}
}
Ok(())
}
.await;
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
validated?;
Ok(archive)
}
async fn restore_files(archive: ValidatedBackup<File>, retry: bool) -> Result<(IProfiles, IVerge)> {
let home_dir = app_home_dir()?;
let mut archive = validate_restore(archive, &home_dir, retry).await?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let extracted = archive.extract_to(&home_dir).map_err(anyhow::Error::from);
if let Err(error) = &extracted {
profile_storage::block_restore(error);
}
extracted
})
.await
.map_err(|join| {
let error = anyhow!("backup extraction task failed: {join}");
profile_storage::block_restore(&error);
error
})??;
let loaded = async {
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
let profiles = load_profiles_unlocked().await?;
Ok((profiles, verge))
}
.await;
if let Err(error) = &loaded {
profile_storage::block_restore(error);
}
loaded
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
let archive = AsyncHandler::spawn_blocking(move || -> Result<_> {
Ok(ValidatedBackup::open(File::open(path)?, RECOVERY_ENTRY_NAMES)?)
})
.await
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
let (webdav_url, webdav_username, webdav_password) = {
let verge = Config::verge().await;
let verge = verge.latest_arc();
@@ -249,35 +144,41 @@ async fn restore_backup_archive(path: PathBuf) -> Result<()> {
)
};
tokio::spawn(async move {
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password, archive).await
let home_dir = app_home_dir()?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let file = std::fs::File::open(&path)?;
let mut zip = zip::ZipArchive::new(file)?;
zip.extract(&home_dir)?;
Ok(())
})
.await?
.await
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password).await
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
tokio::spawn(async move {
let archive_dir = tempfile::tempdir()?;
let archive = archive_dir.path().join("backup.zip");
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, archive.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let result = restore_backup_archive(archive).await;
drop(archive_dir);
result
})
.await?
let backup_storage_path = app_home_dir()
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
.join(filename.as_str());
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, backup_storage_path.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let res = restore_backup_archive(backup_storage_path.clone()).await;
let _ = backup_storage_path.remove_if_exists().await;
res
}
pub async fn create_local_backup() -> Result<()> {
@@ -464,49 +365,3 @@ pub async fn export_local_backup(filename: String, destination: String) -> Resul
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clash_verge_backup_archive::BackupWriter;
use std::io::Write as _;
#[tokio::test]
async fn validates_config_before_replacing_live_files() -> Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join(PROFILE_YAML);
let live = b"items: []\n";
fs::write(&path, live).await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}\n").await?;
let open_backup = |index: Option<&[u8]>, include_body: bool| -> Result<_> {
let file = tempfile::tempfile()?;
let mut writer = BackupWriter::new(file)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}\n")?;
if let Some(index) = index {
writer.start_file(PROFILE_YAML)?.write_all(index)?;
}
if include_body {
writer.start_profile("r.yaml")?.write_all(b"proxies: []\n")?;
}
Ok(ValidatedBackup::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?)
};
let invalid = open_backup(Some(b"items: invalid\n"), false)?;
assert!(validate_restore(invalid, home.path(), false).await.is_err());
assert_eq!(fs::read(&path).await?, live);
validate_restore(open_backup(None, false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(None, false)?, home.path(), true)
.await
.is_err()
);
let index = b"items: [{uid: r, type: remote, file: r.yaml}]\n";
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
validate_restore(open_backup(Some(index), true)?, home.path(), true).await?;
Ok(())
}
}
+4 -7
View File
@@ -34,13 +34,10 @@ pub async fn set_dns_override(
profiles.current.as_ref() == Some(&profile_uid),
"The active profile changed; retry the DNS setting"
);
let source = {
let _guard = crate::config::profile_storage::read().await?;
dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?
};
let source = dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?;
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
}
-1
View File
@@ -9,7 +9,6 @@ mod icon;
mod listener;
mod profile;
mod proxy;
pub(crate) mod proxy_view;
mod subscription;
mod tun;
mod window;
-165
View File
@@ -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(())
}
}
-81
View File
@@ -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))
}
+20 -20
View File
@@ -1,5 +1,5 @@
use crate::{
config::{Config, PrfOption, download_subscription, profile_storage, profiles::apply_remote_refresh_safe},
config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe},
core::{
CoreManager, handle,
notify::{NoticeStatus, Refresh, announce},
@@ -11,15 +11,8 @@ use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tristr::alias::String;
struct RefreshSource {
url: String,
file: Option<String>,
option: Option<PrfOption>,
}
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<RefreshSource>> {
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let _guard = profile_storage::read().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");
@@ -44,23 +37,22 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Op
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
)
);
Ok(Some(RefreshSource {
url: item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
file: item.file.clone(),
option: item.option.clone(),
}))
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,
source: &RefreshSource,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let url = source.url.as_str();
let merged_opt = PrfOption::merge(source.option.as_ref(), option);
let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
@@ -133,7 +125,15 @@ async fn perform_profile_update(
let last_err = match result {
Ok((strategy, downloaded)) => {
// A persistence error must not replay a successful download with another transport.
apply_remote_refresh_safe(uid, url, source.file.clone(), downloaded, merged_opt).await?;
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());
}
@@ -157,8 +157,8 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
let url_opt = should_update_profile(uid, is_manual_trigger).await?;
let profile_persisted = match url_opt {
Some(source) => {
perform_profile_update(uid, &source, option, is_manual_trigger).await?;
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?;
true
}
None => false,
+6
View File
@@ -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 {
use specta::datatype::{DataType, Fields};
let mut types = specta::Types::default().register::<crate::config::IVerge>();
+1 -2
View File
@@ -21,7 +21,6 @@ pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
pub static CLASH_CONFIG: &str = "config.yaml";
pub static VERGE_CONFIG: &str = "verge.yaml";
pub static PROFILE_YAML: &str = "profiles.yaml";
pub static PROFILES_DIR: &str = "profiles";
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
@@ -49,7 +48,7 @@ pub fn app_resources_dir() -> Result<PathBuf> {
}
pub fn app_profiles_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join(PROFILES_DIR))
Ok(app_home_dir()?.join("profiles"))
}
pub fn app_icons_dir() -> Result<PathBuf> {
+1 -6
View File
@@ -470,8 +470,7 @@ async fn initialize_config_files() -> Result<()> {
logging!(info, Type::Setup, "Created verge config at {:?}", path);
}
if crate::config::profile_storage::check().is_ok()
&& let Ok(path) = dirs::profiles_path()
if let Ok(path) = dirs::profiles_path()
&& !path.exists()
{
let template = IProfiles::default();
@@ -490,10 +489,6 @@ async fn initialize_config_files() -> Result<()> {
/// Initializes configuration required before Tauri setup.
pub async fn init_config() -> Result<()> {
if let Err(error) = crate::config::profile_storage::recover_at_startup().await {
logging!(error, Type::Config, "Profile recovery failed: {error:#}");
}
#[cfg(target_os = "macos")]
migrate_legacy_macos_logs().await?;
+1
View File
@@ -21,3 +21,4 @@ pub mod tmpl;
#[cfg(target_os = "macos")]
pub mod tray_speed;
pub mod window_manager;
pub mod yaml_emitter;
+6 -1
View File
@@ -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
@@ -1,10 +1,9 @@
use serde::Serialize;
use serde_yaml_ng::Result;
pub(crate) use serde_yaml_ng::to_string as serialize;
pub(crate) fn serialize_for_export<T: Serialize>(data: &T) -> Result<String> {
Ok(quote_fake_ip_filter_wildcards(&serialize(data)?))
pub fn to_mihomo_config_string<T: Serialize>(data: &T) -> Result<String> {
let yaml = serde_yaml_ng::to_string(data)?;
Ok(quote_fake_ip_filter_wildcards(&yaml))
}
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;
for line in yaml.lines() {
let indent = line.len() - line.trim_start_matches(' ').len();
let indent = leading_spaces(line);
let trimmed = &line[indent..];
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:" {
in_fake_ip_filter = true;
fake_ip_filter_indent = indent;
result.push_str(line);
result.push('\n');
continue;
}
if in_fake_ip_filter
&& indent >= fake_ip_filter_indent
&& let Some(item) = trimmed.strip_prefix("- ")
&& needs_quotes(item)
{
result.push_str(&line[..indent + 2]);
push_quoted(&mut result, item);
} else {
result.push_str(line);
if in_fake_ip_filter && indent >= fake_ip_filter_indent && trimmed.starts_with("- ") {
result.push_str(&line[..indent]);
result.push_str("- ");
result.push_str(&quote_wildcard_item(&trimmed[2..]));
result.push('\n');
continue;
}
result.push_str(line);
result.push('\n');
}
result
}
fn needs_quotes(item: &str) -> bool {
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
fn leading_spaces(line: &str) -> usize {
line.len() - line.trim_start_matches(' ').len()
}
fn push_quoted(output: &mut String, item: &str) {
output.push('\'');
for (index, part) in item.split('\'').enumerate() {
if index != 0 {
output.push_str("''");
}
output.push_str(part);
fn quote_wildcard_item(item: &str) -> String {
if !item.starts_with('\"') && !item.starts_with('\'') && contains_wildcard(item) {
quote_string(item)
} else {
item.to_string()
}
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)]
#[allow(clippy::expect_used)]
mod tests {
use super::serialize_for_export;
use super::to_mihomo_config_string;
fn roundtrip(input: &str) {
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");
assert_eq!(reparsed, value);
@@ -84,7 +90,7 @@ dns:
roundtrip(input);
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("- '+.market.xiaomi.com'"));
+1 -1
View File
@@ -1,5 +1,5 @@
import { Box, Typography, alpha, useTheme } from '@mui/material'
import React, { forwardRef, ReactNode } from 'react'
import { forwardRef, ReactNode } from 'react'
// 自定义卡片组件接口
interface EnhancedCardProps {
+33 -33
View File
@@ -32,39 +32,39 @@
}
},
"ruleDialog": {
"title": "Add rule…",
"matchBy": "Match by",
"domain": "Domain",
"unavailable": "Not available",
"destination": "Add to the prepend rules of “{{name}}”.",
"newConnections": "New connections will match the updated configuration.",
"processPathHint": "Matches all destinations accessed by processes at this path.",
"processNameHint": "Matches all destinations accessed by processes with this name.",
"ruleModeHint": "Rule-based routing takes effect in Rule mode.",
"addAndApply": "Add and apply",
"profileChanged": "The active profile changed. Close this dialog and add the rule again.",
"applyFailed": "The rule could not be applied. Your selection has been kept.",
"unsupportedValue": "This value contains characters that cannot be used in a quick rule.",
"saved": "Rule saved and configuration applied.",
"noMetadata": "This connection has no domain, process or IP information for configuring a rule.",
"noProfile": "No active profile with an editable rule extension is available.",
"entry": "Configure rule…",
"modifyTitle": "Modify rule",
"domainScope": "Domain scope",
"exactDomain": "Only this domain",
"allSubdomains": "This domain and all its subdomains",
"title": "Adicionar regra…",
"matchBy": "Correspondência por",
"domain": "Domínio",
"unavailable": "Indisponível",
"destination": "Adicionar no início das regras de “{{name}}”.",
"newConnections": "As novas conexões seguirão a configuração atualizada.",
"processPathHint": "Corresponde a todos os destinos acessados por processos neste caminho.",
"processNameHint": "Corresponde a todos os destinos acessados por processos com este nome.",
"ruleModeHint": "O roteamento por regras funciona no modo Regra.",
"addAndApply": "Adicionar e aplicar",
"profileChanged": "O perfil ativo mudou. Feche esta janela e adicione a regra novamente.",
"applyFailed": "Não foi possível aplicar a regra. Sua seleção foi mantida.",
"unsupportedValue": "Este valor contém caracteres que não podem ser usados em uma regra rápida.",
"saved": "Regra salva e configuração aplicada.",
"noMetadata": "Esta conexão não tem informações de domínio, processo ou IP para configurar uma regra.",
"noProfile": "Não há um perfil ativo com uma extensão de regras editável.",
"entry": "Configurar regra…",
"modifyTitle": "Modificar regra",
"domainScope": "Escopo do domínio",
"exactDomain": "Apenas este domínio",
"allSubdomains": "Este domínio e todos os seus subdomínios",
"rootDomain": "Domínio principal e todos os seus subdomínios ({{domain}})",
"policyUnavailable": "This policy is no longer available. Choose another policy.",
"editDestination": "Update the existing rule in “{{name}}”, keeping its position.",
"saveAndApply": "Save and apply",
"sourceIp": "Source IP",
"destinationIp": "Destination IP",
"sourceHint": "Matches all requests from this IP or subnet, including requests from other applications. No port filtering.",
"destinationHint": "Matches this destination IP or subnet across all domains. No port filtering.",
"fullPath": "Full path",
"connectionHost": "Current connection domain: {{host}}",
"invalidDomain": "Enter the current domain or a parent domain with at least two labels.",
"matchingDomain": "Matching domain",
"invalidIp": "Enter a valid IP/prefix length: 0–32 for IPv4 or 0–128 for IPv6."
"policyUnavailable": "Esta política não está mais disponível. Escolha outra.",
"editDestination": "Atualizar a regra existente em “{{name}}”, mantendo sua posição.",
"saveAndApply": "Salvar e aplicar",
"sourceIp": "IP de origem",
"destinationIp": "IP de destino",
"sourceHint": "Corresponde a todas as solicitações deste IP ou sub-rede, inclusive de outros aplicativos. Sem filtro de portas.",
"destinationHint": "Corresponde a este IP de destino ou sub-rede em todos os domínios. Sem filtro de portas.",
"fullPath": "Caminho completo",
"connectionHost": "Domínio da conexão atual: {{host}}",
"invalidDomain": "Informe o domínio atual ou um domínio superior com pelo menos dois segmentos.",
"matchingDomain": "Domínio correspondente",
"invalidIp": "Informe um IP e um tamanho de prefixo válidos: 0–32 para IPv4 ou 0–128 para IPv6."
}
}