Compare commits

..
142 Commits
Author SHA1 Message Date
Tunglies 3dc6205c80 fix(backup): restore files from the validated staging directory 2026-12-04 12:54:11 +08:00
Tunglies f535ca192d fix(profile): commit missing companions with the refreshed subscription 2026-12-04 12:38:59 +08:00
Tunglies 20b7a4a0e7 fix(profile): report manual refresh failures once 2026-12-04 12:31:34 +08:00
Tunglies 333ffe5f64 chore: merge the runtime changes from dev 2026-12-04 07:39:33 +08:00
Tunglies 70d6917104 fix(profile): identify subscriptions that need recovery 2026-12-04 07:37:51 +08:00
Tunglies 06329c3337 refactor(backend): extract configuration and runtime capabilities (#8801)
* chore(clippy): scope crate lint policy

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

* docs(agents): define Rust backend architecture boundaries

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

* refactor(draft): type async publication conflicts

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

* refactor(logging): use typed logger errors

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

* refactor(subscription): extract response decoding

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

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

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

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

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

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

* refactor(profile): extract selected node recovery rules

* docs(agents): define dependencies between capability crates

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

* refactor(backup): extract backup ZIP writing

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

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

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

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

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

* refactor(profile): extract script validation and execution

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

* refactor(config): extract configuration renderer

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

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

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

* refactor(config): inject the profile script executor

* refactor(config): centralize Mihomo YAML output

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

* chore(clippy): scope crate lint policy

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

* docs(agents): define Rust backend architecture boundaries

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

* refactor(draft): type async publication conflicts

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

* refactor(logging): use typed logger errors

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

* refactor(subscription): extract response decoding

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

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

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

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

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

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

* refactor(profile): extract selected node recovery rules

* docs(agents): define dependencies between capability crates

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

* refactor(backup): extract backup ZIP writing

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

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

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

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

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

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

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

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

* style(profile): keep profile fields together

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

* refactor(profile): call the core reload directly

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

* refactor(config): name the runtime rendering step

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

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

* refactor(config): load cached chain items directly

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

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

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

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

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

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

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

* fix(config): keep runtime field sorting stable

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

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

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

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

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

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

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

* fix(script): reject oversized names before escaping
2026-12-03 23:24:11 +00:00
Tunglies 235a0507f0 refactor(profile): borrow profile identifiers from the render snapshot 2026-12-04 01:48:34 +08:00
Tunglies 77f4c77b50 fix(profile): preserve storage recovery details in refresh errors 2026-12-04 01:48:34 +08:00
Tunglies 338c3f67fa fix(backup): distinguish staging failures from live restore failures 2026-12-04 01:48:34 +08:00
Tunglies 4e50ea0678 perf(backup): allocate each profile entry name once 2026-12-04 01:48:34 +08:00
Tunglies 9c894956d1 fix(backup): serialize restore with WebDAV credential updates 2026-12-04 01:48:34 +08:00
Tunglies ba6be42a7d fix(backup): validate restored core and DNS settings in staging 2026-12-04 01:48:33 +08:00
Tunglies 731b3fc8c9 fix(profile): report partial writes on the legacy refresh path 2026-12-04 01:48:33 +08:00
Tunglies 2b02e2de3e fix(backup): restore from a stable copy of the local archive 2026-12-04 01:48:33 +08:00
Tunglies d2f0f3c0c1 refactor(backup): name the archive before staging verification 2026-12-04 01:48:33 +08:00
Tunglies 6b84c0d625 fix(backup): reject entries shorter than their declared length 2026-12-04 01:48:33 +08:00
Tunglies 5edc035120 perf(profile-store): reuse buffers while preparing a refresh 2026-12-04 01:48:33 +08:00
Tunglies 2cdd0dd701 fix(backup): check referenced profile bodies before restore 2026-12-04 01:48:32 +08:00
Tunglies 44aa5f2430 refactor(profile): simplify saved body validation and rollback 2026-12-04 01:48:32 +08:00
Tunglies 28aefde36f refactor(subscription): carry refresh metadata through the download 2026-12-04 01:48:32 +08:00
Tunglies 59762520cc fix(profile-store): refresh native Unix body filenames 2026-12-04 01:48:32 +08:00
Tunglies 1172ff24ff chore: merge runtime base into storage branch 2026-12-04 01:32:11 +08:00
Tunglies 71c2b9317f fix(script): reject oversized names before escaping 2026-12-03 21:39:26 +08:00
Tunglies 675933c5f0 perf(runtime-bundle): reuse the normalized destination buffer 2026-12-03 21:39:25 +08:00
Tunglies 1c4bf7c223 fix(runtime-bundle): reject mixed owners of a provider path 2026-12-03 21:39:25 +08:00
Tunglies dc9ace6645 perf(proxy): resolve unique members without building scope caches 2026-12-03 21:39:24 +08:00
Tunglies 4da989534f perf(script): count integer digits without formatting JSON 2026-12-03 21:39:24 +08:00
Tunglies c99a0a18a5 fix(script): support runtime console methods during validation 2026-12-03 21:39:23 +08:00
Tunglies 21099614a8 fix(script): check the evaluated profile entry point 2026-12-03 21:39:22 +08:00
Tunglies 9b10b9bb25 perf(config): reuse profile sequence storage during rendering 2026-12-03 21:39:21 +08:00
Tunglies 1471ad31a5 fix(config): keep runtime field sorting stable 2026-12-03 21:39:21 +08:00
Tunglies 2735282879 fix(config): fill blank IPv6 fake IP ranges in TUN mode 2026-12-03 21:39:20 +08:00
Tunglies dd48d2acb5 chore(storage): sync the runtime branch with dev 2026-12-03 21:00:08 +08:00
Tunglies 7b6113c91b chore(runtime): merge dev after the profile squash 2026-12-03 20:58:17 +08:00
Tunglies 4fa9983576 refactor(runtime-bundle): share provider section order 2026-12-03 20:56:45 +08:00
Tunglies 473452c57e refactor(proxy): build the view from its input 2026-12-03 20:56:44 +08:00
Tunglies 17bd142fb7 refactor(proxy): collect provider snapshots in display order 2026-12-03 20:56:44 +08:00
Tunglies 4e49320ba2 refactor(config): reuse sequence storage when applying profile edits 2026-12-03 20:56:43 +08:00
Tunglies b5546c03b5 refactor(proxy): read group order and scope in one pass 2026-12-03 20:56:43 +08:00
Tunglies 91aae5ef40 refactor(script): keep console state local to evaluation 2026-12-03 20:56:43 +08:00
Tunglies ce1c0ee510 refactor(config): load cached chain items directly 2026-12-03 20:56:42 +08:00
Tunglies 079a8563a9 refactor(config): accumulate profile keys and logs during rendering 2026-12-03 20:56:42 +08:00
Tunglies 6cce982f58 refactor(config): remove the unused runtime patch API 2026-12-03 20:56:41 +08:00
Tunglies 447ce3ccfb refactor(backend): extract profile and subscription capabilities (#8800)
* chore(clippy): scope crate lint policy

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

* docs(agents): define Rust backend architecture boundaries

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

* refactor(draft): type async publication conflicts

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

* refactor(logging): use typed logger errors

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

* refactor(subscription): extract response decoding

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

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

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

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

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

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

* refactor(profile): extract selected node recovery rules

* docs(agents): define dependencies between capability crates

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

* refactor(backup): extract backup ZIP writing

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

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

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

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

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

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

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

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

* style(profile): keep profile fields together

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

* refactor(profile): call the core reload directly

* refactor(backup): move archive validation to the restore change
2026-12-03 12:42:26 +00:00
Tunglies 93a5528025 refactor(backup): keep archive validation with restore 2026-12-03 19:43:10 +08:00
Tunglies 63000f39f5 refactor(config): name the runtime rendering step 2026-12-03 19:42:50 +08:00
Tunglies ca22495869 chore(runtime): sync the profile refactor 2026-12-03 19:42:46 +08:00
Tunglies a272280f1a refactor(backup): move archive validation to the restore change 2026-12-03 19:38:51 +08:00
Tunglies 35dbb3716d refactor(profile): call the core reload directly 2026-12-03 19:38:46 +08:00
Tunglies 651f297785 refactor(profile): name index operations after what they change 2026-12-03 19:38:42 +08:00
Tunglies 80fca96848 style(profile): keep profile fields together 2026-12-03 19:38:36 +08:00
Tunglies 966e0e03ff refactor(profile): remove companions from the deleted profile 2026-12-03 19:38:32 +08:00
Tunglies 3af8034e02 refactor(profile): build companion options in one place 2026-12-03 19:38:28 +08:00
Tunglies 83a520ea19 refactor(subscription): pass the proxy directly to each download 2026-12-03 19:38:23 +08:00
Tunglies c742a9a17c refactor(profile): look up the refresh target once 2026-12-03 19:38:18 +08:00
Tunglies c53e005f25 fix(subscription): separate deep link parameters from nested URLs 2026-12-03 17:59:25 +08:00
Tunglies 390231a043 fix(subscription): preserve filenames from response headers and URL paths 2026-12-03 17:59:25 +08:00
Tunglies c4ee0e0c8a fix(profile): preserve delays for future update timestamps 2026-12-03 17:59:24 +08:00
Tunglies 041454be57 refactor(subscription): keep profile writes outside proxy fallback 2026-12-03 17:20:42 +08:00
Tunglies 18f733fca9 refactor(backup): extract backup ZIP writing 2026-12-03 17:20:42 +08:00
Tunglies 911a3c58fa refactor(task): move retry primitives into the task crate 2026-12-03 17:20:32 +08:00
Tunglies 0bc38ba664 docs(agents): define dependencies between capability crates 2026-12-03 17:20:32 +08:00
Tunglies 00cb43f5de refactor(profile): extract selected node recovery rules 2026-12-03 17:20:32 +08:00
Tunglies 85c0a60ddb refactor(subscription): decode deep links in the subscription crate 2026-12-03 17:20:32 +08:00
Tunglies c6e59ad538 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-03 17:20:32 +08:00
Tunglies 64490c44ab 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-03 17:20:32 +08:00
Tunglies 9614dee991 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-03 17:20:32 +08:00
Tunglies ad285eac95 refactor(logging): use typed logger errors
Expose crate-owned logger errors and preserve the underlying error sources.
2026-12-03 17:20:32 +08:00
Tunglies 72e7201abc 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-03 17:20:32 +08:00
Tunglies 03ff4f846c docs(agents): define Rust backend architecture boundaries
Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.
2026-12-03 17:20:21 +08:00
Tunglies 032eb9767e chore(clippy): scope crate lint policy
Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.
2026-12-03 17:20:21 +08:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>Tunglies
a76818326d chore(deps): update tauri (#8764)
* chore(deps): update tauri

* fix(installer): align NSIS locale variables with Tauri 2.13

* chore(tray): migrate template icons to Tauri 2.13 APIs

* fix(core): resolve the bundled core for validation fingerprints

* fix(deps): resolve Tauri 2.13 with the patched WebDriver

* fix(tray): wake the main window from Linux tray clicks

Use StatusNotifierItem activation to wake the dashboard, including lightweight mode.

Closes #8517

* fix(tray): gate template icon handling to macOS at compile time

* fix(deps): select GTK3 for Linux dialogs

* fix(linux): return when the startup dialog cannot initialize GTK

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
2026-12-03 08:07:50 +00:00
Tunglies 16ef6fbc34 fix(i18n): resolve startup locales consistently
Prefer a supported saved language over the cache and browser locale.
Align frontend alias resolution with Rust and ignore unsupported saved
values when the layout mounts so they cannot overwrite the fallback.

In Rust, walk borrowed prefixes instead of rebuilding strings. This
preserves locale resolution and removes quadratic work on long tags.
Across all 14 shipped locale IDs (equally weighted),
median lookup time fell from 40.0 to 22.4 ns and heap allocations fell
from 4 to 2 per lookup. A synthetic 64 KiB tag fell from 771 ms to 240 µs.
2026-12-03 12:59:02 +08:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 9bdd2c0623 build(deps): bump cookie (#8807)
Bumps the cargo group with 1 update in the / directory: [cookie](https://github.com/rwf2/cookie-rs).

Updates `cookie` from 0.18.1 to 0.18.3
- [Changelog](https://github.com/rwf2/cookie-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rwf2/cookie-rs/compare/0.18.1...0.18.3)

---
updated-dependencies:
- dependency-name: cookie
  dependency-version: 0.18.3
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-02 16:34:41 +00:00
renovate[bot]Tungliesrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
39fd5e968b chore(deps): update cargo dependencies (#8811)
* test(draft): cover conflict wakeup and busy layer

* chore(deps): update cargo dependencies

---------

Co-authored-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 13:41:44 +00:00
Tunglies c9223b204b fix(limiter): handle stale clock samples and timestamp overflow
A caller could sample the clock at 1000 ms and pause while another
caller was admitted at 2000 ms. On resuming, the first caller could
load the newer last_run_ms, mistake its stale sample for a clock
rollback, and replace 2000 with 1000. This reopened the 100 ms period
and let another check at 2000 ms pass. Load last_run_ms before sampling
the clock so the stale caller's compare-exchange fails if a newer
admission has changed that value. Preserve sequential clock rollback
behavior and the existing atomic orderings.

The period check also added the period to last_run_ms. A last admission
at u64::MAX - 55 with a 56 ms period overflowed on the next check:
debug builds panicked and release builds wrapped the deadline to zero,
admitting a duplicate timestamp. Compare elapsed time against the
period only after confirming the clock has not moved backward, which
makes the subtraction safe and preserves the exact period boundary.

Enable the stale-sample and overflow regressions, keep the saved
Proptest seed, and add Loom coverage for advancing time and multiple
stale callers plus a deterministic test at u64::MAX.
2026-12-02 21:18:45 +08:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
9c3a433979 chore(deps): update agentic workflows to v1.4.5 (#8809)
- Bump actions in `copilot-setup-steps.yml`
- Bump other agentic workflow lockfiles

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-12-02 12:42:22 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 2943b58ef7 chore(deps): update dependency terser to v5.51.3 [security] (#8810)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-02 10:33:16 +00:00
Tunglies 186ec116fa refactor(frontend): outfox foxact, foxts, and eslint-plugin-sukka (#8808)
* chore(eslint): remove eslint-plugin-sukka

* refactor(frontend): remove foxts and inline local utilities

* refactor(frontend): remove foxact and replace with local hooks

* refactor(proxy): reuse local storage for group preferences
2026-12-02 01:34:55 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
87de9bd5bf chore(deps): update github/gh-aw-actions action to v1.4.4 (#8804)
* chore(deps): update github/gh-aw-actions action to v1.4.4

* chore(gh-aw): update agentic workflows to v1.4.4

- Updates workflow tooling and threat detection
- Refreshes generated workflows with the latest compiler, container digests, and GitHub MCP server
- Improves detection activation metadata restoration and prepares detection inputs before reporting or artifacts run

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-12-01 18:12:16 +00:00
Tunglies 4168a87983 perf(runtime-bundle): read remote providers from borrowed configuration 2026-12-02 02:10:11 +08:00
Tunglies 573eac8ec9 refactor(config): centralize Mihomo YAML output 2026-12-02 02:10:11 +08:00
Tunglies e0cced59eb refactor(config): inject the profile script executor 2026-12-02 02:10:11 +08:00
Tunglies ecf1dd2486 refactor(proxy): extract proxy view and its use case
Project the Mihomo snapshot into the existing IPC DTO and move use-case orchestration out of the command.
2026-12-02 02:10:11 +08:00
Tunglies 7d665bd5bb refactor(config): extract configuration renderer
Render from inputs supplied by the app, reuse the script crate, and preserve the default template fast path.
2026-12-02 02:10:11 +08:00
Tunglies 5605cc26c5 refactor(profile): extract script validation and execution
Share the Boa validation and execution API while preserving the save-side timeout and diagnostics.
2026-12-02 02:10:11 +08:00
Tunglies aa62db78a9 perf(runtime-bundle): share destination strings with tristr
Share destination storage within bundle planning and preserve the Service wire strings and provider readback.
2026-12-02 02:10:11 +08:00
Tunglies 6c78c16a96 refactor(runtime-bundle): extract runtime bundle planning
Plan provider destinations and assets in the crate. Adapt the plan to the Service wire format at the call site.
2026-12-02 02:10:11 +08:00
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
Tunglies 4b602e1436 Merge branch 'crates-me-runtime' into crates-me
# Conflicts:
#	src-tauri/src/config/profiles.rs
#	src-tauri/src/feat/subscription.rs
2026-12-01 23:01:08 +08:00
Tunglies 171586d725 Merge branch 'crates-me-profile' into crates-me-runtime 2026-12-01 22:59:00 +08:00
Tunglies fe523dc34d perf(backup): verify file contents during restore staging 2026-12-01 22:58:36 +08:00
Tunglies bc5ed53a1b perf(runtime-bundle): read remote providers from borrowed configuration 2026-12-01 22:58:35 +08:00
Tunglies be8dd3b060 refactor(subscription): keep profile writes outside proxy fallback 2026-12-01 22:58:35 +08:00
Tunglies bc000a8e39 refactor(profile-store): reuse the journal install scratch file 2026-12-01 22:58:35 +08:00
Tunglies 724f10fd33 refactor(profile-store): simplify refresh cleanup and legacy writes 2026-12-01 22:20:33 +08: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
Tunglies 5c05722f9a refactor(config): centralize Mihomo YAML output 2026-12-01 22:10:13 +08:00
Tunglies 1450ad441c fix(backup): validate restore inputs and allow recovery retries 2026-12-01 22:10:13 +08:00
Tunglies dbf252ed65 fix(profile-store): recover aliased subscription body creation 2026-12-01 22:10:13 +08:00
Tunglies e575f4dda7 fix(profile): recover interrupted subscription refreshes
Keep subscription body and index writes recoverable, and coordinate startup, readers, backup, and Draft publication around the transaction.
2026-12-01 22:10:13 +08:00
Tunglies 840de9c4d1 refactor(config): inject the profile script executor 2026-12-01 22:09:39 +08:00
Tunglies c5b74aa01d refactor(proxy): extract proxy view and its use case
Project the Mihomo snapshot into the existing IPC DTO and move use-case orchestration out of the command.
2026-12-01 22:09:24 +08:00
Tunglies f50e52172c refactor(config): extract configuration renderer
Render from inputs supplied by the app, reuse the script crate, and preserve the default template fast path.
2026-12-01 22:09:16 +08:00
Tunglies 5d471d97aa refactor(profile): extract script validation and execution
Share the Boa validation and execution API while preserving the save-side timeout and diagnostics.
2026-12-01 22:09:04 +08:00
Tunglies fc9d5ce2a4 perf(runtime-bundle): share destination strings with tristr
Share destination storage within bundle planning and preserve the Service wire strings and provider readback.
2026-12-01 22:08:47 +08:00
Tunglies 4142fb07fd refactor(runtime-bundle): extract runtime bundle planning
Plan provider destinations and assets in the crate. Adapt the plan to the Service wire format at the call site.
2026-12-01 22:08:47 +08:00
Tunglies 177c73f6d7 refactor(backup): extract backup ZIP writing 2026-12-01 22:08:20 +08:00
Tunglies 9eea0c7ce1 refactor(task): move retry primitives into the task crate 2026-12-01 22:07:38 +08:00
Tunglies a7b6b070b7 docs(agents): define dependencies between capability crates 2026-12-01 22:07:38 +08:00
Tunglies 61bd24d788 refactor(profile): extract selected node recovery rules 2026-12-01 22:07:38 +08:00
Tunglies 7f4ed2c179 refactor(subscription): decode deep links in the subscription crate 2026-12-01 22:07:38 +08:00
Tunglies 33ce830c01 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-01 22:07:38 +08:00
Tunglies 25750ae001 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-01 22:07:19 +08: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
Tunglies 1baa72c2f4 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-11-30 18:13:49 +08:00
Tunglies a0d4426f0a refactor(logging): use typed logger errors
Expose crate-owned logger errors and preserve the underlying error sources.
2026-11-30 18:13:48 +08:00
Tunglies 1c7bc3200b 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-11-30 18:13:47 +08:00
Tunglies 7b43bac198 docs(agents): define Rust backend architecture boundaries
Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation.
2026-11-30 18:13:47 +08:00
Tunglies 1fa03291f3 chore(clippy): scope crate lint policy
Keep panic-on-error lints at application target roots and scope signal dependencies to Linux.
2026-11-30 18:13:46 +08:00
Jeferson Araujo b484a8f24c fix(i18n): translate the connection rule dialog to pt-BR (#8771) 2026-11-30 08:30:04 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> e04fae62d9 chore(deps): update dependency tar to v8 (#8769)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 14:25:03 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 4ce69ec2b1 chore(deps): update dependency knip to v6.49.0 (#8768)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-29 14:19:06 +00:00
❤是纱雾酱哟~ 8d242b5732 chore(agents): adds instructions for GitHub Copilot (#8765)
- Create `.github/copilot-instructions.md` as agent-specific instruction
  file for GitHub Copilot
- Use "one-line-wrapper" prompt to `AGENTS.md`, like `GEMINI.md`
- Use "at annotation syntax" for instructions importing, like
  `CLAUDE.md`

Assisted-by: Copilot Fusion (High), actually GPT-6.1 Sol, GPT-6.1 Terra and GPT-6 Luna

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-29 08:30:36 +00:00
198 changed files with 11531 additions and 7294 deletions
+2 -2
View File
@@ -4,8 +4,8 @@
"features": { "features": {
"ghcr.io/devcontainers/features/node:2": { "ghcr.io/devcontainers/features/node:2": {
"version": "26.13.1", "version": "26.14.0",
"pnpmVersion": "12.23.0" "pnpmVersion": "12.25.1"
}, },
"ghcr.io/devcontainers/features/rust:1": { "ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1", "version": "1.100.1",
+65 -263
View File
@@ -1,275 +1,77 @@
--- ---
name: Agentic Workflows 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 disable-model-invocation: true
--- ---
# GitHub Agentic Workflows Agent # 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 ## Execution and safety
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.
## Repository Instructions Overlay - For incident, health, and failure-related optimization requests,
use intent routing before generic update, upgrade, or optimization routes.
Load the target repository's `.github/aw/instructions.md`, if present. First load
Use `@.github/aw/instructions.md` only in a matching checkout; do not substitute [debug-bootstrap.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/debug-bootstrap.md)
a guidance-repository overlay. 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`
Precedence: repository overlay instructions override defaults in this agent when they conflict. 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 ## 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**: [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)
- **Creating new workflows**: Routes to `create` prompt - **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).
- **Updating existing workflows**: Routes to `update` prompt - **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.
- **Diagnosis, patching, and active debugging**: Routes to `debug-agentic-workflow` for the local-first strategy, evidence triage and live gates - **Upgrading workflows**: [upgrade-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/upgrade-agentic-workflows.md)
- **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 - **Creating report-generating workflows**: [report.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/report.md)
- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt - **Creating shared components**: [create-shared-agentic-workflow.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/create-shared-agentic-workflow.md)
- **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 - **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`.
- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt - **Analyzing test coverage**: [test-coverage.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/test-coverage.md)
- **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 - **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`.
- **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 - **Reducing token use or cost**: [token-optimization.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/token-optimization.md)
- **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 - **Selecting workflow architecture or patterns**: [patterns.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/patterns.md)
- **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 - **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.
- **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 - **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.
- **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 - **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.
- **Git-backed work queues**: Routes to `work-queue` instructions for producers, dispatchers, workers, observers, deployment and recovery - **Local SDLC issue bootstrap**: [squad.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/squad.md)
- **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 or coordination; consult the
selected design prompt.
Workflows may optionally include:
For general workflow authoring, load
- **Project tracking / monitoring** (GitHub Projects updates, status reporting) [github-agentic-workflows.md](https://raw.githubusercontent.com/github/gh-aw/main/.github/aw/github-agentic-workflows.md).
- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows) Load linked specifications only when the selected prompt requires them.
## Files This Applies To <!-- instruction-prefix-end -->
- 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`
+38 -13
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0", "version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
}, },
"github/gh-aw-actions/setup@v1.4.1": { "github/gh-aw-actions/setup@v1.4.5": {
"repo": "github/gh-aw-actions/setup", "repo": "github/gh-aw-actions/setup",
"version": "v1.4.1", "version": "v1.4.5",
"sha": "367d4dc4e89caf85422092845006e4a4a660d926" "sha": "a83eaf07e756a15e65f669eb32d00787cf5a2569"
} }
}, },
"containers": { "containers": {
@@ -52,6 +52,11 @@
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059", "digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@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": { "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "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", "digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -92,6 +97,11 @@
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7", "digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@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": { "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "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", "digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -112,6 +122,11 @@
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3", "digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@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": { "ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14", "image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0", "digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -127,6 +142,11 @@
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a", "digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@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": { "ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13", "image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56", "digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -167,20 +187,25 @@
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d", "digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@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": { "ghcr.io/github/gh-aw-firewall/squid:0.29.22": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15", "image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22",
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1", "digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1" "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": { "ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node", "image": "ghcr.io/github/gh-aw-node",
"digest": "sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc", "digest": "sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f",
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:8735428c2d4e602f90781ba0c571c400e8ff93c7ee1508a75d71f87e34e415cc" "pinned_image": "ghcr.io/github/gh-aw-node@sha256:1ee08ba84b321ff231ca905b73e6e7da8f5fd177bcc6433a56631fce2b5a0f2f"
}, },
"ghcr.io/github/github-mcp-server:v2.2.0": { "ghcr.io/github/github-mcp-server:v2.3.0": {
"image": "ghcr.io/github/github-mcp-server:v2.2.0", "image": "ghcr.io/github/github-mcp-server:v2.3.0",
"digest": "sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174", "digest": "sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6",
"pinned_image": "ghcr.io/github/github-mcp-server:v2.2.0@sha256:040c4e99810076035eb1d9beb4b4a96fcf589c43cefed6ff51a46a553eb4e174" "pinned_image": "ghcr.io/github/github-mcp-server:v2.3.0@sha256:f8ee4dedc7d5c8cb32854ab91cc92a31c55a8a5510708cf8742e9f9427588ca6"
} }
} }
} }
+5
View File
@@ -0,0 +1,5 @@
# GitHub Copilot Instructions
Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.
@../AGENTS.md
@@ -100,6 +100,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/charts.md` - `.github/aw/charts.md`
- `.github/aw/cli-commands.md` - `.github/aw/cli-commands.md`
- `.github/aw/compat.md` - `.github/aw/compat.md`
- `.github/aw/connectors-authoring.md`
- `.github/aw/connectors.md` - `.github/aw/connectors.md`
- `.github/aw/context.md` - `.github/aw/context.md`
- `.github/aw/create-agentic-workflow-design.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/maintainer.md`
- `.github/aw/mcp-clis.md` - `.github/aw/mcp-clis.md`
- `.github/aw/memory-stateful-patterns.md` - `.github/aw/memory-stateful-patterns.md`
- `.github/aw/memory-wiki-comment.md`
- `.github/aw/memory.md` - `.github/aw/memory.md`
- `.github/aw/messages.md` - `.github/aw/messages.md`
- `.github/aw/multi-agent-research.md` - `.github/aw/multi-agent-research.md`
+5 -5
View File
@@ -51,7 +51,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Install dependencies - name: Install dependencies
run: pnpm install --frozen-lockfile run: pnpm install --frozen-lockfile
@@ -182,7 +182,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -262,7 +262,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -395,7 +395,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -479,7 +479,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6.1.1 - uses: pnpm/action-setup@v6.1.1
name: Install pnpm name: Install pnpm
+1 -1
View File
@@ -63,7 +63,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - run: pnpm install --frozen-lockfile
+3 -3
View File
@@ -31,9 +31,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- name: Install gh-aw extension - name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1 uses: github/gh-aw-actions/setup-cli@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5
with: with:
version: v1.4.1 version: v1.4.5
- name: Install Rust Stable - name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
with: with:
@@ -49,7 +49,7 @@ jobs:
- name: Install Node.js - name: Install Node.js
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Install frontend dependencies - name: Install frontend dependencies
env: env:
+1 -1
View File
@@ -43,7 +43,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+1 -1
View File
@@ -104,7 +104,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true' if: github.event.inputs[matrix.input] == 'true'
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- run: pnpm install --frozen-lockfile - 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 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
if: github.event.action != 'closed' if: github.event.action != 'closed'
+8 -8
View File
@@ -46,7 +46,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Validate source and publish the approved snapshot - name: Validate source and publish the approved snapshot
id: source id: source
env: env:
@@ -231,7 +231,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -330,7 +330,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -461,7 +461,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
cache: 'pnpm' cache: 'pnpm'
- name: Pnpm install and check - name: Pnpm install and check
@@ -542,7 +542,7 @@ jobs:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
with: with:
run_install: false run_install: false
@@ -565,7 +565,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -593,7 +593,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -661,7 +661,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm 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 - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Install pnpm - name: Install pnpm
uses: pnpm/action-setup@v6 uses: pnpm/action-setup@v6
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/setup-node@v7 - uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- name: Sync Mihomo version - name: Sync Mihomo version
id: sync id: sync
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -15,7 +15,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
@@ -39,7 +39,7 @@ jobs:
- name: Install Node - name: Install Node
uses: actions/setup-node@v7 uses: actions/setup-node@v7
with: with:
node-version: '26.13.1' node-version: '26.14.0'
- uses: pnpm/action-setup@v6 - uses: pnpm/action-setup@v6
name: Install pnpm name: Install pnpm
+2 -2
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1 nodejs 26.14.0
pnpm 12.23.0 pnpm 12.25.1
rust 1.100.1 rust 1.100.1
+4
View File
@@ -60,6 +60,10 @@ the ownership evidence the AI-slop review evaluates (see
- For development and bug fixes, follow the - For development and bug fixes, follow the
[development workflow](CONTRIBUTING.md#development-workflow). [development workflow](CONTRIBUTING.md#development-workflow).
- For Rust backend changes that affect capability ownership or dependency
boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md).
For Tauri commands and desktop integration, also follow
[Backend Architecture Guardrails](src-tauri/AGENTS.md).
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md). - For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
Review is read-only unless changes are authorized; findings do not expand Review is read-only unless changes are authorized; findings do not expand
that authorization to unrelated fixes, commits, pushes, or GitHub updates. that authorization to unrelated fixes, commits, pushes, or GitHub updates.
Generated
+1001 -638
View File
File diff suppressed because it is too large Load Diff
+32 -6
View File
@@ -9,6 +9,14 @@ members = [
"crates/tauri-plugin-clash-verge-sysinfo", "crates/tauri-plugin-clash-verge-sysinfo",
"crates/clash-verge-i18n", "crates/clash-verge-i18n",
"crates/clash-verge-limiter", "crates/clash-verge-limiter",
"crates/clash-verge-subscription",
"crates/clash-verge-runtime-bundle",
"crates/clash-verge-config-render",
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
"crates/clash-verge-profile-store",
"crates/clash-verge-backup-archive",
] ]
resolver = "2" resolver = "2"
@@ -50,8 +58,11 @@ split-debuginfo = "unpacked"
[patch.crates-io] [patch.crates-io]
# Backport Windows menu command ID recycling on the muda 0.20 compatibility branch. # Backport Windows menu command ID recycling on the muda 0.20 compatibility branch.
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" } muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "2745082c7f487c5e0c9568000b5a7ac24234d6e4" }
[workspace.dependencies] [workspace.dependencies]
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
clash-verge-draft = { path = "crates/clash-verge-draft" } clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" } clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" } clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
@@ -59,16 +70,27 @@ clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" } clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-subscription = { path = "crates/clash-verge-subscription" }
clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-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" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44" tracing = "0.1.44"
tauri = { version = "=3.0.0-alpha.6" } tauri = { version = "2.13.0" }
tauri-runtime-wry = "=3.0.0-alpha.6" tauri-plugin-clipboard-manager = "2.5.0"
tauri-plugin-clipboard-manager = "=3.0.0-alpha.3"
parking_lot = "0.13.0" parking_lot = "0.13.0"
anyhow = "1.0.105" anyhow = "1.0.105"
thiserror = "2.0.20"
zip = "9.9.0"
boa_engine = "0.22.0"
futures = "0.3.34" futures = "0.3.34"
loom = "0.7.3"
proptest = "1.12.0"
chrono = "0.4.45" chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] } criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [ tokio = { version = "1.54.1", features = [
@@ -92,11 +114,14 @@ serde = { version = "1.0.229" }
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] } tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
serde_json = { version = "1.0.154" } serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" } serde_yaml_ng = { version = "0.10.0" }
sha2 = "0.11.2"
tempfile = "3.27.0"
specta = "=2.0.0-rc.26"
socket2 = "0.6.5" socket2 = "0.6.5"
# *** For Windows platform only *** # *** For Windows platform only ***
deelevate = "0.2.0" deelevate = "0.2.0"
windows-sys = { version = "0.61.2", features = [ windows-sys = { version = "0.101.0", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock", "Win32_Networking_WinSock",
@@ -109,6 +134,9 @@ windows-sys = { version = "0.61.2", features = [
] } ] }
# ********************************* # *********************************
[workspace.lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(loom)'] }
[workspace.lints.clippy] [workspace.lints.clippy]
# fallible_impl_from = "deny" // 过于激进,暂时不开启 # fallible_impl_from = "deny" // 过于激进,暂时不开启
# implicit_clone = "deny" // 可能会造成额外开销,暂时不开启 # implicit_clone = "deny" // 可能会造成额外开销,暂时不开启
@@ -125,7 +153,6 @@ copy_iterator = "deny"
correctness = { level = "deny", priority = -1 } correctness = { level = "deny", priority = -1 }
dbg_macro = "warn" dbg_macro = "warn"
equatable_if_let = "deny" equatable_if_let = "deny"
expect_used = "warn"
expl_impl_clone_on_copy = "deny" expl_impl_clone_on_copy = "deny"
future_not_send = "deny" future_not_send = "deny"
iter_on_empty_collections = "deny" iter_on_empty_collections = "deny"
@@ -164,7 +191,6 @@ unnecessary_self_imports = "deny"
unnecessary_wraps = "deny" unnecessary_wraps = "deny"
unused_async = "deny" unused_async = "deny"
unused_trait_names = "deny" unused_trait_names = "deny"
unwrap_used = "warn"
use_self = "deny" use_self = "deny"
useless_let_if_seq = "deny" useless_let_if_seq = "deny"
wildcard_imports = "deny" wildcard_imports = "deny"
+6
View File
@@ -28,11 +28,16 @@
<details> <details>
<summary><strong> 🐞 修复问题 </strong></summary> <summary><strong> 🐞 修复问题 </strong></summary>
- 优化本地与 WebDAV 备份恢复,复用已校验的文件,减少重复解压
- 修复订阅更新覆盖下载期间修改的设置,以及更新失败后遗留增强配置
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
- 优化订阅恢复失败提示,显示受影响的订阅名称
- 修复「外部控制器」复制成功的提示一闪而过 - 修复「外部控制器」复制成功的提示一闪而过
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位 - 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
- 修复检测更新后又发布新版时,应用内更新失败 - 修复检测更新后又发布新版时,应用内更新失败
- 修复关闭「自动检查更新」后,手动检查更新时弹窗空白 - 修复关闭「自动检查更新」后,手动检查更新时弹窗空白
- 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB - 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB
- 修复服务端文件名无效时导入的订阅名称为空
- 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组 - 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组
- 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用 - 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用
- 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」 - 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」
@@ -59,6 +64,7 @@
**🐧 Linux** **🐧 Linux**
- 修复 Linux OpenRC 环境下服务安装失败 - 修复 Linux OpenRC 环境下服务安装失败
- 修复 Linux 左键点击托盘图标时无法唤回主窗口
</details> </details>
+5
View File
@@ -0,0 +1,5 @@
# Clippy loads a single configuration file, so repeat the workspace defaults.
avoid-breaking-exported-api = true
allow-unwrap-in-tests = true
cognitive-complexity-threshold = 25
excessive-nesting-threshold = 5
+46 -9
View File
@@ -2,19 +2,34 @@
## Choose the boundary ## Choose the boundary
- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain
types, invariants, parsing, validation, and deterministic transitions
independent of Tauri, concrete OS APIs, and implicit application state.
- Keep use cases, async coordination, cancellation, and timeouts in
framework-independent application modules. Pass dependencies explicitly.
Define ports where an external effect needs a contract. Adapters implement
the contracts owned by their consumers. Keep filesystem, network, IPC, process,
and OS-specific operations in their adapters.
- Extract a capability whose invariants can be owned behind a small API. Before - Extract a capability whose invariants can be owned behind a small API. Before
creating a crate, identify its owner, what callers supply, and what can be creating a crate, identify its owner, what callers supply, and what can be
verified through the crate API. Keep a module when the proposed boundary only verified through the crate API. Extract a crate when it provides a useful
relocates implementation or introduces a pass-through API. dependency, portability, testing, or ownership boundary. Keep a module when
- Keep the dependency direction from the app to the crate. Resolve app paths, the proposed boundary only relocates implementation or introduces a
read product settings, start app-owned tasks, and publish UI events in the app. pass-through API.
Pass the values, resources, or callbacks the crate needs. For example, - Keep capability crates independent by default. Compose peer capabilities in
the application and pass inputs or callbacks through the consumer's API.
Depend on another workspace crate for foundational mechanisms such as logging
and task primitives, or for a shared domain contract required to enforce the
same invariant. Keep tightly coupled rules together when separating them
would duplicate that contract or split its ownership.
- Keep dependencies pointing toward domain and application contracts. Resolve
app paths and read current settings at the application boundary. Pass in the
required values, resources, or callbacks. For example,
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the [logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
app supplies directories and limits through `LoggerConfig`. app supplies directories and limits through `LoggerConfig`.
- Keep framework and platform dependencies scoped to the capability that needs - Run framework-independent tests without starting the desktop app. A platform
them. Runtime-independent logic should be runnable without the desktop app. adapter can own runtime startup when its resource lifetime requires it, as
A platform adapter can own runtime startup when its resource lifetime requires [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
## Design the API ## Design the API
@@ -31,6 +46,14 @@
workspace lints. Reuse workspace dependencies where available and declare workspace lints. Reuse workspace dependencies where available and declare
only the features the crate needs. only the features the crate needs.
## Handle fallible input
- Define crate-owned error types with `thiserror` in a dedicated `error` module.
Re-export public errors through their established import paths.
- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate
errors from required external data and use defaults only when the input
contract gives the default a meaning.
## Own background work ## Own background work
- Give ordered start, replacement, and cleanup to one task owner. Reuse - Give ordered start, replacement, and cleanup to one task owner. Reuse
@@ -43,6 +66,20 @@
transaction boundaries and keep the reply path free of locks held by the transaction boundaries and keep the reply path free of locks held by the
waiting caller. Cancel only at safe boundaries and own issued effects through waiting caller. Cancel only at safe boundaries and own issued effects through
completion or explicit reconciliation. completion or explicit reconciliation.
- Distinguish requested effects from completed effects in typed outcomes.
Define how failures, cancellation, and timeouts affect publication, retry,
rollback, or reconciliation.
## Validate new crates
- Fuzz the public boundary before tuning. Exercise malformed input, fallback
behavior, and failures that can affect user data. Preserve the corpus and
record the baseline revision and dependency resolution.
- Try at least one targeted performance improvement. Compare the baseline and
candidate on the same workload and build settings. Record stable gains, flat
cases, and regressions, and justify which changes to keep.
- Fuzz the final candidate again. Use the baseline corpus and compare outputs,
diagnostics, and errors with the baseline where behavior should be preserved.
Verify the extracted contract through its public API when practical. Use Verify the extracted contract through its public API when practical. Use
`cargo test -p <crate>` for focused tests and keep native behavior checks at the `cargo test -p <crate>` for focused tests and keep native behavior checks at the
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-backup-archive"
version = "0.1.0"
edition = "2024"
[dependencies]
cap-primitives = "4.0.3"
cap-fs-ext = "4.0.3"
tempfile = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
[lints]
workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_System_SystemServices"] }
@@ -0,0 +1,15 @@
#[derive(Debug, thiserror::Error)]
pub enum ArchiveError {
#[error(transparent)]
Zip(#[from] zip::result::ZipError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("backup contains a symbolic link")]
Symlink,
#[error("backup contains an invalid path")]
InvalidPath,
#[error("archive contains profile recovery data")]
ReservedEntry,
#[error("backup entry length differs from its declared size")]
SizeMismatch,
}
@@ -0,0 +1,199 @@
mod error;
mod staged;
pub use error::ArchiveError;
pub use staged::{InstallError, StagedBackup};
use std::{
io::{self, Read, Seek, Write},
path::{Component, Path},
};
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<W: Write + Seek> {
zip: ZipWriter<W>,
options: SimpleFileOptions,
}
impl<W: Write + Seek> BackupWriter<W> {
pub fn new(target: W) -> Result<Self, ArchiveError> {
let mut zip = ZipWriter::new(target);
zip.add_directory("profiles/", SimpleFileOptions::default())?;
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
Ok(Self { zip, options })
}
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.start_file(&["profiles/", filename].concat())
}
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.zip.start_file_with_options(self.options.name(name.as_bytes()))?;
Ok(&mut self.zip)
}
pub fn finish(self) -> Result<W, ArchiveError> {
Ok(self.zip.finish()?)
}
}
pub struct BackupArchive<R: Read + Seek> {
zip: ZipArchive<R>,
entries: Vec<staged::Entry>,
}
impl<R: Read + Seek> BackupArchive<R> {
/// Checks entry paths and lengths. Extract into staging to verify stored file checksums before restore.
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
let mut entries = Vec::with_capacity(zip.len());
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
if entry.is_symlink() {
return Err(ArchiveError::Symlink);
}
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
for component in path.components() {
let Component::Normal(name) = component else {
continue;
};
let name = name.to_string_lossy();
if reserved_names
.iter()
.any(|reserved| name.eq_ignore_ascii_case(reserved))
{
return Err(ArchiveError::ReservedEntry);
}
}
// Extraction skips directory payloads and permits a decoded file shorter than its declared size.
let size = if entry.is_dir() || entry.compression() != CompressionMethod::Stored {
io::copy(&mut entry, &mut io::sink())?
} else {
entry.compressed_size()
};
entries.push(staged::Entry {
path,
directory: entry.is_dir(),
mode: entry.unix_mode(),
});
if size != entry.size() {
return Err(ArchiveError::SizeMismatch);
}
}
Ok(Self { zip, entries })
}
pub fn stage(mut self, home: &Path) -> Result<StagedBackup, ArchiveError> {
let files = tempfile::tempdir_in(home)?;
self.zip.extract(files.path())?;
Ok(StagedBackup {
files,
entries: self.entries,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn rejects_entries_shorter_than_their_declared_size() -> Result<(), ArchiveError> {
for name in ["profiles/example.yaml", "profiles/"] {
for method in [CompressionMethod::Stored, CompressionMethod::Deflated] {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file(name, SimpleFileOptions::default().compression_method(method))?;
writer.write_all(b"abc")?;
let mut bytes = writer.finish()?.into_inner();
let directory = ZipArchive::new(Cursor::new(&bytes))?.central_directory_start() as usize;
// Both ZIP headers agree on a size one byte larger than the actual payload.
bytes[22..26].copy_from_slice(&4u32.to_le_bytes());
bytes[directory + 24..directory + 28].copy_from_slice(&4u32.to_le_bytes());
assert!(
BackupArchive::open(Cursor::new(bytes), &[]).is_err(),
"{name} {method:?}"
);
}
}
Ok(())
}
#[cfg(unix)]
#[test]
fn installs_restricted_entries_and_preserves_omitted_files() -> Result<(), Box<dyn std::error::Error>> {
use std::{fs, os::unix::fs::PermissionsExt as _};
let home = tempfile::tempdir()?;
let implicit = home.path().join("implicit");
fs::create_dir(&implicit)?;
std::os::unix::fs::symlink("implicit", home.path().join("link"))?;
fs::set_permissions(&implicit, fs::Permissions::from_mode(0o750))?;
fs::write(implicit.join("omitted"), "keep")?;
fs::write(implicit.join("replace"), "old")?;
fs::hard_link(implicit.join("replace"), implicit.join("peer"))?;
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.add_directory("private/", SimpleFileOptions::default().unix_permissions(0))?;
writer.start_file("private/body", SimpleFileOptions::default().unix_permissions(0o200))?;
writer.write_all(b"restricted")?;
writer.start_file("link/replace", SimpleFileOptions::default())?;
writer.write_all(b"new")?;
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
staged.install(home.path())?;
let private = home.path().join("private");
assert_eq!(fs::metadata(&private)?.permissions().mode() & 0o777, 0);
fs::set_permissions(&private, fs::Permissions::from_mode(0o700))?;
assert_eq!(fs::metadata(private.join("body"))?.permissions().mode() & 0o777, 0o200);
fs::set_permissions(private.join("body"), fs::Permissions::from_mode(0o600))?;
assert_eq!(fs::read(private.join("body"))?, b"restricted");
assert_eq!(fs::read(implicit.join("replace"))?, b"new");
assert_eq!(fs::read(implicit.join("peer"))?, b"old");
assert_eq!(fs::read(implicit.join("omitted"))?, b"keep");
assert_eq!(fs::metadata(implicit)?.permissions().mode() & 0o777, 0o750);
Ok(())
}
#[test]
fn classifies_install_failure_by_preceding_live_changes() -> Result<(), Box<dyn std::error::Error>> {
for partial in [false, true] {
let home = tempfile::tempdir()?;
std::fs::create_dir(home.path().join("conflict"))?;
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
if partial {
writer.start_file("first", SimpleFileOptions::default())?;
writer.write_all(b"installed")?;
}
writer.start_file("conflict", SimpleFileOptions::default())?;
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
let error = staged.install(home.path()).unwrap_err();
assert_eq!(error.live_changed, partial);
assert_eq!(home.path().join("first").exists(), partial);
}
Ok(())
}
#[test]
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
let source = writer.finish()?;
let mut zip = ZipArchive::new(source.clone())?;
assert_eq!(zip.len(), 3);
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
let profile_time = {
let mut entry = zip.by_index(1)?;
assert_eq!(entry.name()?, "profiles/example.yaml");
assert_eq!(entry.compression(), CompressionMethod::Stored);
let mut contents = Vec::new();
entry.read_to_end(&mut contents)?;
assert_eq!(contents, b"proxies: []\n");
entry.last_modified()
};
let index = zip.by_index(2)?;
assert_eq!(index.name()?, "profiles.yaml");
assert_eq!(index.last_modified(), profile_time);
BackupArchive::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
Ok(())
}
}
@@ -0,0 +1,458 @@
use cap_fs_ext::{MetadataExt as _, OpenOptionsFollowExt as _, OpenOptionsMaybeDirExt as _, OpenOptionsSyncExt as _};
use cap_primitives::fs as cap;
use std::{
collections::BTreeMap,
fs::{self, File},
io::{self, ErrorKind},
path::{Component, Path, PathBuf},
};
pub(super) struct Entry {
pub path: PathBuf,
pub directory: bool,
pub mode: Option<u32>,
}
#[derive(Debug, thiserror::Error)]
#[error("{source}")]
pub struct InstallError {
pub live_changed: bool,
#[source]
source: io::Error,
}
pub struct StagedBackup {
pub(super) files: tempfile::TempDir,
pub(super) entries: Vec<Entry>,
}
impl StagedBackup {
pub fn path(&self) -> &Path {
self.files.path()
}
pub fn install(self, destination: &Path) -> Result<(), InstallError> {
let mut live_changed = false;
self.install_files(destination, &mut live_changed)
.map_err(|source| InstallError { live_changed, source })
}
fn install_files(&self, destination: &Path, changed: &mut bool) -> io::Result<()> {
let destination = destination.canonicalize()?;
let staging = self.path().canonicalize()?;
let staged_dir = cap::open_ambient_dir(&staging, cap_primitives::ambient_authority())?;
let staged_dir = cap::Metadata::from_file(&staged_dir)?;
let root = cap::open_ambient_dir(&destination, cap_primitives::ambient_authority())?;
let mut modes = BTreeMap::new();
for entry in &self.entries {
if entry.path.as_os_str().is_empty() {
continue;
}
let relative = resolve(&destination, &entry.path, &staging, &mut 40, true)?;
if relative.as_os_str().is_empty() {
return Err(invalid_target());
}
let parent = open_dirs(
&root,
relative.parent().ok_or_else(invalid_target)?,
&staged_dir,
changed,
)?;
let name = Path::new(relative.file_name().ok_or_else(invalid_target)?);
if entry.directory {
open_child_dir(&parent.dir, name, &staged_dir, changed)?;
} else {
let source = staging.join(&entry.path);
copy_file(&staging, &source, &parent.dir, name, entry.mode, changed)?;
}
#[cfg(windows)]
let mode = fs::metadata(staging.join(&entry.path))?
.permissions()
.readonly()
.then_some(0o444);
#[cfg(not(windows))]
let mode = entry.mode;
if let Some(mode) = mode {
modes.insert(relative, mode);
} else if !entry.directory {
modes.remove(&relative);
}
}
for (path, mode) in modes.into_iter().rev() {
let parent = open_dirs(&root, path.parent().ok_or_else(invalid_target)?, &staged_dir, changed)?;
let name = Path::new(path.file_name().ok_or_else(invalid_target)?);
set_mode(&parent.dir, name, mode)?;
*changed = true;
}
Ok(())
}
}
fn invalid_target() -> io::Error {
io::Error::new(ErrorKind::PermissionDenied, "invalid backup installation target")
}
fn relative_link<'a>(home: &Path, target: &'a Path) -> io::Result<&'a Path> {
if let Ok(relative) = target.strip_prefix(home) {
return Ok(relative);
}
#[cfg(windows)]
{
use std::path::Prefix;
let volume = |prefix| match prefix {
Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Prefix::Disk(drive.to_ascii_uppercase()),
Prefix::VerbatimUNC(server, share) => Prefix::UNC(server, share),
other => other,
};
let mut home = home.components();
let mut target = target.components();
if let (Some(Component::Prefix(base)), Some(Component::Prefix(link))) = (home.next(), target.next())
&& volume(base.kind()) == volume(link.kind())
{
return target
.as_path()
.strip_prefix(home.as_path())
.map_err(|_| invalid_target());
}
}
Err(invalid_target())
}
// Resolve existing links within the home, then reopen the resolved components without following links.
// A file entry replaces its leaf link only after its target has passed the same containment check.
fn resolve(home: &Path, path: &Path, staging: &Path, hops: &mut u8, keep_leaf: bool) -> io::Result<PathBuf> {
let mut out = PathBuf::new();
let mut components = path.components().peekable();
let mut missing = false;
while let Some(component) = components.next() {
match component {
Component::Normal(name) => out.push(name),
Component::CurDir => continue,
Component::ParentDir if !missing && out.pop() => continue,
_ => return Err(invalid_target()),
}
let full = home.join(&out);
if full.starts_with(staging) {
return Err(invalid_target());
}
match fs::symlink_metadata(&full) {
Ok(meta) if meta.is_symlink() => {
*hops = hops.checked_sub(1).ok_or_else(invalid_target)?;
let link = fs::read_link(&full)?;
let target = if link.is_absolute() {
relative_link(home, &link)?.to_owned()
} else {
out.parent().ok_or_else(invalid_target)?.join(link)
};
let checked = resolve(home, &target, staging, hops, false)?;
if !keep_leaf || components.peek().is_some() {
missing |= !home.join(&checked).try_exists()?;
out = checked;
}
}
Ok(_) => {}
Err(err) if err.kind() == ErrorKind::NotFound => missing = true,
Err(err) => return Err(err),
}
}
Ok(out)
}
struct PinnedDir {
dir: File,
#[cfg(windows)]
ancestors: Vec<File>,
}
fn is_staging_directory(dir: &File, staging: &cap::Metadata) -> io::Result<bool> {
let meta = cap::Metadata::from_file(dir)?;
Ok(meta.dev() == staging.dev() && meta.ino() == staging.ino())
}
fn open_dirs(root: &File, path: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<PinnedDir> {
let mut parent = PinnedDir {
dir: root.try_clone()?,
#[cfg(windows)]
ancestors: Vec::new(),
};
for component in path.components() {
let Component::Normal(name) = component else {
return Err(invalid_target());
};
let child = open_child_dir(&parent.dir, Path::new(name), staging, changed)?;
#[cfg(windows)]
parent.ancestors.push(parent.dir);
parent.dir = child;
}
Ok(parent)
}
fn open_child_dir(parent: &File, name: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<File> {
#[cfg(unix)]
let options = cap::DirBuilderExt::mode(&mut cap::DirOptions::new(), 0o700).clone();
#[cfg(not(unix))]
let options = cap::DirOptions::new();
match cap::create_dir(parent, name, &options) {
Ok(()) => *changed = true,
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
#[cfg(windows)]
Err(error)
if error.kind() == ErrorKind::PermissionDenied
&& cap::stat(parent, name, cap::FollowSymlinks::No).is_ok() => {}
Err(error) => return Err(error),
}
#[cfg(windows)]
{
use cap::OpenOptionsExt as _;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
let mut opts = cap::OpenOptions::new();
opts.read(true)
.maybe_dir(true)
.follow(cap::FollowSymlinks::No)
.share_mode(FILE_SHARE_READ);
let dir = cap::open(parent, name, &opts)?;
let meta = dir.metadata()?;
check_storage_filter(&dir)?;
if !meta.is_dir() || is_staging_directory(&dir, staging)? {
return Err(invalid_target());
}
Ok(dir)
}
#[cfg(not(windows))]
{
let dir = cap::open_dir_nofollow(parent, name)?;
if is_staging_directory(&dir, staging)? {
return Err(invalid_target());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = dir.metadata()?.permissions().mode();
if mode & 0o700 != 0o700 {
cap::set_permissions(&dir, Path::new("."), cap::PermissionsExt::from_mode(mode | 0o700))?;
*changed = true;
}
}
Ok(dir)
}
}
fn open_source(staging: &Path, source: &Path) -> io::Result<File> {
match File::open(source) {
#[cfg(unix)]
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
use std::os::unix::fs::PermissionsExt as _;
// Staging has the final archive modes, including unreadable files and directories.
let mut path = staging.to_owned();
for component in source.strip_prefix(staging).map_err(|_| invalid_target())?.components() {
path.push(component);
let meta = path.symlink_metadata()?;
let needed = if meta.is_dir() { 0o700 } else { 0o400 };
let mode = meta.permissions().mode();
if mode & needed != needed {
fs::set_permissions(&path, fs::Permissions::from_mode(mode | needed))?;
}
}
File::open(source)
}
result => {
let _ = staging;
result
}
}
}
fn copy_file(
staging: &Path,
source: &Path,
parent: &File,
name: &Path,
mode: Option<u32>,
changed: &mut bool,
) -> io::Result<()> {
let mut input = open_source(staging, source)?;
let mut options = cap::OpenOptions::new();
options.write(true).follow(cap::FollowSymlinks::No).nonblock(true);
#[cfg(windows)]
cap::OpenOptionsExt::share_mode(&mut options, windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ);
#[cfg(unix)]
cap::OpenOptionsExt::mode(&mut options, if mode.is_some() { 0o600 } else { 0o666 });
#[cfg(not(unix))]
let _ = mode;
match cap::stat(parent, name, cap::FollowSymlinks::No) {
Ok(metadata) => {
let replace = metadata.is_symlink() || metadata.is_file() && metadata.nlink() > 1;
#[cfg(windows)]
let replace = {
let mut replace = replace;
use windows_sys::Win32::Storage::FileSystem::{
FILE_ATTRIBUTE_OFFLINE, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN,
FILE_ATTRIBUTE_REPARSE_POINT, FILE_READ_ATTRIBUTES,
};
let attrs = cap::MetadataExt::file_attributes(&metadata);
if !metadata.is_symlink() && attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
let mut query = cap::OpenOptions::new();
cap::OpenOptionsExt::access_mode(&mut query, FILE_READ_ATTRIBUTES);
let pinned = cap::open(parent, name, query.follow(cap::FollowSymlinks::No))?;
check_storage_filter(&pinned)?;
replace |= attrs
& (FILE_ATTRIBUTE_OFFLINE
| FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
| FILE_ATTRIBUTE_RECALL_ON_OPEN)
!= 0;
}
replace
};
if replace {
#[cfg(windows)]
if cap::MetadataExt::file_attributes(&metadata)
& windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY
!= 0
{
cap::remove_dir(parent, name)?;
} else {
cap::remove_file(parent, name)?;
}
#[cfg(not(windows))]
cap::remove_file(parent, name)?;
*changed = true;
} else if !metadata.is_file() {
return Err(invalid_target());
}
}
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let mut output = match cap::open(parent, name, &options) {
Err(error) if error.kind() == ErrorKind::NotFound => {
let file = cap::open(parent, name, options.create_new(true))?;
*changed = true;
file
}
result => result?,
};
let meta = cap::Metadata::from_file(&output)?;
if !meta.is_file() || meta.nlink() != 1 {
return Err(invalid_target());
}
#[cfg(windows)]
check_storage_filter(&output)?;
output.set_len(0)?;
*changed = true;
io::copy(&mut input, &mut output)?;
output.set_modified(input.metadata()?.modified()?)?;
Ok(())
}
fn set_mode(parent: &File, name: &Path, mode: u32) -> io::Result<()> {
let mut options = cap::OpenOptions::new();
options
.read(true)
.follow(cap::FollowSymlinks::No)
.maybe_dir(true)
.nonblock(true);
#[cfg(windows)]
{
use windows_sys::Win32::Storage::FileSystem::{FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_WRITE_ATTRIBUTES};
cap::OpenOptionsExt::access_mode(&mut options, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES);
cap::OpenOptionsExt::share_mode(&mut options, FILE_SHARE_READ);
}
let file = match cap::open(parent, name, &options) {
#[cfg(unix)]
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
cap::open(parent, name, options.read(false).write(true))?
}
result => result?,
};
let meta = cap::Metadata::from_file(&file)?;
if !(meta.is_dir() || meta.is_file() && meta.nlink() == 1) {
return Err(invalid_target());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
file.set_permissions(fs::Permissions::from_mode(mode))
}
#[cfg(windows)]
{
check_storage_filter(&file)?;
let mut permissions = file.metadata()?.permissions();
permissions.set_readonly(mode & 0o222 == 0);
file.set_permissions(permissions)
}
}
#[cfg(windows)]
fn check_storage_filter(file: &File) -> io::Result<()> {
use std::os::windows::{fs::MetadataExt as _, io::AsRawHandle as _};
use windows_sys::Win32::{
Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FileAttributeTagInfo, GetFileInformationByHandleEx,
},
System::SystemServices::{
IO_REPARSE_TAG_CLOUD, IO_REPARSE_TAG_CLOUD_MASK, IO_REPARSE_TAG_DEDUP, IO_REPARSE_TAG_FILE_PLACEHOLDER,
IO_REPARSE_TAG_HSM, IO_REPARSE_TAG_HSM2, IO_REPARSE_TAG_ONEDRIVE, IO_REPARSE_TAG_SIS,
IO_REPARSE_TAG_STORAGE_SYNC, IO_REPARSE_TAG_WOF,
},
};
if file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 {
return Ok(());
}
let mut info = FILE_ATTRIBUTE_TAG_INFO::default();
// Inspect the pinned object, so a pathname swap cannot change which filter is classified.
if unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileAttributeTagInfo,
(&raw mut info).cast(),
size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let tag = info.ReparseTag;
if tag & !IO_REPARSE_TAG_CLOUD_MASK == IO_REPARSE_TAG_CLOUD
|| matches!(
tag,
IO_REPARSE_TAG_ONEDRIVE
| IO_REPARSE_TAG_FILE_PLACEHOLDER
| IO_REPARSE_TAG_WOF
| IO_REPARSE_TAG_DEDUP
| IO_REPARSE_TAG_STORAGE_SYNC
| 0x9000_0027
| IO_REPARSE_TAG_HSM2
| IO_REPARSE_TAG_HSM
| IO_REPARSE_TAG_SIS
| 0xC000_0014
)
{
Ok(())
} else {
Err(invalid_target())
}
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
#[test]
fn absolute_links_may_use_an_ordinary_prefix_for_the_same_home() {
let drive = Path::new(r"\\?\C:\home");
let share = Path::new(r"\\?\UNC\server\share\home");
assert_eq!(
relative_link(drive, Path::new(r"c:\home\data")).ok(),
Some(Path::new("data"))
);
assert_eq!(
relative_link(share, Path::new(r"\\server\share\home\data")).ok(),
Some(Path::new("data"))
);
assert!(relative_link(drive, Path::new(r"D:\home\data")).is_err());
assert!(relative_link(share, Path::new(r"\\server\other\home\data")).is_err());
assert!(relative_link(drive, Path::new(r"C:\home-other\data")).is_err());
}
}
@@ -0,0 +1,18 @@
[package]
name = "clash-verge-config-render"
version = "0.1.0"
edition = "2024"
[dependencies]
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
[lints]
workspace = true
@@ -18,19 +18,21 @@ pub const HANDLE_FIELDS: [&str; 12] = [
pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"]; pub const DEFAULT_FIELDS: [&str; 5] = ["proxies", "proxy-providers", "proxy-groups", "rule-providers", "rules"];
fn lowercase_key(key: &str) -> Value {
let mut key = String::from(key);
key.make_ascii_lowercase();
Value::from(key.as_str())
}
pub fn use_lowercase(config: Mapping) -> Mapping { pub fn use_lowercase(config: Mapping) -> Mapping {
let mut lowercased = Mapping::new(); let mut lowercased = Mapping::new();
for (key, value) in config { for (key, value) in config {
if let Some(key_str) = key.as_str() { let mut key = match key {
lowercased.insert(lowercase_key(key_str), value); Value::String(key) => key,
} key => {
let Some(key) = key.as_str() else {
continue;
};
key.to_owned()
}
};
key.make_ascii_lowercase();
lowercased.insert(Value::String(key), value);
} }
lowercased lowercased
} }
@@ -39,7 +41,7 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
let mut sorted = Mapping::new(); let mut sorted = Mapping::new();
HANDLE_FIELDS.into_iter().for_each(|key| { HANDLE_FIELDS.into_iter().for_each(|key| {
let key = Value::from(key); let key = Value::from(key);
if let Some(value) = config.remove(&key) { if let Some(value) = config.shift_remove(&key) {
sorted.insert(key, value); sorted.insert(key, value);
} }
}); });
@@ -66,8 +68,8 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
} }
#[inline] #[inline]
pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a { pub(super) fn lowercase_config_keys(config: &Mapping) -> impl Iterator<Item = String> {
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| { config.keys().filter_map(Value::as_str).map(|s: &str| {
let mut s: String = s.into(); let mut s: String = s.into();
s.make_ascii_lowercase(); s.make_ascii_lowercase();
s s
File diff suppressed because it is too large Load Diff
@@ -32,7 +32,7 @@ pub fn use_merge(merge: Mapping, mut config: Mapping) -> Mapping {
} }
#[test] #[test]
fn test_merge() -> anyhow::Result<()> { fn test_merge() -> Result<(), serde_yaml_ng::Error> {
let merge = r" let merge = r"
prepend-rules: prepend-rules:
- prepend - prepend
@@ -0,0 +1,81 @@
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
use serde_yaml_ng::Mapping;
use tristr::alias::String;
type ScriptResult = (Mapping, Vec<String>, ResultLog);
/// Never fails: exceptions are logged and the input config is returned unchanged.
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
script: String,
config: Mapping,
name: String,
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip.
if script == super::ITEM_SCRIPT {
return (use_lowercase(config), vec![], vec![]);
}
let json = match serde_json::to_value(&config) {
Ok(mut json) => {
if let Some(map) = json.as_object_mut() {
let mut lowered = serde_json::Map::with_capacity(map.len());
for (key, value) in std::mem::take(map) {
let mut key = key;
key.make_ascii_lowercase();
lowered.insert(key, value);
}
*map = lowered;
}
json
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
let (outcome, mut logs) = execute(script, json, name).await;
match outcome {
Ok(result) => {
let result = use_lowercase(result);
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
}
}
#[cfg(test)]
mod tests {
use std::future::ready;
use super::{Mapping, use_script};
#[tokio::test]
async fn default_template_skips_the_executor() {
let mut called = false;
let mut config = Mapping::new();
config.insert("MiXeD".into(), true.into());
let (config, changed_keys, logs) =
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
called = true;
ready((Ok(Mapping::new()), vec![]))
})
.await;
assert!(!called);
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
assert!(changed_keys.is_empty());
assert!(logs.is_empty());
}
}
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Sequence, Value}; use serde_yaml_ng::{Mapping, Sequence, Value};
use std::collections::HashSet; use std::collections::HashSet;
use tristr::TriStr;
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SeqMap { pub struct SeqMap {
@@ -9,14 +10,12 @@ pub struct SeqMap {
pub delete: Vec<String>, pub delete: Vec<String>,
} }
fn collect_proxy_names(seq: &Sequence) -> Vec<String> { fn proxy_name(proxy: &Value) -> Option<&str> {
seq.iter() match proxy {
.filter_map(|item| match item { Value::Mapping(proxy) => proxy.get("name").and_then(Value::as_str),
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(str::to_owned), Value::String(name) => Some(name),
Value::String(name) => Some(name.to_owned()), _ => None,
_ => None, }
})
.collect()
} }
fn is_selector_group(group_map: &Mapping) -> bool { fn is_selector_group(group_map: &Mapping) -> bool {
@@ -34,41 +33,34 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
} = seq; } = seq;
let added_proxy_names = if field == "proxies" { let added_proxy_names = if field == "proxies" {
let mut names = collect_proxy_names(&prepend); prepend
names.extend(collect_proxy_names(&append)); .iter()
let mut seen = HashSet::new(); .chain(&append)
names .filter_map(proxy_name)
.into_iter() .map(TriStr::from)
.filter(|name| seen.insert(name.clone())) .collect::<Vec<_>>()
.collect::<Vec<String>>()
} else { } else {
Vec::new() Vec::new()
}; };
let mut updated_items = Sequence::new(); let mut updated_items = match config.remove(field) {
updated_items.extend(prepend); Some(Value::Sequence(items)) => items,
_ => Sequence::new(),
if let Some(Value::Sequence(existing_items)) = config.remove(field) { };
// Filter out deleted items if !delete.is_empty() {
let kept_items: Sequence = existing_items updated_items.retain(|item| {
.into_iter() let name = match item {
.filter(|item| { Value::String(name) => Some(name),
if let Value::String(s) = item { Value::Mapping(mapping) => match mapping.get("name") {
!delete.contains(s) Some(Value::String(name)) => Some(name),
} else if let Value::Mapping(m) = item { _ => None,
if let Some(Value::String(name)) = m.get("name") { },
!delete.contains(name) _ => None,
} else { };
true name.is_none_or(|name| !delete.contains(name))
} });
} else {
true
}
})
.collect();
updated_items.extend(kept_items);
} }
updated_items.splice(..0, prepend);
updated_items.extend(append); updated_items.extend(append);
config.insert(Value::String(field.into()), Value::Sequence(updated_items)); config.insert(Value::String(field.into()), Value::Sequence(updated_items));
@@ -80,66 +72,57 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
return config; return config;
}; };
let Value::Sequence(proxy_groups) = proxy_groups_value else { let Value::Sequence(mut proxy_groups) = proxy_groups_value else {
config.insert(Value::String("proxy-groups".into()), proxy_groups_value); config.insert(Value::String("proxy-groups".into()), proxy_groups_value);
return config; return config;
}; };
let mut updated_groups = Sequence::new();
let mut appended_to_selector = false; let mut appended_to_selector = false;
for group in proxy_groups { for group in &mut proxy_groups {
if let Value::Mapping(mut group_map) = group { let Value::Mapping(group_map) = group else {
let mut group_proxies = match group_map.remove("proxies") { continue;
Some(Value::Sequence(proxies)) => Some( };
proxies let mut group_proxies = match group_map.remove("proxies") {
.into_iter() Some(Value::Sequence(mut proxies)) => {
.filter(|p| { if !delete.is_empty() {
if let Value::String(name) = p { proxies.retain(|member| !matches!(member, Value::String(name) if delete.contains(name)));
!delete.contains(name)
} else {
true
}
})
.collect::<Sequence>(),
),
Some(value) => {
group_map.insert(Value::String("proxies".into()), value);
None
} }
None => None, Some(proxies)
};
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(&group_map) {
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
let mut merged_proxies = Sequence::new();
let mut seen_proxy_names = HashSet::new();
for name in &added_proxy_names {
if seen_proxy_names.insert(name.clone()) {
merged_proxies.push(Value::String(name.clone()));
}
}
for value in base_group_proxies {
if let Value::String(name) = &value
&& !seen_proxy_names.insert(name.to_owned())
{
continue;
}
merged_proxies.push(value);
}
group_proxies = Some(merged_proxies);
appended_to_selector = true;
} }
Some(value) => {
if let Some(group_proxies) = group_proxies { group_map.insert(Value::String("proxies".into()), value);
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies)); None
} }
updated_groups.push(Value::Mapping(group_map)); None => None,
} else { };
updated_groups.push(group);
if !appended_to_selector && !added_proxy_names.is_empty() && is_selector_group(group_map) {
let base_group_proxies = group_proxies.unwrap_or_else(Sequence::new);
let mut merged_proxies = Sequence::new();
let mut seen_proxy_names = HashSet::new();
for name in &added_proxy_names {
if seen_proxy_names.insert(name.clone()) {
merged_proxies.push(Value::String(name.as_str().to_owned()));
}
}
for value in base_group_proxies {
if let Value::String(name) = &value
&& !seen_proxy_names.insert(TriStr::from(name.as_str()))
{
continue;
}
merged_proxies.push(value);
}
group_proxies = Some(merged_proxies);
appended_to_selector = true;
}
if let Some(group_proxies) = group_proxies {
group_map.insert(Value::String("proxies".into()), Value::Sequence(group_proxies));
} }
} }
config.insert(Value::String("proxy-groups".into()), Value::Sequence(updated_groups)); config.insert(Value::String("proxy-groups".into()), Value::Sequence(proxy_groups));
config config
} }
@@ -32,9 +32,7 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
revise!(dns_val, "fake-ip-range", "198.18.0.1/16"); revise!(dns_val, "fake-ip-range", "198.18.0.1/16");
} }
if ipv6_val && !dns_val.contains_key(Value::from("fake-ip-range6")) { super::ensure_fake_ip_range6(&mut dns_val);
revise!(dns_val, "fake-ip-range6", "2001:2::0/64");
}
} }
revise!(config, "dns", dns_val); revise!(config, "dns", dns_val);
@@ -45,3 +43,20 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
config config
} }
pub(super) const DEFAULT_MTU: u16 = 1500;
/// Saved dialog fields; `enable` belongs to the verge switch.
pub(super) const GUI_KEYS: &[&str] = &[
"stack",
"device",
"auto-route",
"route-exclude-address",
#[cfg(target_os = "linux")]
"auto-redirect",
"auto-detect-interface",
"dns-hijack",
"dns-mode",
"strict-route",
"mtu",
];
+1 -1
View File
@@ -10,7 +10,7 @@ harness = false
[dependencies] [dependencies]
parking_lot = { workspace = true } parking_lot = { workspace = true }
anyhow = { workspace = true } thiserror = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
[dev-dependencies] [dev-dependencies]
+3 -3
View File
@@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main};
use std::hint::black_box; use std::hint::black_box;
use tokio::runtime::Runtime; use tokio::runtime::Runtime;
use clash_verge_draft::Draft; use clash_verge_draft::{Draft, DraftConflict};
#[derive(Default, Clone, Debug)] #[derive(Default, Clone, Debug)]
struct IVerge { struct IVerge {
@@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) {
group.bench_function("with_data_modify_async", |b| { group.bench_function("with_data_modify_async", |b| {
b.to_async(&rt).iter(|| async { b.to_async(&rt).iter(|| async {
let draft = black_box(make_draft()); let draft = black_box(make_draft());
let _: Result<(), anyhow::Error> = draft let _: Result<(), DraftConflict> = draft
.with_data_modify::<_, _, _>(|mut box_data| async move { .with_data_modify(|mut box_data| async move {
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false)); box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
Ok((box_data, ())) Ok((box_data, ()))
}) })
+12
View File
@@ -0,0 +1,12 @@
/// Committed data changed before an asynchronous edit could publish.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("Optimistic lock failed: Committed data has changed during async operation")]
pub struct DraftConflict;
/// Another transaction is already staging a change to one of the layers asked for.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("configuration layer {layer} is being changed elsewhere")]
pub struct DraftBusy {
/// The layer that was already claimed.
pub layer: &'static str,
}
+12 -25
View File
@@ -1,3 +1,7 @@
mod error;
pub use error::{DraftBusy, DraftConflict};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{ use std::sync::atomic::{
@@ -91,14 +95,16 @@ impl<T: Clone> Draft<T> {
} }
/// Optimistically replaces committed data after an asynchronous edit. /// Optimistically replaces committed data after an asynchronous edit.
/// The caller's error type carries both edit failures and publication conflicts.
#[inline] #[inline]
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error> pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E>
where where
T: Send + Sync + 'static, T: Send + Sync + 'static,
F: FnOnce(T) -> Fut + Send, F: FnOnce(T) -> Fut + Send,
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send, Fut: std::future::Future<Output = Result<(T, R), E>> + Send,
E: From<DraftConflict>,
{ {
let _permit = self.acquire_data_modify_permit().await; let permit = self.acquire_data_modify_permit().await;
let (local, original_arc) = { let (local, original_arc) = {
let guard = self.inner.data.lock(); let guard = self.inner.data.lock();
let arc = Arc::clone(&guard.0); let arc = Arc::clone(&guard.0);
@@ -108,9 +114,9 @@ impl<T: Clone> Draft<T> {
let (new_local, res) = f(local).await?; let (new_local, res) = f(local).await?;
let mut guard = self.inner.data.lock(); let mut guard = self.inner.data.lock();
if !Arc::ptr_eq(&guard.0, &original_arc) { if !Arc::ptr_eq(&guard.0, &original_arc) {
return Err(anyhow::anyhow!( drop(guard);
"Optimistic lock failed: Committed data has changed during async operation" drop(permit);
)); return Err(DraftConflict.into());
} }
guard.0 = Arc::new(Box::new(new_local)); guard.0 = Arc::new(Box::new(new_local));
drop(guard); drop(guard);
@@ -191,25 +197,6 @@ impl<T: Clone + Send + Sync> DraftLayer for Draft<T> {
} }
} }
/// Another transaction is already staging a change to one of the layers asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DraftBusy {
/// The layer that was already claimed.
pub layer: &'static str,
}
impl std::fmt::Display for DraftBusy {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"configuration layer {} is being changed elsewhere",
self.layer
)
}
}
impl std::error::Error for DraftBusy {}
/// Exclusively claims several draft layers and rolls them all back unless committed. /// Exclusively claims several draft layers and rolls them all back unless committed.
/// ///
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected. /// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
+71 -13
View File
@@ -1,7 +1,14 @@
use std::sync::Arc; use std::{
pin::pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll, Wake, Waker},
};
use clash_verge_draft::{Draft, DraftTransaction}; use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction};
use tokio::sync::Notify; use tokio::sync::{Notify, oneshot};
#[derive(Clone, Debug, Default, PartialEq)] #[derive(Clone, Debug, Default, PartialEq)]
struct Config { struct Config {
@@ -28,14 +35,19 @@ fn edits_can_be_committed_or_discarded() {
} }
#[tokio::test] #[tokio::test]
async fn async_updates_are_serialized() -> anyhow::Result<()> { async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>> {
let draft = Arc::new(Draft::new(0_u8)); let draft = Arc::new(Draft::new(0_u8));
let mut updates = Vec::new(); let mut updates = Vec::new();
for _ in 0..16 { for _ in 0..16 {
let draft = Arc::clone(&draft); let draft = Arc::clone(&draft);
updates.push(tokio::spawn(async move { updates.push(tokio::spawn(async move {
draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await draft
.with_data_modify(|value| async move {
tokio::task::yield_now().await;
Ok::<_, DraftConflict>((value + 1, ()))
})
.await
})); }));
} }
for update in updates { for update in updates {
@@ -47,7 +59,7 @@ async fn async_updates_are_serialized() -> anyhow::Result<()> {
} }
#[tokio::test] #[tokio::test]
async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> { async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn std::error::Error>> {
let draft = Arc::new(Draft::new(Config::default())); let draft = Arc::new(Draft::new(Config::default()));
let started = Arc::new(Notify::new()); let started = Arc::new(Notify::new());
let finish = Arc::new(Notify::new()); let finish = Arc::new(Notify::new());
@@ -61,7 +73,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()>
started.notify_one(); started.notify_one();
finish.notified().await; finish.notified().await;
config.enabled = true; config.enabled = true;
Ok((config, ())) Ok::<_, DraftConflict>((config, ()))
}) })
.await .await
}) })
@@ -72,14 +84,55 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()>
draft.apply(); draft.apply();
finish.notify_one(); finish.notify_one();
assert!(update.await?.is_err()); assert_eq!(update.await?, Err(DraftConflict));
assert!(!draft.data_arc().enabled); assert!(!draft.data_arc().enabled);
assert_eq!(draft.data_arc().port, 7897); assert_eq!(draft.data_arc().port, 7897);
Ok(()) Ok(())
} }
#[test] #[test]
fn transaction_commits_every_layer() -> anyhow::Result<()> { fn parked_async_update_is_woken_after_optimistic_conflict() {
#[derive(Default)]
struct WakeFlag(AtomicBool);
impl Wake for WakeFlag {
fn wake(self: Arc<Self>) {
self.0.store(true, Ordering::Relaxed);
}
}
let draft = Draft::new(1);
let (finish, finished) = oneshot::channel();
let mut owner = pin!(draft.with_data_modify(|value| async move {
finished.await.expect("owner completion signal");
Ok::<_, DraftConflict>((value + 10, ()))
}));
let mut owner_context = Context::from_waker(Waker::noop());
assert!(owner.as_mut().poll(&mut owner_context).is_pending());
let wake_flag = Arc::new(WakeFlag::default());
let waker = Waker::from(Arc::clone(&wake_flag));
let mut waiter_context = Context::from_waker(&waker);
let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok::<_, DraftConflict>((value + 1, value)) }));
// The fast retry wakes once before the waiter parks on Notify.
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(wake_flag.0.swap(false, Ordering::Relaxed), "fast retry did not wake");
assert!(waiter.as_mut().poll(&mut waiter_context).is_pending());
assert!(!wake_flag.0.load(Ordering::Relaxed), "waiter did not park");
draft.edit_draft(|value| *value = 7);
draft.apply();
assert!(finish.send(()).is_ok());
assert!(matches!(owner.as_mut().poll(&mut owner_context), Poll::Ready(Err(_))));
assert_eq!(**draft.data_arc(), 7);
assert!(wake_flag.0.load(Ordering::Relaxed), "parked waiter was not notified");
assert!(matches!(waiter.as_mut().poll(&mut waiter_context), Poll::Ready(Ok(7))));
assert_eq!(**draft.data_arc(), 8);
}
#[test]
fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(String::from("a")); let second = Draft::new(String::from("a"));
let transaction = DraftTransaction::begin(vec![&first, &second])?; let transaction = DraftTransaction::begin(vec![&first, &second])?;
@@ -94,7 +147,7 @@ fn transaction_commits_every_layer() -> anyhow::Result<()> {
} }
#[test] #[test]
fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(String::from("a")); let second = Draft::new(String::from("a"));
@@ -110,12 +163,17 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
} }
#[test] #[test]
fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> { fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> {
let first = Draft::new(1_u8); let first = Draft::new(1_u8);
let second = Draft::new(2_u8); let second = Draft::new(2_u16);
let held = DraftTransaction::begin(vec![&second])?; let held = DraftTransaction::begin(vec![&second])?;
assert!(DraftTransaction::begin(vec![&first, &second]).is_err()); let busy = DraftTransaction::begin(vec![&first, &second])
.err()
.expect("transaction claimed an already-held layer");
let layer = std::any::type_name::<u16>();
assert_eq!(busy.layer, layer);
assert!(busy.to_string().contains(layer));
let available = DraftTransaction::begin(vec![&first])?; let available = DraftTransaction::begin(vec![&first])?;
drop(available); drop(available);
+3
View File
@@ -0,0 +1,3 @@
fn main() {
println!("cargo::rerun-if-changed=locales");
}
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: وكيل النظام systemProxy: وكيل النظام
tun: TUN tun: TUN
profile: ملف تعريفي profile: ملف تعريفي
profileRecovery:
named: يجب استعادة الاشتراك «{name}». راجع سجل التطبيق للاطلاع على التفاصيل.
unknown: يجب استعادة أحد الاشتراكات، لكن تعذّر تحديده. راجع سجل التطبيق للاطلاع على التفاصيل.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Systemproxy systemProxy: Systemproxy
tun: TUN tun: TUN
profile: Profil profile: Profil
profileRecovery:
named: Das Abonnement „{name}“ muss wiederhergestellt werden. Details stehen im Anwendungsprotokoll.
unknown: Ein Abonnement muss wiederhergestellt werden, konnte aber nicht identifiziert werden. Details stehen im Anwendungsprotokoll.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: System Proxy systemProxy: System Proxy
tun: TUN tun: TUN
profile: Profile profile: Profile
profileRecovery:
named: Subscription “{name}” needs recovery. See the application log for details.
unknown: Subscription recovery is required. The affected subscription could not be identified. See the application log for details.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proxy del sistema systemProxy: Proxy del sistema
tun: TUN tun: TUN
profile: Perfil profile: Perfil
profileRecovery:
named: Hay que recuperar la suscripción «{name}». Consulta el registro de la aplicación para más detalles.
unknown: Hay que recuperar una suscripción, pero no se pudo identificar cuál. Consulta el registro de la aplicación para más detalles.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: پروکسی سیستم systemProxy: پروکسی سیستم
tun: TUN tun: TUN
profile: پروفایل profile: پروفایل
profileRecovery:
named: اشتراک «{name}» باید بازیابی شود. برای جزئیات، گزارش برنامه را ببینید.
unknown: بازیابی اشتراک لازم است، اما اشتراک موردنظر شناسایی نشد. برای جزئیات، گزارش برنامه را ببینید.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proksi Sistem systemProxy: Proksi Sistem
tun: TUN tun: TUN
profile: Profil profile: Profil
profileRecovery:
named: Langganan “{name}” perlu dipulihkan. Lihat log aplikasi untuk detailnya.
unknown: Langganan perlu dipulihkan, tetapi langganan yang terdampak tidak dapat diidentifikasi. Lihat log aplikasi untuk detailnya.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: システムプロキシ systemProxy: システムプロキシ
tun: TUN tun: TUN
profile: プロファイル profile: プロファイル
profileRecovery:
named: サブスクリプション「{name}」の復旧が必要です。詳細はアプリのログを確認してください。
unknown: サブスクリプションの復旧が必要ですが、対象を特定できません。詳細はアプリのログを確認してください。
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 시스템 프록시 systemProxy: 시스템 프록시
tun: TUN tun: TUN
profile: 프로필 profile: 프로필
profileRecovery:
named: “{name}” 구독을 복구해야 합니다. 자세한 내용은 앱 로그를 확인하세요.
unknown: 구독을 복구해야 하지만 해당 구독을 식별할 수 없습니다. 자세한 내용은 앱 로그를 확인하세요.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Proxy do sistema systemProxy: Proxy do sistema
tun: TUN tun: TUN
profile: Perfil profile: Perfil
profileRecovery:
named: É necessário recuperar a assinatura “{name}”. Consulte o registro do aplicativo para mais detalhes.
unknown: É necessário recuperar uma assinatura, mas não foi possível identificá-la. Consulte o registro do aplicativo para mais detalhes.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Системный прокси systemProxy: Системный прокси
tun: TUN tun: TUN
profile: Профиль profile: Профиль
profileRecovery:
named: Подписку «{name}» нужно восстановить. Подробности в журнале приложения.
unknown: Не удалось определить, какую подписку необходимо восстановить. Подробности в журнале приложения.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Sistem Vekil'i systemProxy: Sistem Vekil'i
tun: TUN tun: TUN
profile: Profil profile: Profil
profileRecovery:
named: “{name}” aboneliğinin kurtarılması gerekiyor. Ayrıntılar için uygulama günlüğüne bakın.
unknown: Kurtarılması gereken abonelik belirlenemedi. Ayrıntılar için uygulama günlüğüne bakın.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: Системалы прокси systemProxy: Системалы прокси
tun: TUN tun: TUN
profile: Профиль profile: Профиль
profileRecovery:
named: «{name}» язылуын торгызырга кирәк. Тулырак мәгълүмат кушымта журналында.
unknown: Кайсы язылуны торгызырга кирәклеген билгеләп булмады. Тулырак мәгълүмат кушымта журналында.
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 系统代理 systemProxy: 系统代理
tun: TUN tun: TUN
profile: 订阅 profile: 订阅
profileRecovery:
named: 订阅「{name}」需要恢复,详情请查看应用日志。
unknown: 订阅需要恢复,但无法识别受影响的订阅。详情请查看应用日志。
+3
View File
@@ -85,3 +85,6 @@ tray:
systemProxy: 系統代理 systemProxy: 系統代理
tun: 虛擬網路介面卡 tun: 虛擬網路介面卡
profile: 訂閱 profile: 訂閱
profileRecovery:
named: 訂閱「{name}」需要復原,詳情請查看應用程式記錄。
unknown: 訂閱需要復原,但無法識別受影響的訂閱。詳情請查看應用程式記錄。
+8 -5
View File
@@ -23,17 +23,20 @@ fn resolve_supported_language(language: &str) -> Option<Cow<'static, str>> {
return None; return None;
} }
let normalized = language.to_lowercase().replace('_', "-"); let normalized = language.to_lowercase().replace('_', "-");
let segments: Vec<&str> = normalized.split('-').collect(); let mut prefix = normalized.as_str();
for i in (1..=segments.len()).rev() { loop {
let prefix = segments[..i].join("-"); if let Some(alias) = locale_alias(prefix)
if let Some(alias) = locale_alias(&prefix)
&& let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias)) && let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(alias))
{ {
return Some(found.clone()); return Some(found.clone());
} }
if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(&prefix)) { if let Some(found) = SUPPORTED_LOCALES.iter().find(|l| l.eq_ignore_ascii_case(prefix)) {
return Some(found.clone()); return Some(found.clone());
} }
let Some((shorter, _)) = prefix.rsplit_once('-') else {
break;
};
prefix = shorter;
} }
None None
} }
+6
View File
@@ -5,5 +5,11 @@ edition = "2024"
[dependencies] [dependencies]
[dev-dependencies]
proptest = { workspace = true }
[target.'cfg(loom)'.dependencies]
loom = { workspace = true }
[lints] [lints]
workspace = true workspace = true
+43 -6
View File
@@ -1,5 +1,12 @@
#[cfg(loom)]
use loom::sync::Arc;
#[cfg(loom)]
use loom::sync::atomic::AtomicU64;
#[cfg(not(loom))]
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering}; #[cfg(not(loom))]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub type SystemLimiter = Limiter<SystemClock>; pub type SystemLimiter = Limiter<SystemClock>;
@@ -38,6 +45,7 @@ pub struct Limiter<C: Clock = SystemClock> {
} }
impl<C: Clock> Limiter<C> { impl<C: Clock> Limiter<C> {
#[cfg(not(loom))]
pub const fn new(period: Duration, clock: C) -> Self { pub const fn new(period: Duration, clock: C) -> Self {
Self { Self {
last_run_ms: AtomicU64::new(0), last_run_ms: AtomicU64::new(0),
@@ -46,11 +54,21 @@ impl<C: Clock> Limiter<C> {
} }
} }
pub fn check(&self) -> bool { #[cfg(loom)]
let now = self.clock.now_ms(); pub fn new(period: Duration, clock: C) -> Self {
let last = self.last_run_ms.load(Ordering::Relaxed); Self {
last_run_ms: AtomicU64::new(0),
period_ms: period.as_millis() as u64,
clock,
}
}
if now < last + self.period_ms && now >= last { pub fn check(&self) -> bool {
// Load before sampling so a stale sample cannot move a newer admission backward.
let last = self.last_run_ms.load(Ordering::Relaxed);
let now = self.clock.now_ms();
if now >= last && now - last < self.period_ms {
return false; return false;
} }
@@ -74,6 +92,22 @@ mod tests {
} }
} }
#[test]
fn system_clock_reports_unix_epoch_milliseconds() {
const MAX_DRIFT_MS: u64 = 5 * 60 * 1_000;
let wall_clock_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let clock_ms = SystemClock.now_ms();
assert!(
clock_ms.abs_diff(wall_clock_ms) <= MAX_DRIFT_MS,
"SystemClock::now_ms() should return Unix epoch milliseconds, got {clock_ms} while wall clock is {wall_clock_ms}"
);
}
#[test] #[test]
fn enforces_the_period_boundary() { fn enforces_the_period_boundary() {
let clock = MockClock(AtomicU64::new(1_000)); let clock = MockClock(AtomicU64::new(1_000));
@@ -100,7 +134,10 @@ mod tests {
} }
let admitted = handles let admitted = handles
.into_iter() .into_iter()
.map(|handle| handle.join().unwrap_or(false)) .map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|passed| *passed) .filter(|passed| *passed)
.count(); .count();
+225
View File
@@ -0,0 +1,225 @@
#![cfg(loom)]
use std::sync::atomic::Ordering;
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use loom::sync::Arc;
use loom::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
const PERIOD_MS: u64 = 100;
const START_MS: u64 = 1_000;
struct MockClock(AtomicU64);
impl Clock for MockClock {
fn now_ms(&self) -> u64 {
self.0.load(Ordering::SeqCst)
}
}
type TestLimiter = Limiter<Arc<MockClock>>;
struct AdvancingClock(AtomicU64);
impl Clock for AdvancingClock {
fn now_ms(&self) -> u64 {
self.0.fetch_add(1, Ordering::SeqCst)
}
}
fn limiter_at(now_ms: u64) -> (Arc<MockClock>, Arc<TestLimiter>) {
let clock = Arc::new(MockClock(AtomicU64::new(now_ms)));
let limiter = Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock));
(clock, Arc::new(limiter))
}
fn run_two_concurrent_checks<C: Clock + 'static>(limiter: &Arc<Limiter<C>>) -> usize {
let handles: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(limiter);
loom::thread::spawn(move || limiter.check())
});
handles
.into_iter()
.map(|handle| match handle.join() {
Ok(admitted) => admitted,
Err(panic) => std::panic::resume_unwind(panic),
})
.filter(|admitted| *admitted)
.count()
}
#[test]
fn admits_exactly_one_caller_in_an_eligible_window() {
loom::model(|| {
let (_clock, limiter) = limiter_at(START_MS);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn rejects_concurrent_callers_inside_the_restricted_period() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS - 1, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 0);
});
}
#[test]
fn admits_exactly_one_caller_at_the_period_boundary() {
loom::model(|| {
let (clock, limiter) = limiter_at(START_MS);
assert!(limiter.check());
clock.0.store(START_MS + PERIOD_MS, Ordering::SeqCst);
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
#[test]
fn concurrent_clock_advancement_admits_exactly_one_caller() {
loom::model(|| {
let clock = Arc::new(AdvancingClock(AtomicU64::new(START_MS)));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
assert_eq!(run_two_concurrent_checks(&limiter), 1);
});
}
struct StaleClock {
current: AtomicU64,
reads: AtomicUsize,
stale_reads: usize,
sampled: AtomicUsize,
released: AtomicBool,
}
impl StaleClock {
fn new(now_ms: u64, stale_reads: usize) -> Self {
Self {
current: AtomicU64::new(now_ms),
reads: AtomicUsize::new(0),
stale_reads,
sampled: AtomicUsize::new(0),
released: AtomicBool::new(false),
}
}
fn release(&self) {
self.released.store(true, Ordering::SeqCst);
}
}
impl Clock for StaleClock {
fn now_ms(&self) -> u64 {
if self.reads.fetch_add(1, Ordering::SeqCst) < self.stale_reads {
let stale = self.current.load(Ordering::SeqCst);
self.sampled.fetch_add(1, Ordering::SeqCst);
// Parking can wake spuriously; re-check the release flag on each
// wake. Unparking after setting the flag avoids a lost wakeup.
while !self.released.load(Ordering::SeqCst) {
loom::thread::park();
}
stale
} else {
self.current.load(Ordering::SeqCst)
}
}
}
/// Regression: a caller that sampled the clock before a newer admission must
/// not overwrite that admission when it resumes.
#[test]
fn stale_clock_sample_does_not_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 1));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
while clock.sampled.load(Ordering::SeqCst) < 1 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
let later_caller = {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
};
let later_admitted = later_caller.join().unwrap();
assert!(
later_admitted,
"the later caller must be admitted before the stale caller resumes"
);
clock.release();
stale_caller.thread().unpark();
let stale_admitted = stale_caller.join().unwrap();
let reopened = limiter.check();
assert!(
!stale_admitted,
"stale caller must not be admitted after the later caller"
);
assert!(
!reopened,
"stale caller admitted={stale_admitted} moved last_run_ms from {LATER_MS} back to {START_MS}"
);
});
}
#[test]
fn multiple_stale_clock_samples_cannot_reopen_the_period() {
loom::model(|| {
const LATER_MS: u64 = START_MS + PERIOD_MS * 10;
let clock = Arc::new(StaleClock::new(START_MS, 2));
let limiter = Arc::new(Limiter::new(Duration::from_millis(PERIOD_MS), Arc::clone(&clock)));
let stale_callers: [_; 2] = std::array::from_fn(|_| {
let limiter = Arc::clone(&limiter);
loom::thread::spawn(move || limiter.check())
});
while clock.sampled.load(Ordering::SeqCst) < 2 {
loom::thread::yield_now();
}
clock.current.store(LATER_MS, Ordering::SeqCst);
assert!(
limiter.check(),
"the later caller must be admitted before the stale callers resume"
);
clock.release();
for caller in &stale_callers {
caller.thread().unpark();
}
let stale_admitted = stale_callers
.into_iter()
.map(|caller| caller.join().unwrap())
.filter(|admitted| *admitted)
.count();
assert_eq!(
stale_admitted, 0,
"stale callers must not be admitted after the later caller"
);
assert!(!limiter.check(), "stale callers reopened the period at {LATER_MS}");
});
}
@@ -0,0 +1,7 @@
# Seeds for failure cases proptest has generated in the past. It is
# automatically read and these particular cases re-run before any
# novel cases are generated.
#
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 0139d921e3faaf32821ee0c596b0d495ffc72ce94200b8d5a795883db56305e6 # shrinks to period = 56, start = 18446744073709551560
@@ -0,0 +1,211 @@
#![cfg(not(loom))]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use clash_verge_limiter::{Clock, Limiter};
use proptest::prelude::*;
use proptest::test_runner::FileFailurePersistence;
const CASES: u32 = 10_000;
const MAX_PERIOD_MS: u64 = 100_000;
const MAX_START_MS: u64 = 1_000_000;
const MAX_DELTA_MS: u64 = 10_000;
/// Returns one clock value per call, in order. The test supplies exactly as
/// many values as the limiter will read.
struct SequenceClock {
values: Vec<u64>,
next: AtomicUsize,
}
impl SequenceClock {
const fn new(values: Vec<u64>) -> Self {
Self {
values,
next: AtomicUsize::new(0),
}
}
}
impl Clock for SequenceClock {
fn now_ms(&self) -> u64 {
let index = self.next.fetch_add(1, Ordering::SeqCst);
self.values[index]
}
}
fn timestamps(start: u64, deltas: &[u64]) -> Vec<u64> {
let mut now = start;
let mut values = Vec::with_capacity(deltas.len() + 1);
values.push(now);
for delta in deltas {
now += delta;
values.push(now);
}
values
}
proptest! {
#![proptest_config(ProptestConfig {
cases: CASES,
failure_persistence: Some(Box::new(FileFailurePersistence::Direct(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/properties.proptest-regressions"
)))),
..ProptestConfig::default()
})]
/// For positive periods and nondecreasing time, admission is equivalent to
/// reaching the next allowed timestamp after the previous admission.
#[test]
fn sequential_results_match_the_next_allowed_time_contract(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut last_admitted = None;
for now in times {
let expected = match last_admitted {
None => true,
Some(last) => now >= last + period,
};
let actual = limiter.check();
prop_assert!(
actual == expected,
"period={} now={} last={:?}",
period,
now,
last_admitted
);
if actual {
last_admitted = Some(now);
}
}
}
/// An admission at the period boundary is accepted, while a repeated or
/// pre-boundary check is rejected.
#[test]
fn period_boundary_and_repeated_checks_follow_the_period(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
) {
let boundary = start + period;
let clock = SequenceClock::new(vec![start, start, boundary - 1, boundary]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check(), "first check at {}", start);
prop_assert!(!limiter.check(), "repeated check at {}", start);
prop_assert!(!limiter.check(), "pre-boundary check at {}", boundary - 1);
prop_assert!(limiter.check(), "boundary check at {}", boundary);
}
/// Any two admitted timestamps in a monotonic sequence are separated by at
/// least one configured period.
#[test]
fn admitted_timestamps_are_at_least_one_period_apart(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let clock = SequenceClock::new(times.clone());
let limiter = Limiter::new(Duration::from_millis(period), &clock);
let mut admitted = Vec::new();
for now in times {
if limiter.check() {
admitted.push(now);
}
}
for pair in admitted.windows(2) {
prop_assert!(
pair[1] - pair[0] >= period,
"period={} admitted pair={:?}",
period,
pair
);
}
}
/// A rejected duplicate at the current admission timestamp must not change
/// the outcomes of later checks.
#[test]
fn rejected_checks_do_not_change_future_admissions(
period in 1u64..=MAX_PERIOD_MS,
start in MAX_PERIOD_MS..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let base_times = timestamps(start, &deltas);
let base_clock = SequenceClock::new(base_times.clone());
let base = Limiter::new(Duration::from_millis(period), &base_clock);
let base_results: Vec<bool> = base_times.iter().map(|_| base.check()).collect();
let mut repeated_times = vec![start, start];
repeated_times.extend_from_slice(&base_times[1..]);
let repeated_len = repeated_times.len();
let repeated_clock = SequenceClock::new(repeated_times);
let repeated = Limiter::new(Duration::from_millis(period), &repeated_clock);
let repeated_results: Vec<bool> = (0..repeated_len).map(|_| repeated.check()).collect();
prop_assert!(repeated_results[0]);
prop_assert!(!repeated_results[1]);
prop_assert_eq!(&base_results[1..], &repeated_results[2..]);
}
/// Every sub-millisecond period is represented as zero milliseconds, so it
/// must produce the same admissions as `Duration::ZERO`. This deliberately
/// does not assert a policy for zero periods.
#[test]
fn zero_and_submillisecond_periods_are_equivalent(
nanos in 0u64..1_000_000,
start in 0u64..=MAX_START_MS,
deltas in prop::collection::vec(0u64..=MAX_DELTA_MS, 0..64),
) {
let times = timestamps(start, &deltas);
let zero_clock = SequenceClock::new(times.clone());
let zero = Limiter::new(Duration::ZERO, &zero_clock);
let submillisecond_clock = SequenceClock::new(times.clone());
let submillisecond =
Limiter::new(Duration::from_nanos(nanos), &submillisecond_clock);
for now in times {
prop_assert_eq!(
zero.check(),
submillisecond.check(),
"nanos={} now={}",
nanos,
now
);
}
}
/// Regression: timestamp arithmetic must not overflow near `u64::MAX`.
#[test]
fn extreme_timestamp_and_period_do_not_overflow(
period in 1u64..=1_000,
start in (u64::MAX - 1_000)..=u64::MAX,
) {
let clock = SequenceClock::new(vec![start, start]);
let limiter = Limiter::new(Duration::from_millis(period), &clock);
prop_assert!(limiter.check());
prop_assert!(!limiter.check());
}
}
#[test]
fn max_timestamp_boundary_does_not_overflow() {
let clock = SequenceClock::new(vec![u64::MAX - 1, u64::MAX, u64::MAX]);
let limiter = Limiter::new(Duration::from_millis(1), &clock);
assert!(limiter.check());
assert!(limiter.check());
assert!(!limiter.check());
}
+1 -1
View File
@@ -6,7 +6,7 @@ edition = "2024"
[dependencies] [dependencies]
log = { workspace = true } log = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
anyhow = { workspace = true } thiserror = { workspace = true }
flexi_logger = { workspace = true } flexi_logger = { workspace = true }
tracing-estuary = { workspace = true } tracing-estuary = { workspace = true }
+11
View File
@@ -0,0 +1,11 @@
#[derive(Debug, thiserror::Error)]
pub enum LoggerError {
#[error(transparent)]
Pipeline(Box<dyn std::error::Error + Send + Sync>),
#[error(transparent)]
Sidecar(#[from] flexi_logger::FlexiLoggerError),
#[error("failed to get tracing pipeline, make sure it init")]
PipelineUnavailable,
#[error("failed to reset log writer: {0}")]
ResetWriter(String),
}
+18 -12
View File
@@ -1,3 +1,7 @@
mod error;
pub use error::LoggerError;
use std::{ use std::{
collections::VecDeque, collections::VecDeque,
fmt, fmt,
@@ -10,7 +14,6 @@ use std::{
time::Duration, time::Duration,
}; };
use anyhow::{Result, bail};
use flexi_logger::{ use flexi_logger::{
Cleanup, Criterion, DeferredNow, FileSpec, Naming, Cleanup, Criterion, DeferredNow, FileSpec, Naming,
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _}, writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
@@ -177,7 +180,7 @@ impl Logger {
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare /// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
/// level) overrides the configured level. /// level) overrides the configured level.
pub fn init(&self, cfg: &LoggerConfig) -> Result<()> { pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
let log_level = std::env::var("RUST_LOG") let log_level = std::env::var("RUST_LOG")
.ok() .ok()
.and_then(|v| LevelFilter::from_str(v.trim()).ok()) .and_then(|v| LevelFilter::from_str(v.trim()).ok())
@@ -186,14 +189,15 @@ impl Logger {
let pipeline = tracing_estuary::PipelineBuilder::new() let pipeline = tracing_estuary::PipelineBuilder::new()
.default_level(log_level) .default_level(log_level)
.file_writer(self.generate_file_log_writer()) .file_writer(self.generate_file_log_writer())
.init()?; .init()
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
self.pipeline.set(pipeline).ok(); self.pipeline.set(pipeline).ok();
Ok(()) Ok(())
} }
/// Installs the sidecar file writer and the panic hook. Safe to call when /// Installs the sidecar file writer and the panic hook. Safe to call when
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber). /// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> { pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
self.store_config(cfg); self.store_config(cfg);
self.ensure_sidecar_writer(self.generate_sidecar_builder())?; self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
@@ -245,7 +249,7 @@ impl Logger {
/// Ensures the sidecar writer exists and points at `builder`'s config: /// Ensures the sidecar writer exists and points at `builder`'s config:
/// built once, then reset in place — flexi's flusher thread cannot be /// built once, then reset in place — flexi's flusher thread cannot be
/// stopped, so every dropped writer would leak a thread and an fd. /// stopped, so every dropped writer would leak a thread and an fd.
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> { fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> {
let sidecar = self.sidecar_file_writer.write(); let sidecar = self.sidecar_file_writer.write();
match sidecar.as_ref() { match sidecar.as_ref() {
Some(writer) => { Some(writer) => {
@@ -296,27 +300,29 @@ impl Logger {
} }
/// only update app log level /// only update app log level
pub fn update_log_level(&self, level: LevelFilter) -> Result<()> { pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> {
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
pipeline.filter.set_default_level(level)?; pipeline
.filter
.set_default_level(level)
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
} else { } else {
bail!("failed to get tracing pipeline, make sure it init"); return Err(LoggerError::PipelineUnavailable);
}; };
Ok(()) Ok(())
} }
/// Rebuilds both file writers with the new limits. /// Rebuilds both file writers with the new limits.
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> { pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> {
self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(pipeline) = self.pipeline.get() { if let Some(pipeline) = self.pipeline.get() {
let log_file_writer = self.generate_file_log_writer(); let log_file_writer = self.generate_file_log_writer();
if let Some(sink) = pipeline.sink.as_ref() { if let Some(sink) = pipeline.sink.as_ref() {
sink.reset(log_file_writer) sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?;
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
} }
} else { } else {
bail!("failed to get tracing pipeline, make sure it init"); return Err(LoggerError::PipelineUnavailable);
}; };
self.ensure_sidecar_writer(self.generate_sidecar_builder())?; self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
Ok(()) Ok(())
@@ -0,0 +1,16 @@
[package]
name = "clash-verge-profile-script"
version = "0.1.0"
edition = "2024"
[dependencies]
boa_engine = { workspace = true }
clash-verge-logging = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
tokio = { workspace = true }
tristr = { workspace = true }
[lints]
workspace = true
@@ -1,79 +1,64 @@
use crate::{process::AsyncHandler, utils::tmpl};
use super::field::use_lowercase;
use anyhow::Result;
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute}; use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use std::sync::Arc; use std::cell::{Cell, RefCell};
use std::rc::Rc;
use tristr::alias::String; use tristr::alias::String;
const MAX_OUTPUTS: usize = 1000; const MAX_OUTPUTS: usize = 1000;
const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB const MAX_OUTPUT_SIZE: usize = 1024 * 1024; // 1MB
const MAX_PROFILE_NAME_BYTES: usize = 1024;
const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB const MAX_JSON_SIZE: usize = 10 * 1024 * 1024; // 10MB
const MAX_LOOP_ITERATIONS: u64 = 10_000_000; const MAX_LOOP_ITERATIONS: u64 = 10_000_000;
const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); const SCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
type ScriptResult = (Mapping, Vec<String>, Vec<(String, String)>); /// Script logs are retained when evaluation or result conversion fails.
type EvalOutcome = (Result<Mapping, std::string::String>, Vec<(String, String)>); pub type ScriptLogs = Vec<(String, String)>;
/// Never fails: exceptions are logged and the input config is returned unchanged. type EvalOutcome = (Result<Mapping, std::string::String>, ScriptLogs);
pub(super) async fn use_script(script: String, config: Mapping, name: String) -> ScriptResult {
// The template is identity-plus-lowercasing; skip the Boa round-trip. #[derive(Debug, PartialEq, Eq)]
if script == tmpl::ITEM_SCRIPT { pub enum MainDeclaration {
return (use_lowercase(config), vec![], vec![]); Present,
Missing,
}
/// Evaluates the source and checks that the entry point is callable.
pub fn validate(source: &str) -> Result<MainDeclaration, std::string::String> {
let mut context = Context::default();
let _ = context.eval(Source::from_bytes(
"var console = Object.freeze({log(...data){},info(...data){},error(...data){},debug(...data){},warn(...data){},table(...data){}});",
));
context
.eval(Source::from_bytes(source))
.map_err(|err| err.to_string())?;
let has_main = context
.eval(Source::from_bytes("typeof main === 'function'"))
.map_err(|err| err.to_string())?
.to_boolean();
Ok(if has_main {
MainDeclaration::Present
} else {
MainDeclaration::Missing
})
}
/// Runs one script on the blocking pool. The timeout bounds waiting for its result.
pub async fn execute(script: String, config: serde_json::Value, name: String) -> EvalOutcome {
if json_approx_size(&config) > MAX_JSON_SIZE {
return (
Err("Configuration size exceeds maximum allowed size".to_owned()),
vec![],
);
} }
let evaluated = tokio::task::spawn_blocking(move || eval_script(&script, &config, &name));
let json = match serde_json::to_value(&config) { match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
Ok(mut json) => {
if let Some(map) = json.as_object_mut() {
let mut lowered = serde_json::Map::with_capacity(map.len());
for (key, value) in std::mem::take(map) {
let mut key = key;
key.make_ascii_lowercase();
lowered.insert(key, value);
}
*map = lowered;
}
if json_approx_size(&json) <= MAX_JSON_SIZE {
json
} else {
let message = "Configuration size exceeds maximum allowed size";
return (config, vec![], vec![("exception".into(), message.into())]);
}
}
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
};
let evaluated = AsyncHandler::spawn_blocking(move || eval_script(&script, &json, &name));
let (outcome, mut logs) = match tokio::time::timeout(SCRIPT_TIMEOUT, evaluated).await {
Ok(Ok(evaluated)) => evaluated, Ok(Ok(evaluated)) => evaluated,
Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]), Ok(Err(join_err)) => (Err(format!("script task panicked: {join_err}")), vec![]),
Err(_elapsed) => ( Err(_) => (
Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")), Err(format!("script execution timed out after {SCRIPT_TIMEOUT:?}")),
vec![], vec![],
), ),
};
match outcome {
Ok(result) => {
// Compared against the config as handed in, not the lowercased copy the script saw.
let changed_keys = result
.iter()
.filter(|(key, value)| config.get(key) != Some(value))
.filter_map(|(key, _)| {
let mut key: String = key.as_str()?.into();
key.make_ascii_lowercase();
Some(key)
})
.collect();
(result, changed_keys, logs)
}
Err(reason) => {
logs.push(("exception".into(), reason.into()));
(config, vec![], logs)
}
} }
} }
@@ -85,13 +70,11 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
.runtime_limits_mut() .runtime_limits_mut()
.set_loop_iteration_limit(MAX_LOOP_ITERATIONS); .set_loop_iteration_limit(MAX_LOOP_ITERATIONS);
let outputs = Arc::new(Mutex::new(vec![])); let logs = Rc::new(RefCell::new(Vec::new()));
let total_size = Arc::new(Mutex::new(0usize)); let console_logs = Rc::clone(&logs);
let logged_bytes = Cell::new(0);
let outputs_clone = Arc::clone(&outputs); let take_logs = || logs.take();
let total_size_clone = Arc::clone(&total_size); 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 { let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| { NativeFunction::from_closure(move |_: &JsValue, args: &[JsValue], context: &mut Context| {
@@ -111,23 +94,21 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into()) boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into())
})?; })?;
// 检查输出限制 let mut entries = console_logs.borrow_mut();
if outputs_clone.lock().len() >= MAX_OUTPUTS { if entries.len() >= MAX_OUTPUTS {
return Err(boa_engine::JsError::from_opaque( return Err(boa_engine::JsError::from_opaque(
JsString::from("Maximum number of log outputs exceeded").into(), JsString::from("Maximum number of log outputs exceeded").into(),
)); ));
} }
let mut size = total_size_clone.lock(); let new_size = logged_bytes.get() + level.len() + data.len();
let new_size = *size + level.len() + data.len();
if new_size > MAX_OUTPUT_SIZE { if new_size > MAX_OUTPUT_SIZE {
return Err(boa_engine::JsError::from_opaque( return Err(boa_engine::JsError::from_opaque(
JsString::from("Maximum output size exceeded").into(), JsString::from("Maximum output size exceeded").into(),
)); ));
} }
*size = new_size; logged_bytes.set(new_size);
drop(size); entries.push((level.into(), data.into()));
outputs_clone.lock().push((level.into(), data.into()));
Ok(JsValue::undefined()) Ok(JsValue::undefined())
}) })
}); });
@@ -151,16 +132,14 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
return bail(format!("failed to bind config for script: {err}")); return bail(format!("failed to bind config for script: {err}"));
} }
// 仅处理 name 参数中的特殊字符 let Some(escaped_profile_name) = escape_profile_name(name) else {
let safe_name = escape_js_string_for_single_quote(name);
if safe_name.len() > 1024 {
return bail("Name parameter too long".to_owned()); return bail("Name parameter too long".to_owned());
} };
let code = format!( let code = format!(
r"try{{ r"try{{
{script}; {script};
main(globalThis.__verge_config__,'{safe_name}') main(globalThis.__verge_config__,'{escaped_profile_name}')
}} catch(err) {{ }} catch(err) {{
`__error_flag__ ${{err.toString()}}` `__error_flag__ ${{err.toString()}}`
}}" }}"
@@ -214,7 +193,7 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
} }
match serde_json::from_value::<Mapping>(result) { match serde_json::from_value::<Mapping>(result) {
Ok(config) => (Ok(use_lowercase(config)), outputs.lock().to_vec()), Ok(config) => (Ok(config), take_logs()),
Err(err) => { Err(err) => {
logging!( logging!(
error, error,
@@ -235,21 +214,92 @@ fn json_approx_size(value: &serde_json::Value) -> usize {
.map(|(key, value)| key.len() + 4 + json_approx_size(value)) .map(|(key, value)| key.len() + 4 + json_approx_size(value))
.sum(), .sum(),
serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(), serde_json::Value::Array(items) => items.iter().map(json_approx_size).sum(),
serde_json::Value::Number(n) => n.to_string().len(), serde_json::Value::Number(n) => {
if let Some(n) = n.as_u64() {
n.checked_ilog10().unwrap_or(0) as usize + 1
} else if let Some(n) = n.as_i64() {
n.unsigned_abs().checked_ilog10().unwrap_or(0) as usize + 2
} else {
n.to_string().len()
}
}
serde_json::Value::Bool(_) | serde_json::Value::Null => 4, serde_json::Value::Bool(_) | serde_json::Value::Null => 4,
} }
} }
// 安全地转义字符串 fn escape_profile_name(name: &str) -> Option<String> {
fn escape_js_string_for_single_quote(s: &str) -> String { if name.len() > MAX_PROFILE_NAME_BYTES {
// 限制处理的字符串长度 return None;
if s.len() > 10240 { }
return s[..10240].replace('\\', "\\\\").replace('\'', "\\'").into(); let escaped = name
.replace('\\', "\\\\")
.replace('\'', "\\'")
.replace('\n', "\\n")
.replace('\r', "\\r");
(escaped.len() <= MAX_PROFILE_NAME_BYTES).then(|| escaped.into())
}
#[cfg(test)]
mod tests {
use super::{MainDeclaration, eval_script, validate};
#[test]
fn profile_name_limit_counts_escaped_bytes() {
assert!(super::escape_profile_name(&"订阅".repeat(171)).is_none());
assert!(super::escape_profile_name(&"'".repeat(512)).is_some());
assert!(super::escape_profile_name(&"'".repeat(513)).is_none());
} }
s.replace('\\', "\\\\") #[test]
.replace('\'', "\\'") fn numeric_size_matches_the_rendered_number() {
.replace('\n', "\\n") // 添加换行符转义 for number in [
.replace('\r', "\\r") // 添加回车转义 0.into(),
.into() 10.into(),
(-10).into(),
i64::MIN.into(),
u64::MAX.into(),
serde_json::json!(1.25),
] {
assert_eq!(super::json_approx_size(&number), number.to_string().len());
}
}
#[test]
fn console_entries_survive_a_script_error() {
let (result, logs) = eval_script(
"function main() { console.log(1); console.warn(2); throw Error(); }",
&serde_json::json!({}),
&"profile".into(),
);
assert!(result.is_err());
assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]);
}
#[test]
fn validation_checks_the_evaluated_main_binding() {
assert_eq!(
validate("const main = config => config;"),
Ok(MainDeclaration::Present)
);
assert_eq!(validate("// function main goes here"), Ok(MainDeclaration::Missing));
assert_eq!(validate("const main = 42;"), Ok(MainDeclaration::Missing));
}
#[test]
fn validation_supports_console_methods_at_top_level() {
assert_eq!(
validate("console.warn('setup'); console.table([1]); function main(config) { return config; }"),
Ok(MainDeclaration::Present)
);
}
#[test]
fn validation_distinguishes_missing_main_from_evaluation_failure() {
assert_eq!(
validate("console.log('setup'); const main = config => config;"),
Ok(MainDeclaration::Present)
);
assert_eq!(validate("console.log('setup');"), Ok(MainDeclaration::Missing));
assert!(validate("throw new Error('setup failed'); function main(config) { return config; }").is_err());
}
} }
@@ -0,0 +1,28 @@
[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",
] }
@@ -0,0 +1,78 @@
use std::{io, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("could not recover subscription “{name}”: {source}")]
NamedRecovery { name: String, source: Box<Self> },
#[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),
}
+820
View File
@@ -0,0 +1,820 @@
//! 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";
const MAX_COMPANIONS: usize = 5;
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],
#[serde(default, skip_serializing_if = "Vec::is_empty")]
companions: Vec<Companion>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Companion {
uid: String,
digest: [u8; 32],
}
fn companion_file<'a>(profiles: &'a IProfiles, parent: &str, uid: &str) -> Result<&'a str> {
let item = profiles.get_item(uid)?;
let options = profiles
.get_item(parent)?
.option
.as_ref()
.ok_or(StoreError::DecisionTargetMismatch)?;
let reference = match item.itype.as_deref() {
Some("merge") => &options.merge,
Some("script") => &options.script,
Some("rules") => &options.rules,
Some("proxies") => &options.proxies,
Some("groups") => &options.groups,
_ => return Err(StoreError::DecisionTargetMismatch),
};
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
validate_filename(file)?;
if reference.as_deref() != Some(uid)
|| profiles
.items
.iter()
.flatten()
.filter(|other| other.uid.as_deref() == Some(uid) || other.file.as_deref() == Some(file))
.count()
!= 1
{
return Err(StoreError::DecisionTargetMismatch);
}
Ok(file)
}
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)? {
let source = StoreError::UnsupportedVolume;
return Err(match pending_refresh_name(&root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(source),
},
None => source,
});
}
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
lock.lock()?;
let session = Self { root, _lock: lock };
session
.recover(checkpoint)
.map_err(|error| match refresh_name(&session.root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(error),
},
None => error,
})?;
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 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 new_item = candidate.get_item(uid)?;
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, 1)?;
unshared_body(&profiles_dir, candidate, file, 1)?;
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 mut index = b"# Profiles Config for Clash Verge\n\n".to_vec();
serde_yaml_ng::to_writer(&mut index, candidate)?;
let mut companions = Vec::new();
let mut templates = Vec::new();
for item in candidate.items.iter().flatten() {
let Some(data) = &item.file_data else { continue };
let id = item.uid.as_deref().ok_or(StoreError::DecisionTargetMismatch)?;
let file = companion_file(candidate, uid, id)?;
if current
.items
.iter()
.flatten()
.any(|old| old.uid.as_deref() == Some(id) || old.file.as_deref() == Some(file))
|| optional_regular(&profiles_dir.join(file))?.is_some()
{
return Err(StoreError::ExistingBodyPath);
}
let bytes = data.as_bytes();
companions.push(Companion {
uid: id.to_owned(),
digest: Sha256::digest(bytes).into(),
});
templates.push(bytes);
}
if companions.len() > MAX_COMPANIONS {
return Err(StoreError::DecisionTargetMismatch);
}
let decision = Decision {
version: if companions.is_empty() { 1 } else { 2 },
companions,
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).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")?;
for (slot, bytes) in templates.into_iter().enumerate() {
write_new(&journal.join(format!("companion.{slot}")), bytes, None)?;
}
write_new(&journal.join(INDEX_NEXT), &index, 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, 1)?;
}
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, 1)?;
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, 1)?;
}
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));
}
}
let old_companion_index: Option<IProfiles> = if !index_installed && !decision.companions.is_empty() {
let (index, _) = verified(&index_path, decision.old_index_digest)?;
Some(serde_yaml_ng::from_slice(&index)?)
} else {
None
};
for (slot, companion) in decision.companions.iter().enumerate() {
let file = companion_file(&candidate, &decision.uid, &companion.uid)?;
let staged = journal.join(format!("companion.{slot}"));
if file_digest(&staged)? != companion.digest {
return Err(StoreError::StagedChecksumMismatch);
}
let target = profiles_dir.join(file);
match fs::hard_link(&staged, &target) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
if platform::file_identity(&target, &regular(&target)?)?
!= platform::file_identity(&staged, &regular(&staged)?)?
{
return Err(StoreError::LiveContentChanged(target));
}
}
Err(error) => return Err(error.into()),
}
unshared_body(&profiles_dir, &candidate, file, 2)?;
if let Some(old) = &old_companion_index {
unshared_body(&profiles_dir, old, file, 2)?;
}
checkpoint("companion-installed")?;
}
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))?;
}
match fs::remove_dir(&journal) {
Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
for slot in 0..MAX_COMPANIONS {
remove_file_if_exists(&journal.join(format!("companion.{slot}")))?;
}
fs::remove_dir(&journal)?;
}
result => result?,
}
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);
}
if new_pair && !intent.companions.is_empty() {
let (bytes, _) = verified(&self.root.join(INDEX), intent.index_digest)?;
let candidate = serde_yaml_ng::from_slice(&bytes)?;
for companion in &intent.companions {
let file = companion_file(&candidate, &intent.uid, &companion.uid)?;
let path = self.root.join(PROFILES).join(file);
if optional_file_digest(&path)? != Some(companion.digest) {
return Err(StoreError::LiveContentChanged(path));
}
}
}
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 !matches!(
(decision.version, decision.companions.len()),
(1, 0) | (2, 1..=MAX_COMPANIONS)
) {
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'])
|| (cfg!(windows) && file.contains(':'))
{
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, expected_links: u64) -> Result<Option<fs::Metadata>> {
let mut 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 != expected_links)
{
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)?;
path.set_file_name(other);
match fs::metadata(&path) {
Ok(metadata) => {
if let Some(identity) = &identity
&& platform::file_identity(&path, &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()),
}
}
fn refresh_name(root: &Path) -> Option<String> {
let journal = root.join(RECOVERY_JOURNAL_NAME);
directory(&journal).ok()?;
let marker = match optional_regular(&journal.join(DECISION)).ok()? {
Some(_) => DECISION,
None => DECISION_NEXT,
};
let decision = read_decision(&journal.join(marker)).ok()?;
let (index, _) = verified(&journal.join(INDEX_NEXT), decision.index_digest).ok()?;
let profiles: IProfiles = serde_yaml_ng::from_slice(&index).ok()?;
if body_filename(&profiles, &decision.uid).ok()? != decision.file {
return None;
}
let item = profiles.get_item(&decision.uid).ok()?;
item.name
.as_deref()
.filter(|name| !name.trim().is_empty())
.map(str::to_owned)
}
/// Identifies a pending transaction when this build or volume cannot replay it.
#[cfg(windows)]
pub fn pending_refresh_name(root: &Path) -> Option<String> {
let lock = File::open(root.join(RECOVERY_LOCK_NAME)).ok()?;
lock.try_lock_shared().ok()?;
refresh_name(root)
}
/// 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)?)
}
@@ -0,0 +1,209 @@
#[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()
}
}
@@ -0,0 +1,175 @@
#![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_preserves_native_unix_filenames() -> 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/remote:old.yaml"), b"old")?;
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
let old = "items:\n- {uid: r, type: remote, file: 'remote:old.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/remote:old.yaml"))?, b"new");
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(())
}
#[cfg(feature = "test-support")]
#[test]
fn recovery_identifies_the_interrupted_subscription_from_its_verified_index()
-> Result<(), clash_verge_profile_store::StoreError> {
use clash_verge_profile_store::{StoreError, recover_pending};
let home = tempfile::tempdir()?;
let root = home.path();
fs::create_dir(root.join("profiles"))?;
let index = "current: other\nitems:\n- {uid: other, name: Home, type: remote, file: other.yaml}\n- {uid: opaque, name: 工作线路, type: remote, file: target.yaml}\n";
fs::write(root.join("profiles.yaml"), index)?;
let candidate = serde_yaml_ng::from_str(index)?;
let outcome = Session::open(root)?.commit_observed("opaque", &candidate, b"new", &mut |phase| {
if phase == "decision-created" {
return Err(std::io::Error::other("interrupted").into());
}
Ok(())
});
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)));
fs::write(root.join("profiles/target.yaml"), b"changed outside the refresh")?;
let error = recover_pending(root).unwrap_err();
assert!(
matches!(error, StoreError::NamedRecovery { name, source } if name == "工作线路" && matches!(*source, StoreError::LiveContentChanged(_)))
);
let journal = root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME);
fs::write(journal.join("index.next"), index.replace("工作线路", "Wrong"))?;
assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch)));
Ok(())
}
#[cfg(feature = "test-support")]
#[test]
fn legacy_companions_follow_the_refresh_decision() -> Result<(), clash_verge_profile_store::StoreError> {
for phase in ["prepared", "companion-installed", "decision-removed"] {
let home = tempfile::tempdir()?;
let root = home.path();
let profiles = root.join("profiles");
fs::create_dir(&profiles)?;
let old = "items: [{uid: r, type: remote, file: r.yaml}]";
fs::write(root.join("profiles.yaml"), old)?;
fs::write(profiles.join("r.yaml"), b"old")?;
let mut candidate: IProfiles = serde_yaml_ng::from_str(
"items: [{uid: r, type: remote, file: r.yaml, option: {script: s}}, {uid: s, type: script, file: s.js}]",
)?;
candidate.get_item_mut("s")?.file_data = Some("template".into());
let result = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |checkpoint| {
if checkpoint == phase {
return Err(std::io::Error::other("interrupted").into());
}
Ok(())
});
if phase == "decision-removed" {
assert!(matches!(result, CommitOutcome::CommittedCleanupPending(_)));
fs::write(profiles.join("s.js"), b"edited")?;
assert!(clash_verge_profile_store::recover_pending(root).is_err());
assert_eq!(fs::read(profiles.join("s.js"))?, b"edited");
assert!(root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
continue;
}
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
if phase == "prepared" {
assert!(matches!(result, CommitOutcome::Retryable(_)));
clash_verge_profile_store::recover_pending(root)?;
assert!(!profiles.join("s.js").exists());
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"old");
} else {
assert!(matches!(result, CommitOutcome::NeedsRecovery(_)));
clash_verge_profile_store::recover_pending(root)?;
let stored: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
assert_eq!(stored.get_item("s")?.file.as_deref(), Some("s.js"));
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"new");
assert_eq!(fs::read(profiles.join("s.js"))?, b"template");
}
}
Ok(())
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-profile"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
[lints]
workspace = true
+5
View File
@@ -0,0 +1,5 @@
#[derive(Debug, thiserror::Error)]
#[error("failed to get the profile item \"uid:{uid}\"")]
pub struct ProfileNotFound {
pub(super) uid: String,
}
+397
View File
@@ -0,0 +1,397 @@
mod error;
pub mod selected_nodes;
mod subscription_schedule;
pub use error::ProfileNotFound;
pub use subscription_schedule::SubscriptionSchedule;
use serde::{Deserialize, Serialize};
use tristr::alias::String;
macro_rules! patch_opt_field {
($lv:expr, $rv:expr, $key:tt) => {
if ($rv.$key).is_some() {
$lv.$key = $rv.$key.clone();
}
};
}
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
#[serde(default)]
pub struct PrfItem {
pub uid: Option<String>,
/// enum value: remote | local | script | merge
#[serde(rename = "type")]
pub itype: Option<String>,
pub name: Option<String>,
pub file: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub selected: Option<Vec<PrfSelected>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub extra: Option<PrfExtra>,
pub updated: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub option: Option<PrfOption>,
#[serde(skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
#[serde(skip)]
pub file_data: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfSelected {
pub name: Option<String>,
pub now: Option<String>,
}
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
pub struct PrfExtra {
pub upload: u64,
pub download: u64,
pub total: u64,
pub expire: u64,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
#[serde(default)]
pub struct PrfOption {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub with_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub self_proxy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update_interval: Option<u64>,
/// HTTP request timeout in seconds
/// default is 60 seconds
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_seconds: Option<u64>,
/// default is `false`
#[serde(skip_serializing_if = "Option::is_none")]
pub danger_accept_invalid_certs: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allow_auto_update: Option<bool>,
pub merge: Option<String>,
pub script: Option<String>,
pub rules: Option<String>,
pub proxies: Option<String>,
pub groups: Option<String>,
}
impl PrfOption {
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
match (one, other) {
(Some(a_ref), Some(b_ref)) => {
let mut result = a_ref.clone();
patch_opt_field!(result, b_ref, user_agent);
patch_opt_field!(result, b_ref, with_proxy);
patch_opt_field!(result, b_ref, self_proxy);
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
patch_opt_field!(result, b_ref, allow_auto_update);
patch_opt_field!(result, b_ref, update_interval);
patch_opt_field!(result, b_ref, merge);
patch_opt_field!(result, b_ref, script);
patch_opt_field!(result, b_ref, rules);
patch_opt_field!(result, b_ref, proxies);
patch_opt_field!(result, b_ref, groups);
patch_opt_field!(result, b_ref, timeout_seconds);
Some(result)
}
(Some(a_ref), None) => Some(a_ref.clone()),
(None, Some(b_ref)) => Some(b_ref.clone()),
(None, None) => None,
}
}
}
macro_rules! current_field {
($name:ident, $field:ident) => {
pub fn $name(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.$field.as_ref())
}
};
}
impl PrfItem {
current_field!(current_merge, merge);
current_field!(current_script, script);
current_field!(current_rules, rules);
current_field!(current_proxies, proxies);
current_field!(current_groups, groups);
}
/// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
#[serde(default)]
pub struct IProfiles {
pub current: Option<String>,
pub items: Option<Vec<PrfItem>>,
}
pub struct IProfilePreview<'a> {
pub uid: &'a String,
pub name: &'a String,
pub is_current: bool,
}
pub struct ProfileDeletePlan {
pub deleting_current: bool,
pub files: Vec<String>,
}
impl IProfiles {
pub fn patch_current(&mut self, current: Option<&String>) {
let items = self.items.get_or_insert_with(Vec::new);
if let Some(current) = current
&& items.iter().any(|item| item.uid.as_ref() == Some(current))
{
self.current = Some(current.clone());
}
}
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem, ProfileNotFound> {
let uid = uid.as_ref();
self.items
.iter()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
.ok_or_else(|| ProfileNotFound { uid: uid.to_owned() })
}
pub fn get_item_mut(&mut self, uid: &str) -> Result<&mut PrfItem, ProfileNotFound> {
self.items
.iter_mut()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
.ok_or_else(|| ProfileNotFound { uid: uid.to_owned() })
}
/// Inserts a prepared entry after any required body write.
pub fn append_item(&mut self, item: &PrfItem) {
if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) {
self.current = item.uid.clone();
}
self.items.get_or_insert_with(Vec::new).push(item.clone());
}
/// Returns true if both IDs were found, including when the item stayed at its old position.
pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool {
let Some(items) = self.items.as_mut() else {
return false;
};
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
return false;
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
true
}
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let missing_profile = || ProfileNotFound { uid: uid.to_owned() };
let items = self.items.as_mut().ok_or_else(missing_profile)?;
let profile = remove_item(items, Some(uid)).ok_or_else(missing_profile)?;
let mut files = Vec::from_iter(profile.file);
if let Some(options) = profile.option {
for companion_uid in [
options.merge,
options.script,
options.rules,
options.proxies,
options.groups,
] {
if let Some(file) = remove_item(items, companion_uid.as_deref()).and_then(|item| item.file) {
files.push(file);
}
}
}
if deleting_current {
self.current = items
.iter()
.find(|item| matches!(item.itype.as_deref(), Some("remote" | "local")))
.and_then(|item| item.uid.clone());
}
Ok(ProfileDeletePlan {
deleting_current,
files,
})
}
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
self.items.as_ref().map(|items| {
items
.iter()
.filter_map(|e| {
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
let is_current = self.current.as_ref() == Some(uid);
let preview = IProfilePreview { uid, name, is_current };
Some(preview)
} else {
None
}
})
.collect()
})
}
}
fn remove_item(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<PrfItem> {
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
Some(items.remove(index))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r#"
current: first
items:
- uid: first
type: remote
option: {allow_auto_update: false, update_interval: 0, merge: ""}
file_data: ignored
- uid: second
name: ""
"#,
)?;
let first = profiles.get_item("first")?;
assert!(first.file_data.is_none());
assert_eq!(first.current_merge().map(String::as_str), Some(""));
assert!(first.current_script().is_none());
if let Some(items) = profiles.items.as_mut() {
items[0].file_data = Some("in memory".into());
}
assert_eq!(
serde_json::to_value(&profiles)?,
serde_json::json!({
"current": "first",
"items": [
{"uid": "first", "type": "remote", "name": null, "file": null, "updated": null,
"option": {"allow_auto_update": false, "update_interval": 0, "merge": "",
"script": null, "rules": null, "proxies": null, "groups": null}},
{"uid": "second", "type": null, "name": "", "file": null, "updated": null}
]
})
);
assert_eq!(
serde_json::to_value(serde_yaml_ng::from_str::<IProfiles>("{}")?)?,
serde_json::json!({"current": null, "items": null})
);
Ok(())
}
#[test]
fn merge_overrides_only_explicit_values() {
let base = PrfOption {
user_agent: Some("original".into()),
allow_auto_update: Some(true),
update_interval: Some(60),
merge: Some("original-merge".into()),
..Default::default()
};
let overrides = PrfOption {
user_agent: Some("".into()),
allow_auto_update: Some(false),
update_interval: Some(0),
..Default::default()
};
let expected = PrfOption {
merge: base.merge.clone(),
..overrides.clone()
};
assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected));
assert_eq!(PrfOption::merge(None, None), None);
assert_eq!(
PrfOption::merge(None, Some(&PrfOption::default())),
Some(PrfOption::default())
);
}
#[test]
fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r#"
current: duplicate
items:
- {uid: duplicate, name: first}
- {uid: duplicate, name: last}
- {uid: target, name: ""}
- {name: no UID}
"#,
)?;
assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first"));
assert!(!profiles.reorder("missing", "target"));
assert!(!profiles.reorder("duplicate", "missing"));
assert!(profiles.reorder("duplicate", "duplicate"));
assert!(profiles.reorder("duplicate", "target"));
let preview = profiles.profiles_preview().unwrap_or_default();
let names: Vec<_> = preview
.iter()
.map(|item| (item.name.as_str(), item.is_current))
.collect();
assert_eq!(names, [("first", true), ("", false), ("last", true)]);
Ok(())
}
#[test]
fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() {
let mut profiles = IProfiles::default();
profiles.patch_current(None);
assert!(matches!(&profiles.items, Some(items) if items.is_empty()));
assert!(profiles.current.is_none());
profiles.append_item(&PrfItem {
uid: Some("script".into()),
itype: Some("script".into()),
..Default::default()
});
assert!(profiles.current.is_none());
profiles.append_item(&PrfItem {
uid: Some("local".into()),
itype: Some("local".into()),
..Default::default()
});
assert_eq!(profiles.current.as_deref(), Some("local"));
profiles.patch_current(None);
profiles.patch_current(Some(&String::from("missing")));
assert_eq!(profiles.current.as_deref(), Some("local"));
profiles.patch_current(Some(&String::from("script")));
assert_eq!(profiles.current.as_deref(), Some("script"));
}
#[test]
fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box<dyn std::error::Error>> {
let mut profiles: IProfiles = serde_yaml_ng::from_str(
r"
items:
- {uid: active, type: remote, file: first.yaml, option: {merge: owned}}
- {uid: owned, type: merge, file: owned.yaml}
- {type: script, file: missing-uid.js}
- {uid: next, type: local, file: next.yaml}
",
)?;
let plan = profiles.plan_delete_item("active")?;
assert!(plan.deleting_current);
assert_eq!(
plan.files,
["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from)
);
assert_eq!(profiles.current.as_deref(), Some("next"));
assert!(profiles.get_item("owned").is_err());
Ok(())
}
}
@@ -0,0 +1,147 @@
use super::PrfSelected;
use std::collections::HashSet;
use tristr::alias::String;
pub struct SelectedGroup<'a> {
pub members: Option<&'a [std::string::String]>,
pub current: Option<&'a str>,
pub selectable: bool,
}
#[derive(Debug, PartialEq, Eq)]
pub struct SelectedNodesPlan {
pub selected: Vec<PrfSelected>,
pub activations: Vec<(String, String)>,
pub repaired_count: usize,
}
fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool {
available_nodes.iter().any(|available| available == node)
}
pub fn selected_nodes_need_confirmation<'a, Snapshot>(
selected: &[PrfSelected],
snapshot: &'a Snapshot,
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
) -> bool {
selected.iter().any(|selected_item| {
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
return false;
};
let Some(group) = lookup(snapshot, group_name) else {
return true;
};
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
return true;
};
!node_is_available(available_nodes, node)
})
}
pub fn reconcile_selected_nodes<'a, Snapshot>(
selected: &[PrfSelected],
previous: Option<&'a Snapshot>,
current: &'a Snapshot,
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
) -> SelectedNodesPlan {
let mut plan = SelectedNodesPlan {
selected: Vec::with_capacity(selected.len()),
activations: Vec::new(),
repaired_count: 0,
};
let mut seen_groups = HashSet::new();
let mut unique_selected = selected
.iter()
.rev()
.filter(|item| item.name.as_deref().is_some_and(|name| seen_groups.insert(name)))
.collect::<Vec<_>>();
unique_selected.reverse();
plan.repaired_count += selected.len() - unique_selected.len();
for selected_item in unique_selected {
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
plan.repaired_count += 1;
continue;
};
let Some(group) = lookup(current, group_name) else {
if previous.is_some_and(|snapshot| lookup(snapshot, group_name).is_none()) {
plan.repaired_count += 1;
} else {
plan.selected.push(selected_item.clone());
}
continue;
};
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
// Provider-backed groups can be temporarily incomplete immediately after a reload.
plan.selected.push(selected_item.clone());
continue;
};
if !group.selectable {
let preferred_node = group
.current
.filter(|current| node_is_available(available_nodes, current))
.or_else(|| node_is_available(available_nodes, node).then_some(node.as_str()));
let Some(preferred_node) = preferred_node else {
plan.repaired_count += 1;
continue;
};
plan.repaired_count += usize::from(preferred_node != node.as_str());
plan.selected.push(PrfSelected {
name: Some(group_name.clone()),
now: Some(preferred_node.into()),
});
continue;
}
if node_is_available(available_nodes, node) {
plan.selected.push(selected_item.clone());
if group.current != Some(node.as_str()) {
plan.activations.push((group_name.clone(), node.clone()));
}
continue;
}
let missing_was_confirmed = previous
.and_then(|snapshot| lookup(snapshot, group_name))
.and_then(|group| group.members)
.filter(|nodes| !nodes.is_empty())
.is_some_and(|nodes| !node_is_available(nodes, node));
if !missing_was_confirmed {
plan.selected.push(selected_item.clone());
continue;
}
plan.repaired_count += 1;
if let Some(current_node) = group
.current
.filter(|current| node_is_available(available_nodes, current))
{
plan.selected.push(PrfSelected {
name: Some(group_name.clone()),
now: Some(current_node.into()),
});
}
}
plan
}
/// Returns recorded selections whose groups have not reached the requested node.
pub fn unsettled_selections<'a, Snapshot>(
selected: &[PrfSelected],
snapshot: &'a Snapshot,
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
) -> Vec<String> {
selected
.iter()
.filter_map(|item| {
let (Some(group_name), Some(node)) = (&item.name, &item.now) else {
return None;
};
match lookup(snapshot, group_name) {
Some(group) if group.current == Some(node.as_str()) => None,
_ => Some(group_name.clone()),
}
})
.collect()
}
@@ -0,0 +1,49 @@
use super::PrfItem;
use std::time::Duration;
/// Scheduling policy for a Profile, independent of the task queue and clock.
#[derive(Debug, PartialEq, Eq)]
pub struct SubscriptionSchedule {
pub interval_minutes: u64,
pub first_delay: Duration,
}
impl SubscriptionSchedule {
pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option<Self> {
let option = item.option.as_ref()?;
let interval = option.update_interval.filter(|interval| *interval > 0)?;
if !option.allow_auto_update.unwrap_or(true) {
return None;
}
let mut schedule = Self::new(interval, item.updated, now);
// Startup historically treats an explicit zero timestamp as overdue.
if initializing && item.updated == Some(0) {
schedule.first_delay = Duration::ZERO;
}
Some(schedule)
}
pub fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
let full = Self::interval_duration(interval_minutes);
let elapsed = updated
.filter(|updated| *updated > 0)
.map_or(0, |updated| (now.max(0) as u64).saturating_sub(updated as u64));
Self {
interval_minutes,
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
}
}
pub const fn interval_duration(interval_minutes: u64) -> Duration {
Duration::from_secs(interval_minutes.saturating_mul(60))
}
/// The UI deadline is based on the last saved update. The queue can delay retries further.
pub fn reported_deadline(interval_minutes: u64, updated: Option<usize>) -> Option<i64> {
let updated = i64::try_from(updated.filter(|updated| *updated > 0)?).ok()?;
let interval = i64::try_from(interval_minutes).ok()?.checked_mul(60)?;
updated.checked_add(interval)
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "clash-verge-proxy-view"
version = "0.1.0"
edition = "2024"
[dependencies]
serde = { workspace = true, features = ["derive"] }
specta = { workspace = true, features = ["derive"] }
tristr = { workspace = true }
[lints]
workspace = true
@@ -1,15 +1,40 @@
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::Serialize; use serde::Serialize;
use tauri_plugin_mihomo::models::{ use tristr::alias::String;
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
};
pub struct ProxyViewInput { pub struct ProxyViewInput {
pub runtime_group_order: Vec<String>, pub runtime_group_order: Vec<String>,
pub group_scopes: BTreeMap<String, GroupScope>, pub group_scopes: BTreeMap<String, GroupScope>,
pub proxies: Proxies, pub proxies: HashMap<String, ProxySnapshot>,
pub providers: Option<ProxyProviders>, pub providers: Option<BTreeMap<String, ProviderSnapshot>>,
}
pub struct ProxySnapshot {
pub name: String,
pub proxy_type: String,
pub all: Option<Vec<String>>,
pub fixed: Option<String>,
pub hidden: Option<bool>,
pub icon: Option<String>,
pub now: Option<String>,
pub test_url: Option<String>,
pub id: Option<String>,
pub history: Vec<DelayHistory>,
pub capabilities: ProxyCapabilities,
}
pub struct ProviderSnapshot {
pub vehicle_type: ProxyProviderVehicleType,
pub proxies: Vec<ProxySnapshot>,
pub updated_at: Option<String>,
pub subscription_info: Option<ProxySubscriptionInfo>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
} }
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries. /// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
@@ -18,8 +43,6 @@ pub struct GroupScope {
pub exclude_types: Vec<String>, pub exclude_types: Vec<String>,
} }
pub struct ProxyViewBuilder;
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)] #[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ProxyViewV1 { pub struct ProxyViewV1 {
@@ -62,8 +85,7 @@ pub struct ProxyCapabilities {
pub struct ProxyGroupView { pub struct ProxyGroupView {
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = String)] pub proxy_type: String,
pub proxy_type: ProxyType,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>, pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@@ -74,7 +96,6 @@ pub struct ProxyGroupView {
pub icon: Option<String>, pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>, pub test_url: Option<String>,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(flatten)] #[serde(flatten)]
pub capabilities: ProxyCapabilities, pub capabilities: ProxyCapabilities,
@@ -87,9 +108,7 @@ pub struct ProxyNodeView {
pub record_id: String, pub record_id: String,
pub name: String, pub name: String,
#[serde(rename = "type")] #[serde(rename = "type")]
#[specta(type = String)] pub proxy_type: String,
pub proxy_type: ProxyType,
#[specta(type = Vec<crate::ipc::DelayHistory>)]
pub history: Vec<DelayHistory>, pub history: Vec<DelayHistory>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>, pub id: Option<String>,
@@ -190,8 +209,8 @@ struct MemberResolver<'a> {
impl<'a> MemberResolver<'a> { impl<'a> MemberResolver<'a> {
/// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`. /// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`.
fn scoped_candidates(&self, group: &str, name: &str) -> Vec<&'a String> { fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> {
let (Some(scope), Some(candidates)) = (self.group_scopes.get(group), self.provider_candidates.get(name)) else { let Some(scope) = self.group_scopes.get(group) else {
return Vec::new(); return Vec::new();
}; };
scope scope
@@ -200,17 +219,23 @@ impl<'a> MemberResolver<'a> {
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider)) .flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
.map(|(_, record_id)| record_id) .map(|(_, record_id)| record_id)
.filter(|record_id| { .filter(|record_id| {
!self.records.get(*record_id).is_some_and(|node| { scope.exclude_types.is_empty()
scope || !self.records.get(*record_id).is_some_and(|node| {
.exclude_types scope
.iter() .exclude_types
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str())) .iter()
}) .any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
}) })
.collect() .collect()
} }
fn resolve(&self, name: String, scoped: Option<&String>) -> ProxyMemberRef { fn resolve(
&self,
group: &str,
name: String,
seen: &mut BTreeMap<String, (usize, Vec<&'a String>)>,
) -> ProxyMemberRef {
if self.group_names.contains(&name) { if self.group_names.contains(&name) {
ProxyMemberRef::Group { name } ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) { } else if let Some(record_id) = self.core_node_ids.get(&name) {
@@ -225,16 +250,30 @@ impl<'a> MemberResolver<'a> {
} }
} else { } else {
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice); let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
match (scoped, candidates) { let record_id = match candidates {
(Some(record_id), _) | (None, [(_, record_id)]) => ProxyMemberRef::Node { [(_, record_id)] => Some(record_id),
[] => {
return ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
};
}
_ => {
// The n-th occurrence in Mihomo's member list selects the n-th scoped candidate.
let (occurrence, scoped) = seen
.entry(name.clone())
.or_insert_with(|| (0, self.scoped_candidates(group, candidates)));
let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
record_id
}
};
match record_id {
Some(record_id) => ProxyMemberRef::Node {
name, name,
record_id: record_id.clone(), record_id: record_id.clone(),
}, },
(None, []) => ProxyMemberRef::Unresolved { None => ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
},
(None, _) => ProxyMemberRef::Unresolved {
name, name,
reason: ProxyMemberUnresolvedReason::Ambiguous, reason: ProxyMemberUnresolvedReason::Ambiguous,
}, },
@@ -243,14 +282,14 @@ impl<'a> MemberResolver<'a> {
} }
} }
impl ProxyViewBuilder { impl ProxyViewInput {
pub fn build(input: ProxyViewInput) -> ProxyViewV1 { pub fn into_view(self) -> ProxyViewV1 {
let ProxyViewInput { let Self {
runtime_group_order, runtime_group_order,
group_scopes, group_scopes,
proxies, proxies,
providers, providers,
} = input; } = self;
let provider_state = if providers.is_some() { let provider_state = if providers.is_some() {
ProxyViewProviderState::Ready ProxyViewProviderState::Ready
} else { } else {
@@ -270,7 +309,7 @@ impl ProxyViewBuilder {
let global = core_groups let global = core_groups
.remove("GLOBAL") .remove("GLOBAL")
.map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver)); .map(|proxy| build_group("GLOBAL".into(), proxy, &resolver));
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver); let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
let direct = core_node_ids.get("DIRECT").cloned(); let direct = core_node_ids.get("DIRECT").cloned();
let standalone = build_standalone(&core_node_ids); let standalone = build_standalone(&core_node_ids);
@@ -289,11 +328,13 @@ impl ProxyViewBuilder {
} }
} }
fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) { fn partition_core(
proxies: HashMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
let mut groups = BTreeMap::new(); let mut groups = BTreeMap::new();
let mut nodes = BTreeMap::new(); let mut nodes = BTreeMap::new();
for (name, proxy) in proxies.proxies { for (name, proxy) in proxies {
if proxy.all.is_some() { if proxy.all.is_some() {
groups.insert(name, proxy); groups.insert(name, proxy);
} else { } else {
@@ -305,13 +346,13 @@ fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String
} }
fn build_core_records( fn build_core_records(
core_nodes: BTreeMap<String, Proxy>, core_nodes: BTreeMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) { ) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
let mut records = BTreeMap::new(); let mut records = BTreeMap::new();
let mut ids = BTreeMap::new(); let mut ids = BTreeMap::new();
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() { for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
let record_id = format!("c:{index}"); let record_id: String = format!("c:{index}").into();
ids.insert(name.clone(), record_id.clone()); ids.insert(name.clone(), record_id.clone());
records.insert( records.insert(
record_id.clone(), record_id.clone(),
@@ -328,32 +369,24 @@ fn build_core_records(
} }
fn build_provider_records( fn build_provider_records(
providers: Option<ProxyProviders>, providers: Option<BTreeMap<String, ProviderSnapshot>>,
records: &mut BTreeMap<String, ProxyNodeView>, records: &mut BTreeMap<String, ProxyNodeView>,
) -> (Vec<ProxyProviderView>, ProviderCandidates) { ) -> (Vec<ProxyProviderView>, ProviderCandidates) {
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
let mut views = Vec::new(); let mut views = Vec::new();
let mut candidates = BTreeMap::new(); let mut candidates = BTreeMap::new();
for (provider_name, provider) in providers { for (provider_name, provider) in providers.into_iter().flatten() {
let ProxyProvider { let ProviderSnapshot {
vehicle_type, vehicle_type,
proxies, proxies,
updated_at, updated_at,
subscription_info, subscription_info,
..
} = provider; } = provider;
let vehicle_type = match vehicle_type {
VehicleType::HTTP => ProxyProviderVehicleType::Http,
VehicleType::File => ProxyProviderVehicleType::File,
VehicleType::Inline => ProxyProviderVehicleType::Inline,
_ => continue,
};
let provider_index = views.len(); let provider_index = views.len();
let mut proxy_record_ids = Vec::new(); let mut proxy_record_ids = Vec::new();
for (member_index, proxy) in proxies.into_iter().enumerate() { for (member_index, proxy) in proxies.into_iter().enumerate() {
let record_id = format!("p:{provider_index}:{member_index}"); let record_id: String = format!("p:{provider_index}:{member_index}").into();
let proxy_name = proxy.name.clone(); let proxy_name = proxy.name.clone();
let node_name = proxy.name.clone(); let node_name = proxy.name.clone();
candidates candidates
@@ -379,12 +412,7 @@ fn build_provider_records(
name: provider_name, name: provider_name,
vehicle_type, vehicle_type,
updated_at, updated_at,
subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo { subscription_info,
upload: subscription_info.upload,
download: subscription_info.download,
total: subscription_info.total,
expire: subscription_info.expire,
}),
proxy_record_ids, proxy_record_ids,
}); });
} }
@@ -392,8 +420,8 @@ fn build_provider_records(
(views, candidates) (views, candidates)
} }
fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView { fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let Proxy { let ProxySnapshot {
all, all,
fixed, fixed,
hidden, hidden,
@@ -401,27 +429,15 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
now, now,
test_url, test_url,
history, history,
udp, capabilities,
xudp,
tfo,
mptcp,
smux,
proxy_type, proxy_type,
.. ..
} = proxy; } = proxy;
// The n-th occurrence of a name in `all` is the n-th scoped candidate. let mut seen = BTreeMap::new();
let mut seen = BTreeMap::<String, (usize, Vec<&String>)>::new();
let members = all let members = all
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.map(|member| { .map(|member| resolver.resolve(&name, member, &mut seen))
let (occurrence, scoped) = seen
.entry(member.clone())
.or_insert_with(|| (0, resolver.scoped_candidates(&name, &member)));
let picked = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
resolver.resolve(member, picked)
})
.collect(); .collect();
ProxyGroupView { ProxyGroupView {
@@ -433,29 +449,19 @@ fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> Pro
icon, icon,
test_url, test_url,
history, history,
capabilities: ProxyCapabilities { capabilities,
udp,
xudp,
tfo,
mptcp,
smux,
},
members, members,
} }
} }
fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView { fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
let Proxy { let ProxySnapshot {
id, id,
hidden, hidden,
icon, icon,
test_url, test_url,
history, history,
udp, capabilities,
xudp,
tfo,
mptcp,
smux,
proxy_type, proxy_type,
.. ..
} = proxy; } = proxy;
@@ -469,19 +475,13 @@ fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSo
hidden, hidden,
icon, icon,
test_url, test_url,
capabilities: ProxyCapabilities { capabilities,
udp,
xudp,
tfo,
mptcp,
smux,
},
source, source,
} }
} }
fn build_ordered_groups( fn build_ordered_groups(
mut core_groups: BTreeMap<String, Proxy>, mut core_groups: BTreeMap<String, ProxySnapshot>,
runtime_group_order: Vec<String>, runtime_group_order: Vec<String>,
resolver: &MemberResolver<'_>, resolver: &MemberResolver<'_>,
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) { ) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
@@ -0,0 +1,17 @@
[package]
name = "clash-verge-runtime-bundle"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
clash-verge-logging = { workspace = true }
hex = "0.4.3"
log = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
tristr = { workspace = true }
tokio = { workspace = true, features = ["fs"] }
[lints]
workspace = true
@@ -0,0 +1,43 @@
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum RuntimeBundleError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("failed to read runtime config {path:?}")]
ReadConfig {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to parse runtime config {path:?}")]
ParseConfig {
path: PathBuf,
#[source]
source: serde_yaml_ng::Error,
},
#[error("runtime config has no parent directory")]
MissingConfigDirectory,
#[error("runtime provider destination {0:?} is declared for two different sources")]
DifferentSources(String),
#[error("runtime provider destination {0:?} is claimed more than once")]
DuplicateDestination(String),
#[error("local runtime provider is unavailable: {path:?}")]
LocalProviderUnavailable {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("local runtime provider is outside the config root: {0:?}")]
LocalProviderOutsideRoot(PathBuf),
#[error("runtime provider destination traverses outside the runtime")]
DestinationOutsideRuntime,
#[error("runtime provider path has no existing ancestor: {0:?}")]
MissingAncestor(PathBuf),
#[error("runtime provider path is outside the config root: {0:?}")]
ProviderOutsideRoot(PathBuf),
#[error("local runtime provider destination traverses outside the runtime")]
LocalDestinationOutsideRuntime,
#[error("local runtime provider destination is empty")]
EmptyDestination,
}
@@ -1,12 +1,17 @@
use anyhow::{Context as _, Result, bail}; mod error;
pub use error::RuntimeBundleError;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256}; use sha2::{Digest as _, Sha256};
use std::collections::{BTreeMap, HashSet}; use std::collections::{BTreeMap, HashSet};
use std::path::{Component, Path, PathBuf, Prefix}; use std::path::{Component, Path, PathBuf, Prefix};
use tristr::TriStr;
pub(crate) const GEO_ASSETS: &[&str] = &[ const PROVIDER_SECTIONS: [&str; 2] = ["proxy-providers", "rule-providers"];
pub const GEO_ASSETS: &[&str] = &[
"Country.mmdb", "Country.mmdb",
"ASN.mmdb", "ASN.mmdb",
"geoip.dat", "geoip.dat",
@@ -17,42 +22,62 @@ pub(crate) const GEO_ASSETS: &[&str] = &[
/// Provider identity used by the runtime config and core API. /// Provider identity used by the runtime config and core API.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RemoteProviderRef { pub struct RemoteProviderRef {
pub section: &'static str, pub section: &'static str,
pub name: String, pub name: String,
pub provider: RemoteProvider, pub destination: TriStr,
pub url: String,
} }
struct RuntimeParts { pub struct RuntimeAsset {
config: Value, pub source: String,
assets: Vec<RuntimeAsset>, pub destination: TriStr,
remote_providers: Vec<RemoteProviderRef>,
} }
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> { pub struct RuntimeBundlePlan {
pub config: Value,
pub assets: Vec<RuntimeAsset>,
pub remote_providers: Vec<RemoteProviderRef>,
}
type Result<T> = std::result::Result<T, RuntimeBundleError>;
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
let yaml = tokio::fs::read_to_string(config_file) let yaml = tokio::fs::read_to_string(config_file)
.await .await
.with_context(|| format!("failed to read runtime config {config_file:?}"))?; .map_err(|source| RuntimeBundleError::ReadConfig {
let config: Value = path: config_file.to_owned(),
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?; source,
let config_root = config_file })?;
.parent() let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?; path: config_file.to_owned(),
let parts = collect_runtime_parts(config, config_root)?; source,
Ok(RuntimeBundle { })?;
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?, let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
assets: parts.assets, collect_runtime_parts(config, config_root)
remote_providers: parts
.remote_providers
.into_iter()
.map(|declared| declared.provider)
.collect(),
core_path: core_path.to_string_lossy().into_owned(),
})
} }
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> { pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers) let config_root = std::fs::canonicalize(config_root)?;
let mut destinations = HashSet::new();
let mut remote_providers = Vec::new();
for section in PROVIDER_SECTIONS {
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
continue;
};
for (name, provider) in providers {
plan_provider(
section,
name,
provider,
&config_root,
&mut destinations,
None,
&mut remote_providers,
)?;
}
}
Ok(remote_providers)
} }
#[derive(Default)] #[derive(Default)]
@@ -61,11 +86,11 @@ struct ProviderPathOwners {
local: bool, local: bool,
} }
pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> { pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
let config_root = std::fs::canonicalize(config_root)?; let config_root = std::fs::canonicalize(config_root)?;
let mut paths = BTreeMap::<String, ProviderPathOwners>::new(); let mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect(); let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
for section in ["proxy-providers", "rule-providers"] { for section in PROVIDER_SECTIONS {
let Some(providers) = config.get(section).and_then(Value::as_mapping) else { let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
continue; continue;
}; };
@@ -84,6 +109,7 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root:
let Ok(destination) = destination else { let Ok(destination) = destination else {
continue; continue;
}; };
let destination = TriStr::from(destination.as_str());
reserved.insert(destination.clone()); reserved.insert(destination.clone());
let owners = paths.entry(destination).or_default(); let owners = paths.entry(destination).or_default();
match (is_remote, provider.get("url").and_then(Value::as_str)) { match (is_remote, provider.get("url").and_then(Value::as_str)) {
@@ -117,12 +143,12 @@ pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root:
Ok(()) Ok(())
} }
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<String>) -> String { fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<TriStr>) -> String {
let mut digest = Sha256::new(); let mut digest = Sha256::new();
digest.update(destination.as_bytes()); digest.update(destination.as_bytes());
digest.update([0]); digest.update([0]);
digest.update(url.as_bytes()); digest.update(url.as_bytes());
let digest: String = crate::utils::help::hex_encode(&digest.finalize()); let digest = hex::encode(digest.finalize());
let path = Path::new(destination); let path = Path::new(destination);
let extension = path let extension = path
.extension() .extension()
@@ -134,7 +160,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
.with_file_name(format!("cvr-{digest}{suffix}{extension}")) .with_file_name(format!("cvr-{digest}{suffix}{extension}"))
.to_string_lossy() .to_string_lossy()
.replace('\\', "/"); .replace('\\', "/");
if reserved.insert(candidate.clone()) { if reserved.insert(TriStr::from(candidate.as_str())) {
return candidate; return candidate;
} }
sequence += 1; sequence += 1;
@@ -142,40 +168,34 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
} }
} }
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> { fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeBundlePlan> {
let config_root = std::fs::canonicalize(config_root)?; let config_root = std::fs::canonicalize(config_root)?;
let mut assets = Vec::new(); let mut assets = Vec::new();
let mut destinations = HashSet::new(); let mut destinations = HashSet::new();
let mut remote_providers = Vec::new(); let mut remote_providers = Vec::new();
collect_provider_assets( for section in PROVIDER_SECTIONS {
&mut config, collect_provider_assets(
"proxy-providers", &mut config,
&config_root, section,
&mut destinations, &config_root,
&mut assets, &mut destinations,
&mut remote_providers, &mut assets,
)?; &mut remote_providers,
collect_provider_assets( )?;
&mut config, }
"rule-providers",
&config_root,
&mut destinations,
&mut assets,
&mut remote_providers,
)?;
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets); collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
for filename in GEO_ASSETS { for filename in GEO_ASSETS {
let source = config_root.join(filename); let source = config_root.join(filename);
if source.is_file() && destinations.insert((*filename).to_string()) { if source.is_file() && destinations.insert(TriStr::from(*filename)) {
assets.push(RuntimeAsset { assets.push(RuntimeAsset {
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(), source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
destination: (*filename).to_string(), destination: (*filename).into(),
}); });
} }
} }
Ok(RuntimeParts { Ok(RuntimeBundlePlan {
config, config,
assets, assets,
remote_providers, remote_providers,
@@ -188,7 +208,7 @@ fn collect_provider_assets(
config: &mut Value, config: &mut Value,
section: &'static str, section: &'static str,
config_root: &Path, config_root: &Path,
destinations: &mut HashSet<String>, destinations: &mut HashSet<TriStr>,
assets: &mut Vec<RuntimeAsset>, assets: &mut Vec<RuntimeAsset>,
remote_providers: &mut Vec<RemoteProviderRef>, remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<()> { ) -> Result<()> {
@@ -201,80 +221,105 @@ fn collect_provider_assets(
}; };
for (name, provider) in providers.iter_mut() { for (name, provider) in providers.iter_mut() {
let Some(provider) = provider.as_mapping_mut() else { if let Some(destination) = plan_provider(
continue; section,
}; name,
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else { provider,
continue; config_root,
}; destinations,
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched. Some(assets),
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http"); remote_providers,
let url = provider.get("url").and_then(Value::as_str).map(str::to_owned); )? && let Some(provider) = provider.as_mapping_mut()
let destination = match (is_remote, url) { {
(true, Some(url)) => { provider.insert(Value::String("path".to_owned()), Value::String(destination));
let destination = provider_destination(config_root, raw_path)?; }
// Reserve remote destinations too; copied and downloaded files must not collide. }
Ok(())
}
fn plan_provider(
section: &'static str,
name: &Value,
provider: &Value,
config_root: &Path,
destinations: &mut HashSet<TriStr>,
assets: Option<&mut Vec<RuntimeAsset>>,
remote_providers: &mut Vec<RemoteProviderRef>,
) -> Result<Option<String>> {
let Some(raw_path) = provider
.as_mapping()
.and_then(|provider| provider.get("path"))
.and_then(Value::as_str)
else {
return Ok(None);
};
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Reserve remote destinations too; copied and downloaded files must not collide.
let reserved = TriStr::from(destination.as_str());
if destinations.insert(reserved.clone()) {
remote_providers.push(RemoteProviderRef {
section,
name: name.as_str().unwrap_or_default().to_owned(),
destination: reserved,
url: url.to_owned(),
});
} else {
match remote_providers match remote_providers
.iter() .iter()
.find(|declared| declared.provider.destination == destination) .find(|declared| declared.destination == destination)
{ {
Some(declared) if declared.provider.url == url => {} Some(declared) if declared.url == url => {}
Some(_) => { Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
bail!("runtime provider destination {destination:?} is declared for two different sources") None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
}
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
} }
(true, None) => { destination
}
(true, None) => {
logging!(
warn,
Type::Config,
"remote provider {name:?} declares no url; leaving its path to the core"
);
return Ok(None);
}
(false, _) => {
let Ok(source) = local_provider_source(config_root, raw_path) else {
logging!( logging!(
warn, warn,
Type::Config, Type::Config,
"remote provider {name:?} declares no url; leaving its path to the core" "local provider {name:?} is unavailable at {raw_path:?}; leaving its path to the core"
); );
continue; return Ok(None);
} };
(false, _) => { let destination = destination_below_root(config_root, &source)?;
let Ok(source) = local_provider_source(config_root, raw_path) else { let reserved = TriStr::from(destination.as_str());
logging!( if destinations.insert(reserved.clone()) {
warn, if let Some(assets) = assets {
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 { assets.push(RuntimeAsset {
source: source.to_string_lossy().into_owned(), source: source.to_string_lossy().into_owned(),
destination: destination.clone(), destination: reserved,
}); });
} }
destination } else if remote_providers.iter().any(|provider| provider.destination == reserved) {
return Err(RuntimeBundleError::DuplicateDestination(destination));
} }
}; destination
provider.insert(Value::String("path".to_owned()), Value::String(destination)); }
} };
Ok(()) Ok(Some(destination))
} }
/// Stages file-based ssh keys, which mihomo resolves against the core home directory. /// Stages file-based ssh keys, which mihomo resolves against the core home directory.
fn collect_ssh_private_keys( fn collect_ssh_private_keys(
config: &mut Value, config: &mut Value,
config_root: &Path, config_root: &Path,
destinations: &mut HashSet<String>, destinations: &mut HashSet<TriStr>,
assets: &mut Vec<RuntimeAsset>, assets: &mut Vec<RuntimeAsset>,
) { ) {
let Some(config) = config.as_mapping_mut() else { let Some(config) = config.as_mapping_mut() else {
@@ -325,7 +370,7 @@ fn collect_ssh_private_keys(
let destination = allocate_provider_destination("ssh-private-key", &source, destinations); let destination = allocate_provider_destination("ssh-private-key", &source, destinations);
assets.push(RuntimeAsset { assets.push(RuntimeAsset {
source, source,
destination: destination.clone(), destination: TriStr::from(destination.as_str()),
}); });
proxy.insert(Value::String("private-key".to_owned()), Value::String(destination)); proxy.insert(Value::String("private-key".to_owned()), Value::String(destination));
} }
@@ -347,10 +392,13 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result<PathBuf>
config_root.join(path) config_root.join(path)
}; };
let canonical_source = let canonical_source =
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?; std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
path: source,
source: error,
})?;
canonical_source canonical_source
.strip_prefix(config_root) .strip_prefix(config_root)
.map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?; .map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?;
Ok(canonical_source) Ok(canonical_source)
} }
@@ -360,7 +408,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
.components() .components()
.any(|component| matches!(component, Component::ParentDir)) .any(|component| matches!(component, Component::ParentDir))
{ {
bail!("runtime provider destination traverses outside the runtime"); return Err(RuntimeBundleError::DestinationOutsideRuntime);
} }
if path.is_absolute() { if path.is_absolute() {
let normalized = canonicalize_with_missing_tail(path)?; let normalized = canonicalize_with_missing_tail(path)?;
@@ -376,11 +424,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
while !ancestor.exists() { while !ancestor.exists() {
let name = ancestor let name = ancestor
.file_name() .file_name()
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?; .ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
tail.push(name.to_owned()); tail.push(name.to_owned());
ancestor = ancestor ancestor = ancestor
.parent() .parent()
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?; .ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
} }
let mut normalized = std::fs::canonicalize(ancestor)?; let mut normalized = std::fs::canonicalize(ancestor)?;
for component in tail.iter().rev() { for component in tail.iter().rev() {
@@ -392,31 +440,60 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> { fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
let relative = path let relative = path
.strip_prefix(config_root) .strip_prefix(config_root)
.map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?; .map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?;
normalized_destination(relative) normalized_destination(relative)
} }
fn normalized_destination(relative: &Path) -> Result<String> { fn normalized_destination(relative: &Path) -> Result<String> {
let mut destination = PathBuf::new(); let mut destination = PathBuf::with_capacity(relative.as_os_str().len());
for component in relative.components() { for component in relative.components() {
match component { match component {
Component::Normal(component) => destination.push(component), Component::Normal(component) => destination.push(component),
Component::CurDir => {} Component::CurDir => {}
_ => bail!("local runtime provider destination traverses outside the runtime"), _ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
} }
} }
if destination.as_os_str().is_empty() { if destination.as_os_str().is_empty() {
bail!("local runtime provider destination is empty"); return Err(RuntimeBundleError::EmptyDestination);
}
let destination = destination
.into_os_string()
.into_string()
.unwrap_or_else(|path| path.to_string_lossy().into_owned());
if destination.contains('\\') {
Ok(destination.replace('\\', "/"))
} else {
Ok(destination)
} }
Ok(destination.to_string_lossy().replace('\\', "/"))
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts}; use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
#[test]
fn local_and_remote_providers_cannot_claim_the_same_file() -> Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-mixed-providers-{}", std::process::id()));
std::fs::create_dir_all(&root)?;
std::fs::write(root.join("shared.yaml"), "payload: []")?;
let local = "type: file, path: ./shared.yaml";
let remote = "type: http, url: 'https://example.com/provider', path: shared.yaml";
for (proxy, rule) in [(local, remote), (remote, local)] {
let config = serde_yaml_ng::from_str(&format!(
"proxy-providers: {{a: {{{proxy}}}}}\nrule-providers: {{b: {{{rule}}}}}"
))?;
assert!(matches!(
remote_providers_of(&config, &root),
Err(super::RuntimeBundleError::DuplicateDestination(path)) if path == "shared.yaml"
));
}
std::fs::remove_dir_all(root)?;
Ok(())
}
#[tokio::test] #[tokio::test]
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> { async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
std::fs::create_dir_all(&root)?; std::fs::create_dir_all(&root)?;
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
@@ -433,7 +510,7 @@ mod tests {
resolve_provider_path_conflicts(&mut config, &root)?; resolve_provider_path_conflicts(&mut config, &root)?;
let config_file = root.join("config.yaml"); let config_file = root.join("config.yaml");
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?; std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?; let bundle = collect_runtime_bundle(&config_file).await?;
let paths = &config["rule-providers"]; let paths = &config["rule-providers"];
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]); assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
resolve_provider_path_conflicts(&mut reordered, &root)?; resolve_provider_path_conflicts(&mut reordered, &root)?;
@@ -448,14 +525,14 @@ mod tests {
"resolving an already generated config must be idempotent" "resolving an already generated config must be idempotent"
); );
assert_eq!(serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&bundle.yaml)?, config); assert_eq!(bundle.config.as_mapping(), Some(&config));
let readback = remote_providers_of(&config, &root)?; let readback = remote_providers_of(&config, &root)?;
assert_eq!(bundle.remote_providers.len(), 2); assert_eq!(bundle.remote_providers.len(), 2);
for declared in readback { for declared in readback {
assert!(bundle.remote_providers.contains(&declared.provider)); assert!(bundle.remote_providers.contains(&declared));
assert_eq!( assert_eq!(
config[declared.section][&declared.name]["path"], config[declared.section][&declared.name]["path"],
declared.provider.destination declared.destination.as_str()
); );
assert_eq!( assert_eq!(
config[declared.section][&declared.name]["url"], config[declared.section][&declared.name]["url"],
@@ -467,7 +544,8 @@ mod tests {
} }
#[test] #[test]
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> { fn allocated_provider_paths_do_not_claim_another_declared_path()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir(); let root = std::env::temp_dir();
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n", "proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
@@ -489,7 +567,8 @@ mod tests {
} }
#[test] #[test]
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> { fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str( let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n", "rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
)?; )?;
@@ -500,7 +579,8 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> { async fn collects_only_local_providers_and_existing_geo_assets()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
std::fs::create_dir_all(root.join("providers"))?; std::fs::create_dir_all(root.join("providers"))?;
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?; std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
@@ -516,12 +596,10 @@ mod tests {
absolute_remote.display() absolute_remote.display()
), ),
)?; )?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?; let bundle = collect_runtime_bundle(&config).await?;
let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?; let bundled_config = &bundle.config;
assert_eq!( assert_eq!(
bundled_config["proxy-providers"]["local"]["path"].as_str(), bundled_config["proxy-providers"]["local"]["path"].as_str(),
Some("providers/local.yaml") Some("providers/local.yaml")
@@ -530,7 +608,7 @@ mod tests {
bundled_config["proxy-providers"]["remote"]["path"].as_str(), bundled_config["proxy-providers"]["remote"]["path"].as_str(),
Some("providers/remote.yaml") Some("providers/remote.yaml")
); );
assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned())); assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref()));
assert!( assert!(
bundle bundle
.assets .assets
@@ -560,7 +638,8 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> { async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
-> std::result::Result<(), Box<dyn std::error::Error>> {
// Identical repeats are one service-side file and are safe to fold. // Identical repeats are one service-side file and are safe to fold.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root); let _ = std::fs::remove_dir_all(&root);
@@ -570,10 +649,8 @@ mod tests {
&config, &config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n", "rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
)?; )?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?; let bundle = collect_runtime_bundle(&config).await?;
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice"); assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml"); assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
@@ -582,7 +659,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> { async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root); let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?; std::fs::create_dir_all(&root)?;
@@ -591,11 +668,9 @@ mod tests {
&config, &config,
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n", "rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
)?; )?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config, &core).await else { let Err(error) = collect_runtime_bundle(&config).await else {
anyhow::bail!("two sources cannot own one file"); return Err("two sources cannot own one file".into());
}; };
assert!(error.to_string().contains("two different sources"), "{error}"); assert!(error.to_string().contains("two different sources"), "{error}");
@@ -604,7 +679,8 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> { async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
-> std::result::Result<(), Box<dyn std::error::Error>> {
// Odd providers accepted by mihomo must not block the rest of the bundle. // Odd providers accepted by mihomo must not block the rest of the bundle.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root); let _ = std::fs::remove_dir_all(&root);
@@ -614,10 +690,8 @@ mod tests {
&config, &config,
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n", "rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
)?; )?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let bundle = collect_runtime_bundle(&config, &core).await?; let bundle = collect_runtime_bundle(&config).await?;
assert_eq!( assert_eq!(
bundle.remote_providers.len(), bundle.remote_providers.len(),
@@ -625,9 +699,8 @@ mod tests {
"only the provider that could be classified is declared" "only the provider that could be classified is declared"
); );
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml"); assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
assert_eq!( assert_eq!(
reserialized["rule-providers"]["nourl"]["path"].as_str(), bundle.config["rule-providers"]["nourl"]["path"].as_str(),
Some("./rules/nourl.yaml"), Some("./rules/nourl.yaml"),
"an unclassifiable provider keeps the path the core was given" "an unclassifiable provider keeps the path the core was given"
); );
@@ -636,13 +709,13 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> { async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box<dyn std::error::Error>> {
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id())); let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
std::fs::create_dir_all(&root)?; std::fs::create_dir_all(&root)?;
let config = root.join("config.yaml"); let config = root.join("config.yaml");
let outside = root let outside = root
.parent() .parent()
.ok_or_else(|| anyhow::anyhow!("test root has no parent"))? .ok_or("test root has no parent")?
.join(format!("outside-{}.yaml", std::process::id())); .join(format!("outside-{}.yaml", std::process::id()));
std::fs::write( std::fs::write(
&config, &config,
@@ -651,11 +724,9 @@ mod tests {
outside.display() outside.display()
), ),
)?; )?;
let core = root.join("mihomo");
std::fs::write(&core, b"core")?;
let Err(error) = collect_runtime_bundle(&config, &core).await else { let Err(error) = collect_runtime_bundle(&config).await else {
anyhow::bail!("outside provider path must be rejected"); return Err("outside provider path must be rejected".into());
}; };
assert!(error.to_string().contains("outside the config root")); assert!(error.to_string().contains("outside the config root"));
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024" edition = "2024"
rust-version = "1.91" rust-version = "1.91"
[dependencies] [target.'cfg(target_os = "linux")'.dependencies]
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
log = { workspace = true } log = { workspace = true }
tokio = { workspace = true, features = ["signal"] } tokio = { workspace = true, features = ["signal"] }
@@ -0,0 +1,14 @@
[package]
name = "clash-verge-subscription"
version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = { workspace = true }
http = "1"
percent-encoding = "2.3.2"
serde_yaml_ng = { workspace = true }
url = "2.5"
[lints]
workspace = true
@@ -0,0 +1,84 @@
use percent_encoding::percent_decode_str;
use std::borrow::Cow;
use url::Url;
pub struct SubscriptionLink<'a> {
pub url: Cow<'a, str>,
pub name: Option<Cow<'a, str>>,
}
pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
if !matches!(link.scheme(), "clash" | "clash-verge") {
return None;
}
// The embedded URL can contain unescaped query separators of its own.
let query = link.query()?;
let raw_url = query
.strip_prefix("url=")
.or_else(|| query.split_once("&url=").map(|(_, url)| url))?
.trim();
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
Some(SubscriptionLink {
url: decode_subscription_url(raw_url),
name,
})
}
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
if Url::parse(raw_url).is_ok() {
return Cow::Borrowed(raw_url);
}
// Only the outer name has meaning here. Partly encoded URLs can still contain literal path and query delimiters.
let mut candidate = Cow::Borrowed(
raw_url
.split_once("&name=")
.filter(|(value, _)| !value.contains(['/', '?', '&']))
.map_or(raw_url, |(value, _)| value),
);
for _ in 0..2 {
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
if decoded == candidate {
break;
}
candidate = Cow::Owned(decoded.into_owned());
if Url::parse(&candidate).is_ok() {
break;
}
}
candidate
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> {
let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?;
let link = decode_subscription_link(&plain).expect("plain subscription link");
assert_eq!(link.name.as_deref(), Some("Work VPN"));
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
let partial = Url::parse("clash://install-config?url=https%3A%2F%2Fexample.invalid/a&b/file?token=abc")?;
assert_eq!(
decode_subscription_link(&partial).expect("partially encoded link").url,
"https://example.invalid/a&b/file?token=abc"
);
let missing = Url::parse("clash://install-config?name=myurl=notes")?;
assert!(decode_subscription_link(&missing).is_none());
let named = Url::parse("clash://install-config?name=myurl=notes&url=https://example.invalid/work")?;
assert_eq!(
decode_subscription_link(&named).expect("named link").url,
"https://example.invalid/work"
);
let encoded =
Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub&name=Work")?;
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
assert_eq!(link.url, "https://example.invalid/sub");
Ok(())
}
}
@@ -0,0 +1,7 @@
#[derive(Debug, thiserror::Error)]
pub enum SubscriptionError {
#[error("the remote profile data is invalid yaml")]
InvalidYaml(#[source] serde_yaml_ng::Error),
#[error("profile does not contain `proxies` or `proxy-providers`")]
MissingProviders,
}
+244
View File
@@ -0,0 +1,244 @@
mod deep_link;
mod error;
pub use deep_link::{SubscriptionLink, decode_subscription_link};
pub use error::SubscriptionError;
use http::HeaderMap;
use percent_encoding::percent_decode_str;
use serde_yaml_ng::Mapping;
use url::Url;
pub struct SubscriptionDocument<'a> {
pub body: &'a str,
pub filename: Option<String>,
pub usage: Option<SubscriptionUsage>,
pub update_interval_minutes: Option<u64>,
pub home: Option<String>,
}
pub struct SubscriptionUsage {
pub upload: u64,
pub download: u64,
pub total: u64,
pub expire: u64,
}
pub fn decode_subscription<'a>(
url: &Url,
headers: &HeaderMap,
body: &'a str,
) -> Result<SubscriptionDocument<'a>, SubscriptionError> {
let body = body.trim_start_matches('\u{feff}');
let yaml = serde_yaml_ng::from_str::<Mapping>(body).map_err(SubscriptionError::InvalidYaml)?;
if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") {
return Err(SubscriptionError::MissingProviders);
}
let usage = headers.iter().find_map(|(name, value)| {
let prefix = name.as_str().strip_suffix("subscription-userinfo")?;
if !prefix.is_empty() && !prefix.ends_with('-') {
return None;
}
let value = value.to_str().unwrap_or("");
Some(SubscriptionUsage {
upload: find_field(value, "upload", |field| field.parse().ok()).unwrap_or(0),
download: find_field(value, "download", |field| field.parse().ok()).unwrap_or(0),
total: find_field(value, "total", |field| field.parse().ok()).unwrap_or(0),
expire: find_field(value, "expire", |field| field.parse().ok()).unwrap_or(0),
})
});
let update_interval_minutes = headers.get("profile-update-interval").and_then(|value| {
let hours = value.to_str().ok()?.parse::<u64>().ok()?;
hours.checked_mul(60)
});
let home = headers
.get("profile-web-page-url")
.and_then(|value| value.to_str().ok())
.and_then(normalize_profile_home_url);
Ok(SubscriptionDocument {
body,
filename: subscription_filename(url, headers),
usage,
update_interval_minutes,
home,
})
}
fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option<String> {
if let Some(filename) = headers.get("content-disposition").and_then(disposition_filename) {
return Some(filename);
}
let filename = url.path().rsplit('/').next()?;
let filename = percent_decode_str(filename).decode_utf8_lossy();
if filename.trim().is_empty() {
return None;
}
Some(filename.into_owned())
}
fn disposition_filename(header: &http::HeaderValue) -> Option<String> {
let mut quoted = false;
let mut escaped = false;
let fields = header.as_bytes().split(|&byte| {
if escaped {
escaped = false;
} else if quoted && byte == b'\\' {
escaped = true;
} else if byte == b'"' {
quoted = !quoted;
} else if !quoted && byte == b';' {
return true;
}
false
});
let mut plain = None;
for field in fields {
let Some((key, value)) = std::str::from_utf8(field).ok().and_then(|s| s.split_once('=')) else {
continue;
};
let value = value.trim();
if key.trim().eq_ignore_ascii_case("filename*") {
let encoded = value.splitn(3, '\'').nth(2).unwrap_or(value);
if let Ok(name) = percent_decode_str(encoded).decode_utf8()
&& !name.trim().is_empty()
{
return Some(name.into_owned());
}
} else if plain.is_none() && key.trim().eq_ignore_ascii_case("filename") {
let name = unquote_filename(value);
if !name.trim().is_empty() {
plain = Some(name);
}
}
}
plain
}
fn unquote_filename(value: &str) -> String {
let Some(inner) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else {
return value.to_owned();
};
let mut chars = inner.chars();
let mut name = String::with_capacity(inner.len());
while let Some(ch) = chars.next() {
name.push(if ch == '\\' { chars.next().unwrap_or(ch) } else { ch });
}
name
}
pub fn normalize_profile_home_url(raw: &str) -> Option<String> {
let url = Url::parse(raw.trim()).ok()?;
if !matches!(url.scheme(), "http" | "https") {
return None;
}
url.host_str()?;
Some(url.as_str().into())
}
fn find_field<'a, T>(target: &'a str, key: &str, mut parse: impl FnMut(&'a str) -> Option<T>) -> Option<T> {
target.split(';').map(str::trim).find_map(|s| {
let (name, value) = s.split_once('=')?;
if name != key {
return None;
}
parse(value)
})
}
#[cfg(test)]
mod tests {
use super::*;
use http::HeaderValue;
#[test]
fn decodes_metadata_and_preserves_provider_only_yaml() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.com/fallback.yaml")?;
let mut headers = HeaderMap::new();
headers.insert(
"content-disposition",
HeaderValue::from_static("attachment; filename*=UTF-8''My%20Profile.yaml; filename=fallback.yaml"),
);
headers.insert(
"x-amz-meta-subscription-userinfo",
HeaderValue::from_static("upload=1; download=2; total=3; expire=4"),
);
headers.insert("profile-update-interval", HeaderValue::from_static("2"));
headers.insert(
"profile-web-page-url",
HeaderValue::from_static(" https://example.com "),
);
let yaml = "# keep this comment\nproxy-providers: {}\n";
let body = format!("\u{feff}{yaml}");
let document = decode_subscription(&url, &headers, &body)?;
assert_eq!(document.body, yaml);
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
assert_eq!(document.update_interval_minutes, Some(120));
assert_eq!(document.home.as_deref(), Some("https://example.com/"));
let usage = document.usage.ok_or("missing subscription usage")?;
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
Ok(())
}
#[test]
fn falls_back_when_suggested_filename_is_invalid_or_empty() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.com/url.yaml?token=value")?;
let root_url = Url::parse("https://example.com/")?;
for (disposition, url, expected) in [
(
"attachment; filename*=UTF-8''%FF; filename=valid.yaml",
&url,
Some("valid.yaml"),
),
(
"attachment; filename*=UTF-8''; filename=valid.yaml",
&url,
Some("valid.yaml"),
),
("attachment; filename*=UTF-8''%FF", &url, Some("url.yaml")),
("attachment; filename=", &root_url, None),
] {
let mut headers = HeaderMap::new();
headers.insert("content-disposition", HeaderValue::from_static(disposition));
let document = decode_subscription(url, &headers, "proxies: []")?;
assert_eq!(document.filename.as_deref(), expected);
}
Ok(())
}
#[test]
fn reads_filename_parameters_before_falling_back_to_the_url_path() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.invalid/sub.yaml#my/notes")?;
for (disposition, expected) in [
(r#"attachment; FileName="My; \"Work\".yaml""#, r#"My; "Work".yaml"#),
("attachment; filename*=UTF-8'en'Work%27%27s.yaml", "Work''s.yaml"),
("attachment", "sub.yaml"),
] {
let mut headers = HeaderMap::new();
headers.insert("content-disposition", HeaderValue::from_static(disposition));
let document = decode_subscription(&url, &headers, "proxies: []")?;
assert_eq!(document.filename.as_deref(), Some(expected));
}
Ok(())
}
#[test]
fn ignores_overflowing_server_interval() -> Result<(), Box<dyn std::error::Error>> {
let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?;
let mut headers = HeaderMap::new();
headers.insert("profile-update-interval", HeaderValue::from_str(&u64::MAX.to_string())?);
let document = decode_subscription(&url, &headers, "proxies: []")?;
assert_eq!(document.update_interval_minutes, None);
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
Ok(())
}
}
+2 -1
View File
@@ -1,5 +1,6 @@
//! Single-owner task drivers with caller-managed runtime and cancellation. //! Task drivers and retry primitives with caller-managed runtime and cancellation.
pub mod countdown; pub mod countdown;
pub mod retry;
pub mod scheduled_task; pub mod scheduled_task;
pub mod watch_task; pub mod watch_task;
@@ -21,25 +21,29 @@ pub enum RetryError<E> {
Stop(E), Stop(E),
} }
impl<E> RetryError<E> {
fn into_inner(self) -> E {
match self {
Self::Retry(error) | Self::Stop(error) => error,
}
}
}
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>( pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
policy: RetryPolicy, policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Fut + Send, mut operation: impl FnMut(usize) -> Fut + Send,
) -> Result<T, E> { ) -> Result<T, E> {
let mut result = operation(0).await; let mut result = operation(0).await;
for (index, delay) in policy.delays().enumerate() { for (index, delay) in policy.delays().enumerate() {
match result { if !matches!(result, Err(RetryError::Retry(_))) {
Ok(_) | Err(RetryError::Stop(_)) => break, break;
Err(RetryError::Retry(_)) => { }
if !delay.is_zero() { if !delay.is_zero() {
tokio::time::sleep(delay).await; tokio::time::sleep(delay).await;
}
}
} }
result = operation(index + 1).await; result = operation(index + 1).await;
} }
result.map_err(|error| match error { result.map_err(RetryError::into_inner)
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
} }
pub async fn try_strategies< pub async fn try_strategies<
@@ -53,15 +57,14 @@ pub async fn try_strategies<
rest: [S; N], rest: [S; N],
mut operation: impl FnMut(S) -> Fut + Send, mut operation: impl FnMut(S) -> Fut + Send,
) -> Result<(S, T), E> { ) -> Result<(S, T), E> {
retry( let mut result = operation(first).await.map(|value| (first, value));
RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO), for strategy in rest {
move |attempt| { if result.is_ok() {
let strategy = if attempt == 0 { first } else { rest[attempt - 1] }; break;
let future = operation(strategy); }
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) } result = operation(strategy).await.map(|value| (strategy, value));
}, }
) result
.await
} }
pub async fn retry_with_state<S: Send, T: Send, E: Send>( pub async fn retry_with_state<S: Send, T: Send, E: Send>(
@@ -71,19 +74,15 @@ pub async fn retry_with_state<S: Send, T: Send, E: Send>(
) -> Result<T, E> { ) -> Result<T, E> {
let mut result = operation(&mut state, 0).await; let mut result = operation(&mut state, 0).await;
for (index, delay) in policy.delays().enumerate() { for (index, delay) in policy.delays().enumerate() {
match result { if !matches!(result, Err(RetryError::Retry(_))) {
Ok(_) | Err(RetryError::Stop(_)) => break, break;
Err(RetryError::Retry(_)) => { }
if !delay.is_zero() { if !delay.is_zero() {
tokio::time::sleep(delay).await; tokio::time::sleep(delay).await;
}
}
} }
result = operation(&mut state, index + 1).await; result = operation(&mut state, index + 1).await;
} }
result.map_err(|error| match error { result.map_err(RetryError::into_inner)
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
} }
pub fn retry_sync<T, E>( pub fn retry_sync<T, E>(
@@ -92,41 +91,39 @@ pub fn retry_sync<T, E>(
) -> Result<T, E> { ) -> Result<T, E> {
let mut result = operation(0); let mut result = operation(0);
for (index, delay) in policy.delays().enumerate() { for (index, delay) in policy.delays().enumerate() {
match result { if !matches!(result, Err(RetryError::Retry(_))) {
Ok(_) | Err(RetryError::Stop(_)) => break, break;
Err(RetryError::Retry(_)) => { }
if !delay.is_zero() { if !delay.is_zero() {
std::thread::sleep(delay); std::thread::sleep(delay);
}
}
} }
result = operation(index + 1); result = operation(index + 1);
} }
result.map_err(|error| match error { result.map_err(RetryError::into_inner)
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::future::ready;
#[tokio::test] #[tokio::test(start_paused = true)]
async fn retries_stop_at_success_terminal_error_or_attempt_limit() { async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO); let delay = Duration::from_millis(50);
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay);
let started = tokio::time::Instant::now();
let mut calls = 0; let mut calls = 0;
let success = retry(policy, |attempt| { let success = retry(policy, |attempt| {
calls += 1; calls += 1;
async move { ready(if attempt == 1 {
if attempt == 1 { Ok(7)
Ok(7) } else {
} else { Err(RetryError::Retry(attempt))
Err(RetryError::Retry(attempt)) })
}
}
}) })
.await; .await;
assert_eq!((success, calls), (Ok(7), 2)); assert_eq!((success, calls), (Ok(7), 2));
assert_eq!(started.elapsed(), delay);
calls = 0; calls = 0;
let stopped = retry(policy, |_| { let stopped = retry(policy, |_| {
calls += 1; calls += 1;
@@ -134,6 +131,7 @@ mod tests {
}) })
.await; .await;
assert_eq!((stopped, calls), (Err("terminal"), 1)); assert_eq!((stopped, calls), (Err("terminal"), 1));
assert_eq!(started.elapsed(), delay);
calls = 0; calls = 0;
let exhausted = retry(policy, |attempt| { let exhausted = retry(policy, |attempt| {
calls += 1; calls += 1;
@@ -141,6 +139,7 @@ mod tests {
}) })
.await; .await;
assert_eq!((exhausted, calls), (Err(2), 3)); assert_eq!((exhausted, calls), (Err(2), 3));
assert_eq!(started.elapsed(), delay * 3);
} }
#[tokio::test] #[tokio::test]
@@ -161,11 +160,9 @@ mod tests {
let result = retry_with_state(policy, Vec::new(), |visited, attempt| { let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
Box::pin(async move { Box::pin(async move {
visited.push(attempt); visited.push(attempt);
if visited.len() == 3 { (visited.len() == 3)
Ok(visited.clone()) .then(|| visited.clone())
} else { .ok_or(RetryError::Retry(()))
Err(RetryError::Retry(()))
}
}) })
}) })
.await; .await;
@@ -12,7 +12,7 @@ parking_lot = { workspace = true }
serde = { workspace = true, features = ["derive"] } serde = { workspace = true, features = ["derive"] }
# sysinfo 0.38.2 conflicts with dark-light # sysinfo 0.38.2 conflicts with dark-light
# see https://github.com/GuillaumeGomez/sysinfo/issues/1623 # see https://github.com/GuillaumeGomez/sysinfo/issues/1623
sysinfo = { version = "0.40.4", default-features = false, features = ["network", "system"] } sysinfo = { version = "0.40.5", default-features = false, features = ["network", "system"] }
[target.'cfg(not(windows))'.dependencies] [target.'cfg(not(windows))'.dependencies]
libc = "0.2.191" libc = "0.2.191"
-3
View File
@@ -7,7 +7,6 @@ import pluginImportX from 'eslint-plugin-import-x'
import pluginReactCompiler from 'eslint-plugin-react-compiler' import pluginReactCompiler from 'eslint-plugin-react-compiler'
import pluginReactHooks from 'eslint-plugin-react-hooks' import pluginReactHooks from 'eslint-plugin-react-hooks'
import pluginReactRefresh from 'eslint-plugin-react-refresh' import pluginReactRefresh from 'eslint-plugin-react-refresh'
import PluginSukka from 'eslint-plugin-sukka'
import pluginUnusedImports from 'eslint-plugin-unused-imports' import pluginUnusedImports from 'eslint-plugin-unused-imports'
import globals from 'globals' import globals from 'globals'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
@@ -112,7 +111,6 @@ export default defineConfig([
'import-x': pluginImportX, 'import-x': pluginImportX,
'react-refresh': pluginReactRefresh, 'react-refresh': pluginReactRefresh,
'unused-imports': pluginUnusedImports, 'unused-imports': pluginUnusedImports,
sukka: PluginSukka,
}, },
extends: [ extends: [
@@ -182,7 +180,6 @@ export default defineConfig([
'@eslint-react/no-unused-class-component-members': 'error', '@eslint-react/no-unused-class-component-members': 'error',
'@eslint-react/no-unused-state': 'error', '@eslint-react/no-unused-state': 'error',
'@eslint-react/jsx-no-useless-fragment': 'warn', '@eslint-react/jsx-no-useless-fragment': 'warn',
'sukka/react-prefer-destructuring-assignment': 'warn',
// TypeScript // TypeScript
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
+17 -20
View File
@@ -47,18 +47,16 @@
"@mui/icons-material": "^9.4.0", "@mui/icons-material": "^9.4.0",
"@mui/material": "^9.4.0", "@mui/material": "^9.4.0",
"@tanstack/react-virtual": "^3.14.13", "@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "3.0.0-alpha.3", "@tauri-apps/api": "2.13.0",
"@tauri-apps/plugin-clipboard-manager": "3.0.0-alpha.3", "@tauri-apps/plugin-clipboard-manager": "2.5.0",
"@tauri-apps/plugin-dialog": "3.0.0-alpha.4", "@tauri-apps/plugin-dialog": "2.8.4",
"@tauri-apps/plugin-fs": "3.0.0-alpha.3", "@tauri-apps/plugin-fs": "2.7.1",
"@tauri-apps/plugin-http": "3.0.0-alpha.3", "@tauri-apps/plugin-http": "2.9.0",
"@tauri-apps/plugin-opener": "3.0.0-alpha.3", "@tauri-apps/plugin-opener": "2.7.3",
"@tauri-apps/plugin-updater": "3.0.0-alpha.3", "@tauri-apps/plugin-updater": "2.14.1",
"ahooks": "^3.10.0", "ahooks": "^3.10.0",
"cidr-block": "^2.3.0", "cidr-block": "^2.3.0",
"dayjs": "1.11.23", "dayjs": "1.11.23",
"foxact": "^0.3.12",
"foxts": "^5.9.1",
"i18next": "^27.0.0", "i18next": "^27.0.0",
"js-yaml": "^5.4.2", "js-yaml": "^5.4.2",
"lodash-es": "^4.18.1", "lodash-es": "^4.18.1",
@@ -77,8 +75,8 @@
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"swr": "^2.5.1", "swr": "^2.5.1",
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#8ddbec3a24eea8be18b5eaa1aba16f87f23e9583", "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", "types-pac": "^1.0.3",
"validator": "^13.15.35" "validator": "^13.15.35"
}, },
@@ -87,7 +85,7 @@
"@biomejs/biome": "^2.5.14", "@biomejs/biome": "^2.5.14",
"@eslint-react/eslint-plugin": "^5.20.5", "@eslint-react/eslint-plugin": "^5.20.5",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@tauri-apps/cli": "3.0.0-alpha.6", "@tauri-apps/cli": "2.13.0",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^26.0.0", "@types/node": "^26.0.0",
"@types/react": "19.3.3", "@types/react": "19.3.3",
@@ -100,30 +98,29 @@
"cli-color": "^2.0.4", "cli-color": "^2.0.4",
"commander": "^15.0.0", "commander": "^15.0.0",
"cross-env": "^10.1.0", "cross-env": "^10.1.0",
"eslint": "^10.11.0", "eslint": "^10.16.0",
"eslint-import-resolver-typescript": "^4.4.5", "eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-es-x": "^10.0.1", "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-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7", "eslint-plugin-react-refresh": "^0.5.7",
"eslint-plugin-sukka": "^10.2.0",
"eslint-plugin-unused-imports": "^4.4.1", "eslint-plugin-unused-imports": "^4.4.1",
"globals": "^17.12.0", "globals": "^17.12.0",
"https-proxy-agent": "^9.1.0", "https-proxy-agent": "^9.1.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"jiti": "^2.7.0", "jiti": "^2.7.0",
"knip": "6.48.0", "knip": "6.49.0",
"lint-staged": "^17.5.1", "lint-staged": "^17.5.1",
"sass": "^1.104.1", "sass": "^1.104.1",
"tar": "^7.5.22", "tar": "^8.0.0",
"terser": "^5.51.2", "terser": "^5.51.2",
"tsrs": "0.20.0-ts7.1.0-beta", "tsrs": "0.20.0-ts7.1.0-beta",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.70.0", "typescript-eslint": "^8.74.0",
"vite": "^8.3.0", "vite": "^8.3.0",
"vite-plugin-svgr": "^5.2.0", "vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.1" "vitest": "^5.0.3"
}, },
"lint-staged": { "lint-staged": {
"*.{ts,tsx,js,mjs}": [ "*.{ts,tsx,js,mjs}": [
@@ -135,5 +132,5 @@
] ]
}, },
"type": "module", "type": "module",
"packageManager": "pnpm@12.23.0" "packageManager": "pnpm@12.25.1"
} }
+1052 -1401
View File
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -1,7 +1,6 @@
use objc2::{class, msg_send, runtime::AnyObject, sel}; use objc2::{class, msg_send, runtime::AnyObject, sel};
use objc2_foundation::{NSPoint, NSRect, ns_string}; use objc2_foundation::{NSPoint, NSRect, ns_string};
use tauri::{Manager as _, WebviewWindow}; use tauri::{Manager as _, WebviewWindow};
use tauri_runtime_wry::WebviewWryExt as _;
#[link(name = "CoreGraphics", kind = "framework")] #[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" { unsafe extern "C" {
@@ -141,7 +140,7 @@ async fn perf_state(window: WebviewWindow, action: String) -> Result<serde_json:
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
let fail_app = window.app_handle().clone(); let fail_app = window.app_handle().clone();
window window
.with_wry_webview(move |view| unsafe { .with_webview(move |view| unsafe {
let native = &*(view.ns_window() as *const AnyObject); let native = &*(view.ns_window() as *const AnyObject);
let sender = std::ptr::null::<AnyObject>(); let sender = std::ptr::null::<AnyObject>();
let display = match display_state(native) { let display = match display_state(native) {
@@ -213,7 +212,6 @@ pub fn run() -> std::process::ExitCode {
#[cfg(not(feature = "clippy"))] #[cfg(not(feature = "clippy"))]
let context = tauri::generate_context!(); let context = tauri::generate_context!();
let result = tauri::Builder::default() let result = tauri::Builder::default()
.runtime(tauri_runtime_wry::Wry::default())
.plugin(tauri_plugin_wdio_webdriver::init()) .plugin(tauri_plugin_wdio_webdriver::init())
.invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config]) .invoke_handler(tauri::generate_handler![perf_state, get_clash_logs, get_verge_config])
.setup(|app| { .setup(|app| {
+10 -3
View File
@@ -1,10 +1,17 @@
# Backend Architecture Guardrails # Backend Architecture Guardrails
Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing
capabilities or changing background task ownership. backend capability boundaries, reusable orchestration, or background task
ownership.
- **Tauri adapter.** Commands validate transport input, delegate to application
use cases, and map results and errors to IPC. Tauri wires dependencies and
owns desktop lifecycle, window and tray integration, and event delivery.
Keep domain validation and reusable orchestration independent of command
handlers and framework state.
- **Configuration and effects.** `config` owns source configuration, drafts, and - **Configuration and effects.** `config` owns source configuration, drafts, and
persistence. The effects layer classifies every Verge patch field, including persistence coordination. Persistence adapters perform storage and recovery.
The effects layer classifies every Verge patch field, including
fields without effects and platform-specific fields, and reconciles requested fields without effects and platform-specific fields, and reconciles requested
state in dependency order. Publish rollbackable state after persistence and state in dependency order. Publish rollbackable state after persistence and
commit. On failure, preserve already applied runtime effects, independently commit. On failure, preserve already applied runtime effects, independently
+41 -28
View File
@@ -22,30 +22,39 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"] chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"] clippy = ["tauri/test"]
perf-harness = ["dep:tauri-plugin-wdio-webdriver"] perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
profile-store-windows = []
[package.metadata.bundle] [package.metadata.bundle]
identifier = "io.github.clash-verge-rev.clash-verge-rev" identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies] [build-dependencies]
tauri-build = { version = "=3.0.0-alpha.4", features = [] } tauri-build = { version = "2.8.0", features = [] }
[dependencies] [dependencies]
tempfile = { workspace = true }
clash-verge-draft = { workspace = true } clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true } clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true } clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true } clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true } clash-verge-i18n = { workspace = true }
clash-verge-limiter = { workspace = true } clash-verge-limiter = { workspace = true }
clash-verge-subscription = { workspace = true }
clash-verge-runtime-bundle = { workspace = true }
clash-verge-config-render = { workspace = true }
clash-verge-profile-script = { workspace = true }
clash-verge-proxy-view = { workspace = true }
clash-verge-profile = { workspace = true }
clash-verge-backup-archive = { workspace = true }
tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [ tauri = { workspace = true, features = [
"protocol-asset", "protocol-asset",
"devtools",
"tracing", "tracing",
"tray-icon", "tray-icon",
"image-ico", "image-ico",
"image-png", "image-png",
] } ] }
tauri-runtime-wry = { workspace = true, features = ["common-controls-v6", "devtools", "tracing"] }
parking_lot = { workspace = true } parking_lot = { workspace = true }
anyhow = { workspace = true } anyhow = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
@@ -57,12 +66,10 @@ tristr = { workspace = true }
socket2 = { workspace = true } socket2 = { workspace = true }
warp = { version = "0.4.4", features = ["server"] } warp = { version = "0.4.4", features = ["server"] }
open = "5.4.5" open = "5.4.5"
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
dirs = "7.0.0" dirs = "7.0.0"
dunce = "1.0.5" dunce = "1.0.5"
nanoid = "0.5" nanoid = "0.5"
chrono = { workspace = true } chrono = { workspace = true }
boa_engine = "0.22.0"
http-body-util = "0.1.5" http-body-util = "0.1.5"
percent-encoding = "2.3.2" percent-encoding = "2.3.2"
reqwest = { workspace = true } reqwest = { workspace = true }
@@ -70,51 +77,56 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "
"guard", "guard",
] } ] }
network-interface = { version = "2.0.5", features = ["serde"] } network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "=3.0.0-alpha.3" tauri-plugin-shell = "2.6.0"
tauri-plugin-opener = "=3.0.0-alpha.3" tauri-plugin-opener = "2.7.3"
tauri-plugin-dialog = "=3.0.0-alpha.4" tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = ["gtk3"] }
tauri-plugin-fs = "=3.0.0-alpha.3" tauri-plugin-fs = "2.8.0"
tauri-plugin-deep-link = { git = "https://github.com/tauri-apps/plugins-workspace", rev = "f69e3649d7612a44dfb456a4990c588ea278d73a" } tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "=3.0.0-alpha.2" tauri-plugin-window-state = "2.5.1"
zip = "9.9.0"
flate2 = "1.1.11" flate2 = "1.1.11"
reqwest_dav = "0.4.0" reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" } aes-gcm = { version = "0.11.1" }
base64 = "0.23.1" base64 = "0.23.1"
sha2 = "0.11.2" sha2 = { workspace = true }
getrandom = "0.4.3" getrandom = "0.4.3"
futures = { workspace = true } futures = { workspace = true }
gethostname = "1.1.0" gethostname = "1.1.0"
tauri-plugin-notification = "=3.0.0-alpha.3" tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] } tauri-plugin-http = "2.10.0"
tauri-plugin-http = "=3.0.0-alpha.3" backon = { version = "1.7.0", features = ["tokio-sleep"] }
tracing = { workspace = true } tracing = { workspace = true }
tauri-plugin-devtools = { version = "=3.0.0-alpha.0", optional = true } tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "8ddbec3a24eea8be18b5eaa1aba16f87f23e9583" } tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
async-trait = "0.1.92" async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [ clash_verge_service_ipc = { workspace = true, features = ["client"] }
"client",
] }
arc-swap = "1.9.5" arc-swap = "1.9.5"
tokio-rustls = "0.26.6" tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] } rustls = { version = "0.23.47", features = ["ring"] }
webpki-roots = "1.0.12" webpki-roots = "1.0.12"
dark-light = "3.0.0" dark-light = "3.0.0"
bytes = "1.12.2" bytes = "1.12.2"
tokio-util = { version = "0.7.20", features = ["time"] } tokio-util = { version = "0.7.20", features = ["time"] }
specta = { version = "=2.0.0-rc.26", features = ["derive", "function", "serde_json"] } specta = { workspace = true, features = ["derive", "function", "serde_json"] }
tauri-specta = { git = "https://github.com/tauri-apps/tauri-specta", rev = "6bcec0cdec0c92decf404c85ff01b4d8c3868599", features = ["derive", "typescript"] } tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13" specta-typescript = "=0.0.13"
[target.'cfg(any(unix, windows))'.dependencies]
clash-verge-profile-store = { workspace = true }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2.191" libc = "0.2.191"
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.19"
tauri = { workspace = true, features = ["linux-ksni"] }
# Upstream has no session-end signal support on Linux; see crates/clash-verge-signal. # Upstream has no session-end signal support on Linux; see crates/clash-verge-signal.
clash-verge-signal = { workspace = true } clash-verge-signal = { workspace = true }
[target.'cfg(not(target_os = "linux"))'.dependencies]
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6"] }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { git = "https://github.com/Tunglies/desktop-mobile.git", rev = "3c936ad889b153bbe60902f74cbf69ef04d0e8d0", optional = true } tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.0", optional = true }
objc2 = "0.6.5" objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [ objc2-foundation = { version = "0.3.2", features = [
"NSString", "NSString",
@@ -138,12 +150,13 @@ objc2-app-kit = { version = "0.3.2", features = [
] } ] }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
zip = { workspace = true }
deelevate = { workspace = true } deelevate = { workspace = true }
quick-xml = "0.42.0" quick-xml = "0.42.0"
runas = "=1.2.0" runas = "=1.2.0"
winreg = "0.56.0" winreg = "0.56.0"
windows-service = "0.8.1" windows-service = "0.8.1"
windows = { version = "0.62.2", features = [ windows = { version = "0.101.0", features = [
"Win32_System_Com", "Win32_System_Com",
"Win32_System_Ole", "Win32_System_Ole",
"Win32_System_TaskScheduler", "Win32_System_TaskScheduler",
@@ -152,9 +165,9 @@ windows = { version = "0.62.2", features = [
windows-sys.workspace = true windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "=3.0.0-alpha.3" tauri-plugin-autostart = "2.7.0"
tauri-plugin-global-shortcut = "=3.0.0-alpha.3" tauri-plugin-global-shortcut = "2.4.1"
tauri-plugin-updater = "=3.0.0-alpha.3" tauri-plugin-updater = "2.14.1"
[dev-dependencies] [dev-dependencies]
tokio = { workspace = true, features = ["test-util"] } tokio = { workspace = true, features = ["test-util"] }
+2
View File
@@ -1,3 +1,5 @@
#![deny(clippy::expect_used, clippy::unwrap_used)]
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
+1
View File
@@ -70,6 +70,7 @@
"dialog:allow-open", "dialog:allow-open",
"global-shortcut:allow-is-registered", "global-shortcut:allow-is-registered",
"global-shortcut:allow-register", "global-shortcut:allow-register",
"global-shortcut:allow-register-all",
"global-shortcut:allow-unregister", "global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all", "global-shortcut:allow-unregister-all",
"clipboard-manager:allow-read-text", "clipboard-manager:allow-read-text",

Some files were not shown because too many files have changed in this diff Show More