Compare commits
3 Commits
1.0.1
...
9fd0a8c0b9
| Author | SHA1 | Date | |
|---|---|---|---|
| 9fd0a8c0b9 | |||
| 1bb795a532 | |||
| db0c1dede9 |
61
.agent/README.md
Normal file
61
.agent/README.md
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
# ProxyWarden Agent Kit
|
||||||
|
|
||||||
|
Этот каталог содержит инструкции для кодовых агентов, которые работают с ProxyWarden.
|
||||||
|
|
||||||
|
Главный файл — `AGENTS.md` в корне репозитория. Он задает инварианты и общие правила. Файлы в `.agent/skills` описывают конкретные режимы работы: backend, UI, security, Windows services, subscriptions/routing, testing/release и понятные отчеты.
|
||||||
|
|
||||||
|
## Как использовать
|
||||||
|
|
||||||
|
1. Прочитать корневой `AGENTS.md`.
|
||||||
|
2. Выбрать skill под задачу.
|
||||||
|
3. Перед изменением проверить релевантные чек-листы из `.agent/checklists`.
|
||||||
|
4. После изменения выполнить минимальные проверки.
|
||||||
|
5. Для любого нетривиального ответа использовать `communication-reporting`: коротко, по файлам, с проверками и рисками.
|
||||||
|
6. В финальном отчете явно указать, что было и не было проверено.
|
||||||
|
|
||||||
|
## Как агент должен писать ответы
|
||||||
|
|
||||||
|
По умолчанию агент пишет не техническую простыню, а короткий отчет:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
Что изменилось по файлам
|
||||||
|
Важные места
|
||||||
|
Проверено
|
||||||
|
Не проверено
|
||||||
|
Риски
|
||||||
|
```
|
||||||
|
|
||||||
|
Для 2+ файлов желательно использовать таблицу `Файл / Что изменилось / Зачем`. В ответе должны быть конкретные пути файлов и человеческая причина изменения. Не надо пересказывать каждую строку diff, если пользователь не попросил.
|
||||||
|
|
||||||
|
Подробные правила лежат в `.agent/skills/communication-reporting/SKILL.md`, чек-лист — в `.agent/checklists/communication.md`. Да, это нужно отдельно прописывать, иначе агент опять напишет роман о своем внутреннем мире и двух переименованных переменных.
|
||||||
|
|
||||||
|
## Skill index
|
||||||
|
|
||||||
|
- `repository-orientation` — вход в проект, карта файлов, где искать source of truth.
|
||||||
|
- `rust-tauri-backend` — Tauri commands, Rust models, validation, storage, adapters.
|
||||||
|
- `react-typescript-ui` — React UI, typed invoke facade, readiness, components.
|
||||||
|
- `security-hardening` — CSP, секреты, elevated boundary, storage corruption, SSRF.
|
||||||
|
- `windows-services-powershell` — scripts, UAC, services, ProxiFyre/sing-box operations.
|
||||||
|
- `subscriptions-routing` — external SOCKS5, sing-box subscriptions, config generation, ping.
|
||||||
|
- `testing-ci-release` — build/test matrix, CI recommendations, release hygiene.
|
||||||
|
- `communication-reporting` — короткие планы, понятные сводки по файлам, отчеты без текстовой каши.
|
||||||
|
|
||||||
|
## Communication defaults
|
||||||
|
|
||||||
|
Перед длинным ответом или отчетом использовать:
|
||||||
|
|
||||||
|
- `.agent/skills/communication-reporting/SKILL.md`
|
||||||
|
- `.agent/checklists/communication.md`
|
||||||
|
- `.agent/checklists/explanation-quality.md`
|
||||||
|
- `.agent/templates/change-report.md` или `.agent/templates/user-facing-summary.md`
|
||||||
|
- `.agent/templates/file-impact-map.md`, если надо заранее показать, какие файлы будут затронуты
|
||||||
|
|
||||||
|
Главная идея: сначала короткая сводка, потом таблица файлов, потом проверки и риски. Не наоборот, потому что пользователь не обязан добывать смысл киркой.
|
||||||
|
|
||||||
|
## Что не является целью
|
||||||
|
|
||||||
|
- Перевод проекта в SaaS/gateway/server.
|
||||||
|
- Добавление облачного backend.
|
||||||
|
- Замена ProxiFyre без отдельной архитектурной задачи.
|
||||||
|
- Коммерциализация, telemetry-first подход или рекламная шелуха, этот вид пластика уже и так в океане.
|
||||||
30
.agent/checklists/change-safety.md
Normal file
30
.agent/checklists/change-safety.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Change Safety Checklist
|
||||||
|
|
||||||
|
Use this before and after non-trivial changes.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
- [ ] I identified whether this touches backend, UI, security, Windows service, subscription/routing, testing/release.
|
||||||
|
- [ ] I read the matching skill file.
|
||||||
|
- [ ] I avoided unrelated rewrites.
|
||||||
|
- [ ] I did not introduce a second source of truth.
|
||||||
|
|
||||||
|
## Tauri boundary
|
||||||
|
|
||||||
|
- [ ] New/changed Rust command has matching TypeScript wrapper.
|
||||||
|
- [ ] DTOs are synchronized between Rust and TypeScript.
|
||||||
|
- [ ] Error shape is structured and actionable.
|
||||||
|
- [ ] Blocking work is not run on async runtime thread.
|
||||||
|
|
||||||
|
## UX
|
||||||
|
|
||||||
|
- [ ] User-visible actions are explicit.
|
||||||
|
- [ ] Disabled states have reasons.
|
||||||
|
- [ ] Pending changes are visible before apply.
|
||||||
|
- [ ] Secrets are redacted.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
- [ ] Relevant frontend build/test was run or explicitly not run with reason.
|
||||||
|
- [ ] Relevant Rust fmt/clippy/test was run or explicitly not run with reason.
|
||||||
|
- [ ] Windows-specific behavior was not claimed unless tested on Windows.
|
||||||
37
.agent/checklists/communication.md
Normal file
37
.agent/checklists/communication.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Communication Checklist
|
||||||
|
|
||||||
|
Используй перед финальным ответом по любой нетривиальной задаче.
|
||||||
|
|
||||||
|
## Структура
|
||||||
|
|
||||||
|
- [ ] Ответ начинается с `Коротко` или с такой же короткой сводки на 2-4 пункта.
|
||||||
|
- [ ] Измененные файлы или зоны проекта перечислены в начале ответа, а не спрятаны в конце.
|
||||||
|
- [ ] Для каждого важного файла понятно: что изменилось и зачем.
|
||||||
|
- [ ] Важные изменения поведения, безопасности или состояния отделены от мелких деталей.
|
||||||
|
- [ ] Проверки разделены на `Проверено` и `Не проверено`.
|
||||||
|
- [ ] Риски написаны явно.
|
||||||
|
|
||||||
|
## Понятность
|
||||||
|
|
||||||
|
- [ ] Нет плотных абзацев длиннее 4-5 строк.
|
||||||
|
- [ ] Нет терминов и аббревиатур без пользы или краткого объяснения.
|
||||||
|
- [ ] Нет полных логов, если они не нужны для вывода.
|
||||||
|
- [ ] Нет пересказа каждой строки diff, если пользователь не просил.
|
||||||
|
- [ ] Нет мутных фраз вроде `улучшена архитектура` без объяснения, что стало проще, безопаснее или понятнее.
|
||||||
|
|
||||||
|
## Честность
|
||||||
|
|
||||||
|
- [ ] Windows/service/elevation поведение не названо проверенным, если оно не тестировалось на Windows.
|
||||||
|
- [ ] У пропущенных проверок есть простая причина.
|
||||||
|
- [ ] Ответ не говорит `готово`, если важные проверки пропущены.
|
||||||
|
|
||||||
|
## Быстрая самопроверка
|
||||||
|
|
||||||
|
Перед отправкой ответ должен отвечать на вопросы:
|
||||||
|
|
||||||
|
1. Что изменилось или найдено?
|
||||||
|
2. В каких файлах?
|
||||||
|
3. Зачем это нужно?
|
||||||
|
4. Что реально проверено?
|
||||||
|
5. Что не проверено?
|
||||||
|
6. Где остался риск?
|
||||||
41
.agent/checklists/explanation-quality.md
Normal file
41
.agent/checklists/explanation-quality.md
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# Checklist: Explanation Quality
|
||||||
|
|
||||||
|
Используй перед финальным ответом или PR summary.
|
||||||
|
|
||||||
|
## Обязательное
|
||||||
|
|
||||||
|
- [ ] В начале есть короткий итог на 2–4 пункта.
|
||||||
|
- [ ] Есть список файлов или таблица `файл / что / зачем`.
|
||||||
|
- [ ] Термины объяснены простыми словами, если они важны.
|
||||||
|
- [ ] Нет длинных полотен без заголовков.
|
||||||
|
- [ ] Нет пересказа каждой строки diff.
|
||||||
|
- [ ] Указано, что проверено.
|
||||||
|
- [ ] Указано, что не проверено.
|
||||||
|
- [ ] Риски написаны прямо, без «должно работать».
|
||||||
|
|
||||||
|
## Хороший формат
|
||||||
|
|
||||||
|
```md
|
||||||
|
## Коротко
|
||||||
|
- ...
|
||||||
|
|
||||||
|
## Файлы
|
||||||
|
| Файл | Что | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
- Выполнено: ...
|
||||||
|
- Не выполнено: ...
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
- ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Плохие признаки
|
||||||
|
|
||||||
|
- Один огромный абзац.
|
||||||
|
- Много терминов без пользы.
|
||||||
|
- «Исправлена логика» без указания файла и эффекта.
|
||||||
|
- «Проверено» без команды или способа проверки.
|
||||||
|
- «Не проверял Windows, но всё готово».
|
||||||
|
- Список из 25 пунктов одинаковой важности.
|
||||||
30
.agent/checklists/release.md
Normal file
30
.agent/checklists/release.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Release Checklist
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
- [ ] `npm ci`
|
||||||
|
- [ ] `npm run build`
|
||||||
|
- [ ] `cargo fmt --all -- --check`
|
||||||
|
- [ ] `cargo clippy --all-targets --all-features -- -D warnings`
|
||||||
|
- [ ] `cargo test --all-targets`
|
||||||
|
- [ ] `npm run tauri -- build`
|
||||||
|
|
||||||
|
## Windows smoke
|
||||||
|
|
||||||
|
- [ ] Fresh Windows VM smoke test.
|
||||||
|
- [ ] ProxiFyre install plan and real install.
|
||||||
|
- [ ] sing-box install plan and real install.
|
||||||
|
- [ ] External SOCKS5 route works.
|
||||||
|
- [ ] Local sing-box subscription route works.
|
||||||
|
- [ ] Start/stop/restart service controls work.
|
||||||
|
- [ ] Uninstall does not delete unmanaged paths.
|
||||||
|
|
||||||
|
## Security/release hygiene
|
||||||
|
|
||||||
|
- [ ] CSP enabled.
|
||||||
|
- [ ] Capabilities minimal.
|
||||||
|
- [ ] No raw secrets in repo/logs.
|
||||||
|
- [ ] Subscription redaction checked.
|
||||||
|
- [ ] Generated config writes are safe.
|
||||||
|
- [ ] Artifact version is correct.
|
||||||
|
- [ ] Large assets reviewed/compressed if practical.
|
||||||
36
.agent/checklists/security.md
Normal file
36
.agent/checklists/security.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Security Checklist
|
||||||
|
|
||||||
|
## Secrets
|
||||||
|
|
||||||
|
- [ ] Subscription URLs are redacted through parser-based logic.
|
||||||
|
- [ ] Proxy credentials are not logged.
|
||||||
|
- [ ] Outbound configs with secrets are not printed in diagnostics.
|
||||||
|
- [ ] Error messages do not include tokens/passwords/userinfo.
|
||||||
|
|
||||||
|
## Tauri/webview
|
||||||
|
|
||||||
|
- [ ] CSP is enabled.
|
||||||
|
- [ ] No broad shell permissions added.
|
||||||
|
- [ ] No direct command execution from UI input.
|
||||||
|
- [ ] No `dangerouslySetInnerHTML` or equivalent unsafe HTML rendering without sanitization.
|
||||||
|
|
||||||
|
## Network fetch
|
||||||
|
|
||||||
|
- [ ] Subscription fetch has timeout.
|
||||||
|
- [ ] URL scheme is restricted.
|
||||||
|
- [ ] Local/private/link-local/metadata address behavior is explicit.
|
||||||
|
- [ ] Redirect behavior does not bypass blocked address checks.
|
||||||
|
|
||||||
|
## Filesystem
|
||||||
|
|
||||||
|
- [ ] Critical writes are atomic where practical.
|
||||||
|
- [ ] Corrupt config handling does not silently discard user state.
|
||||||
|
- [ ] Recursive delete has strict path/marker checks.
|
||||||
|
- [ ] Temp elevated scripts use unpredictable names and safe directory/ACL when practical.
|
||||||
|
|
||||||
|
## Windows services
|
||||||
|
|
||||||
|
- [ ] Managed service is verified by name and PathName/metadata.
|
||||||
|
- [ ] Fuzzy candidates are not automatically controlled.
|
||||||
|
- [ ] UAC cancellation has clear error.
|
||||||
|
- [ ] Plan-only remains side-effect-free.
|
||||||
24
.agent/checklists/ui.md
Normal file
24
.agent/checklists/ui.md
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# UI Checklist
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
- [ ] No direct `invoke(...)` outside `src/api/tauriCommands.ts`.
|
||||||
|
- [ ] New reusable UI uses `src/ui/*` components or extends them.
|
||||||
|
- [ ] New business/display logic is not buried in JSX if it can be tested separately.
|
||||||
|
- [ ] `App.tsx` was not made worse without justification.
|
||||||
|
|
||||||
|
## Accessibility and behavior
|
||||||
|
|
||||||
|
- [ ] Buttons have accessible names.
|
||||||
|
- [ ] Toggle state uses `aria-pressed` or equivalent.
|
||||||
|
- [ ] Tabs/popovers preserve keyboard and screen-reader behavior.
|
||||||
|
- [ ] Reduced motion preference is respected where animation is added.
|
||||||
|
- [ ] Errors are visible and readable.
|
||||||
|
|
||||||
|
## ProxyWarden-specific
|
||||||
|
|
||||||
|
- [ ] External SOCKS5 route does not require sing-box.
|
||||||
|
- [ ] Local sing-box route requires selected server and readiness.
|
||||||
|
- [ ] Route chain matches actual backend state.
|
||||||
|
- [ ] Apply readiness gives a clear reason.
|
||||||
|
- [ ] Summary remains read-only.
|
||||||
248
.agent/skills/communication-reporting/SKILL.md
Normal file
248
.agent/skills/communication-reporting/SKILL.md
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
# Skill: Communication Reporting
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill в каждом ответе пользователю после анализа, правки кода, ревью, аудита, планирования рефакторинга или подготовки PR. Особенно если задача затрагивает несколько файлов, backend/frontend boundary, security, Windows services или UI.
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Писать так, чтобы человек с опытом разработки быстро понял суть без чтения технической простыни. Не упрощать до детского сада, но объяснять по-человечески: что поменялось, где, зачем, как проверить, где риск.
|
||||||
|
|
||||||
|
Пользователь не обязан продираться через внутренний монолог агента и каталог аббревиатур. У него есть жизнь, возможно даже вне репозитория, страшно представить.
|
||||||
|
|
||||||
|
## Базовый формат ответа
|
||||||
|
|
||||||
|
Для нетривиальных изменений используй такую структуру:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
- 2-4 пункта: главный результат, важный риск, что проверить.
|
||||||
|
|
||||||
|
Что изменилось по файлам
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| src/... | Кратко | Человеческая причина |
|
||||||
|
|
||||||
|
Важные места
|
||||||
|
- 3-6 конкретных мест: файл + функция/секция + смысл.
|
||||||
|
|
||||||
|
Как проверить
|
||||||
|
- Команды или ручные шаги.
|
||||||
|
|
||||||
|
Что не проверено
|
||||||
|
- Честно и коротко.
|
||||||
|
|
||||||
|
Риски
|
||||||
|
- Только реальные риски, не философия.
|
||||||
|
```
|
||||||
|
|
||||||
|
Если изменение маленькое, можно сократить до:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко: ...
|
||||||
|
|
||||||
|
Файлы:
|
||||||
|
- `path`: что и зачем.
|
||||||
|
|
||||||
|
Проверка: ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Правила ясности
|
||||||
|
|
||||||
|
- Сначала вывод, потом детали.
|
||||||
|
- Не писать длиннее, чем нужно для решения задачи.
|
||||||
|
- Не перечислять каждую строку diff. Указывать только смысловые изменения.
|
||||||
|
- Всегда называть конкретные файлы.
|
||||||
|
- Для сложных мест указывать функцию, модуль или секцию, если это помогает найти код.
|
||||||
|
- Если используешь термин, рядом дать короткое человеческое объяснение.
|
||||||
|
- Не использовать аббревиатуры без расшифровки при первом упоминании, кроме очевидных: UI, JSON, URL, API.
|
||||||
|
- Не писать «улучшена архитектура» без объяснения, что именно стало проще или безопаснее.
|
||||||
|
- Не писать «всё готово», если часть проверок не запускалась.
|
||||||
|
- Не скрывать ошибки окружения. Если `cargo` или Windows недоступны, так и сказать.
|
||||||
|
|
||||||
|
## Как объяснять технические изменения
|
||||||
|
|
||||||
|
Плохо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Refactored orchestration layer and extracted imperative use-case side effects into composable boundaries.
|
||||||
|
```
|
||||||
|
|
||||||
|
Хорошо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Вынес запуск service-команд из большого `commands.rs` в отдельный модуль. Теперь Tauri command только принимает запрос и возвращает ошибку, а вся Windows-логика лежит отдельно. Так проще тестировать и меньше шанс сломать соседние команды.
|
||||||
|
```
|
||||||
|
|
||||||
|
Плохо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Added CSP hardening.
|
||||||
|
```
|
||||||
|
|
||||||
|
Хорошо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Включил CSP в `src-tauri/tauri.conf.json`. Это ограничивает, какие скрипты/ресурсы может загрузить webview, и снижает ущерб, если в UI когда-нибудь появится XSS.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Уровни детализации
|
||||||
|
|
||||||
|
По умолчанию — средний уровень:
|
||||||
|
|
||||||
|
- достаточно конкретно, чтобы разработчик понял diff;
|
||||||
|
- без пересказа каждой строки;
|
||||||
|
- без внутренних рассуждений агента;
|
||||||
|
- без длинной теории.
|
||||||
|
|
||||||
|
Если пользователь просит глубже, добавь раздел:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Детальнее
|
||||||
|
- ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Если пользователь просит совсем кратко, оставь только:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
Файлы
|
||||||
|
Проверка
|
||||||
|
```
|
||||||
|
|
||||||
|
## Таблица файлов
|
||||||
|
|
||||||
|
Для 2+ файлов почти всегда используй таблицу:
|
||||||
|
|
||||||
|
| Файл | Тип изменения | Смысл |
|
||||||
|
|---|---|---|
|
||||||
|
| `src/api/tauriCommands.ts` | API boundary | Добавлен typed wrapper для новой Tauri command |
|
||||||
|
| `src-tauri/src/commands.rs` | Backend | Добавлена команда, которая вызывает уже существующую service-логику |
|
||||||
|
|
||||||
|
Правила:
|
||||||
|
|
||||||
|
- Не вставлять огромные таблицы на 30 строк. Группировать мелкие файлы.
|
||||||
|
- В колонке `Смысл` писать человеческую причину, не только «обновлено».
|
||||||
|
- Если файл опасный, отметить это: `security-sensitive`, `Windows/elevation`, `storage`, `routing`.
|
||||||
|
|
||||||
|
## Как писать про риски
|
||||||
|
|
||||||
|
Риск должен быть конкретным:
|
||||||
|
|
||||||
|
Плохо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Есть некоторые риски.
|
||||||
|
```
|
||||||
|
|
||||||
|
Хорошо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Риск: я не запускал real Windows service flow, поэтому install/start/stop надо проверить на Windows 10/11 с UAC.
|
||||||
|
```
|
||||||
|
|
||||||
|
Плохо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Может быть несовместимость.
|
||||||
|
```
|
||||||
|
|
||||||
|
Хорошо:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Риск: если у пользователя уже стоит чужая служба с похожим именем ProxiFyre, fuzzy detection может показать ее кандидатом. Управлять ей нельзя без проверки `PathName`.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Как писать про проверки
|
||||||
|
|
||||||
|
Разделяй выполненное и невыполненное:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Проверено
|
||||||
|
- `npm run build` — прошел.
|
||||||
|
- Markdown-файлы открываются, битых путей не нашел.
|
||||||
|
|
||||||
|
Не проверено
|
||||||
|
- `cargo test` — не запускал, в среде нет Rust toolchain.
|
||||||
|
- Windows service flow — не проверял, нужна Windows-машина с UAC.
|
||||||
|
```
|
||||||
|
|
||||||
|
Не объединять это в мутное «тесты частично пройдены». Машины и люди заслуживают хотя бы грамм конкретики.
|
||||||
|
|
||||||
|
## Запрещенный стиль
|
||||||
|
|
||||||
|
Не писать:
|
||||||
|
|
||||||
|
- огромные абзацы без заголовков;
|
||||||
|
- «магия», «оптимизировано», «улучшено» без конкретики;
|
||||||
|
- внутренний дневник действий агента;
|
||||||
|
- цепочки мыслей;
|
||||||
|
- список всех строк diff;
|
||||||
|
- рекламный тон;
|
||||||
|
- уверенные заявления о непроверенных Windows/elevation сценариях;
|
||||||
|
- «как вы и просили, я с радостью...» — репозиторий от этого лучше не станет.
|
||||||
|
|
||||||
|
## Мини-шаблоны
|
||||||
|
|
||||||
|
### Для bugfix
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
- Исправил ...
|
||||||
|
- Основной риск был ...
|
||||||
|
- Проверка: ...
|
||||||
|
|
||||||
|
Что изменилось по файлам
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
|
||||||
|
Важные места
|
||||||
|
- `file`: ...
|
||||||
|
|
||||||
|
Проверено
|
||||||
|
- ...
|
||||||
|
|
||||||
|
Не проверено
|
||||||
|
- ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Для ревью без правок
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
- Самая важная проблема: ...
|
||||||
|
- Второй приоритет: ...
|
||||||
|
- Быстрый выигрыш: ...
|
||||||
|
|
||||||
|
Что я смотрел
|
||||||
|
- ...
|
||||||
|
|
||||||
|
Проблемы по важности
|
||||||
|
1. Critical/High: ...
|
||||||
|
2. Medium: ...
|
||||||
|
3. Low: ...
|
||||||
|
|
||||||
|
Что бы я сделал первым
|
||||||
|
- ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### Для плана изменений
|
||||||
|
|
||||||
|
```text
|
||||||
|
Коротко
|
||||||
|
- Цель: ...
|
||||||
|
- Затронет: ...
|
||||||
|
- Не трогаем: ...
|
||||||
|
|
||||||
|
План по файлам
|
||||||
|
| Файл/зона | Что сделать | Почему |
|
||||||
|
|---|---|---|
|
||||||
|
|
||||||
|
Порядок работ
|
||||||
|
1. ...
|
||||||
|
2. ...
|
||||||
|
3. ...
|
||||||
|
|
||||||
|
Проверка
|
||||||
|
- ...
|
||||||
|
```
|
||||||
93
.agent/skills/react-typescript-ui/SKILL.md
Normal file
93
.agent/skills/react-typescript-ui/SKILL.md
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
# Skill: React / TypeScript UI
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при изменениях в `src`, UI, state management, typed Tauri wrappers, readiness logic, route visualization, forms, logs, buttons, popovers, service panels.
|
||||||
|
|
||||||
|
## Главная цель
|
||||||
|
|
||||||
|
UI должен ясно объяснять, что будет сделано с сетью пользователя, не прятать опасные действия и не превращаться в панель управления космической станцией ради одной прокси-кнопки.
|
||||||
|
|
||||||
|
## Инварианты
|
||||||
|
|
||||||
|
- `src/api/tauriCommands.ts` — единственное место для `invoke(...)`.
|
||||||
|
- `src/domain/types.ts` должен отражать backend DTO.
|
||||||
|
- Apply-readiness logic живет в `src/app/readiness.ts`.
|
||||||
|
- Presentational UI должен переиспользовать `src/ui/*`.
|
||||||
|
- Summary panel read-only.
|
||||||
|
- Install/start/stop/uninstall/apply actions must be explicit.
|
||||||
|
- Secrets must be redacted.
|
||||||
|
|
||||||
|
## App.tsx rule
|
||||||
|
|
||||||
|
`src/app/App.tsx` уже слишком большой. Новую логику не добавлять туда, если можно вынести:
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/app/hooks/useStartupSnapshot.ts
|
||||||
|
src/app/hooks/useApplyFlow.ts
|
||||||
|
src/app/hooks/useServiceControl.ts
|
||||||
|
src/app/hooks/useSubscription.ts
|
||||||
|
src/app/lib/parseProxy.ts
|
||||||
|
src/app/lib/snapshots.ts
|
||||||
|
src/app/components/RouteChain.tsx
|
||||||
|
src/app/components/ChangesDock.tsx
|
||||||
|
src/app/components/ProxyPanel.tsx
|
||||||
|
src/app/components/SingBoxWorkspace.tsx
|
||||||
|
```
|
||||||
|
|
||||||
|
Если изменение маленькое и локальное, допустимо править `App.tsx`, но не расширять его архитектурную роль.
|
||||||
|
|
||||||
|
## UI behavior rules
|
||||||
|
|
||||||
|
- Disabled button must explain why.
|
||||||
|
- Loading/busy state must prevent double submit.
|
||||||
|
- Errors must be human-readable and actionable.
|
||||||
|
- Long paths, service names and tags must not break layout.
|
||||||
|
- Do not use native `title` as main tooltip UX. Use existing popover/tooltip pattern.
|
||||||
|
- Use `aria-*` for tabs, toggle buttons, popovers, service controls.
|
||||||
|
- Honor reduced motion where relevant.
|
||||||
|
|
||||||
|
## Proxy/routing UI
|
||||||
|
|
||||||
|
When editing route UI:
|
||||||
|
|
||||||
|
- External SOCKS5 mode must not require sing-box.
|
||||||
|
- Local sing-box mode must require selected server and sing-box readiness.
|
||||||
|
- App list must clearly distinguish process, folder, exe/path if those are different target kinds.
|
||||||
|
- Route chain should reflect actual backend target/profile state.
|
||||||
|
- Pending changes should be visible before apply.
|
||||||
|
|
||||||
|
## Tests/checks
|
||||||
|
|
||||||
|
Minimum:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Recommended for extracted pure logic:
|
||||||
|
|
||||||
|
- Unit tests for proxy parsing.
|
||||||
|
- Unit tests for readiness states.
|
||||||
|
- Unit tests for snapshot diff/change dock model.
|
||||||
|
- UI smoke checks for desktop and narrow layout.
|
||||||
|
|
||||||
|
## Do not
|
||||||
|
|
||||||
|
- Do not call backend commands from random components.
|
||||||
|
- Do not store secrets in React state longer than needed if display value can be redacted.
|
||||||
|
- Do not duplicate Rust validation as the only validation. Frontend validation is UX, backend validation is authority.
|
||||||
|
- Do not add a visual state that implies a service is running unless backend confirmed it.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
78
.agent/skills/repository-orientation/SKILL.md
Normal file
78
.agent/skills/repository-orientation/SKILL.md
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# Skill: Repository Orientation
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill в начале любой нетривиальной задачи по ProxyWarden: аудит, рефакторинг, bugfix, изменение UI, изменение Windows service flow, изменение subscription/routing.
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Быстро понять, где находится нужная логика, какие инварианты нельзя нарушать и какие проверки нужны перед финальным ответом.
|
||||||
|
|
||||||
|
## Карта проекта
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/api/tauriCommands.ts typed frontend API boundary
|
||||||
|
src/domain/types.ts TypeScript DTO/domain mirror
|
||||||
|
src/app/App.tsx current UI orchestration, large file
|
||||||
|
src/app/readiness.ts apply readiness/gating
|
||||||
|
src/app/viewModel.ts view helpers
|
||||||
|
src/ui/* reusable UI components
|
||||||
|
src/styles/app.css global/component CSS
|
||||||
|
|
||||||
|
src-tauri/src/models.rs Rust domain models
|
||||||
|
src-tauri/src/validation.rs input normalization/validation
|
||||||
|
src-tauri/src/storage.rs JSON config/state storage
|
||||||
|
src-tauri/src/activity.rs activity log
|
||||||
|
src-tauri/src/subscription.rs subscription fetch/parse
|
||||||
|
src-tauri/src/component_detection.rs component status detection
|
||||||
|
src-tauri/src/adapters/* ProxiFyre/sing-box/proxy router adapters
|
||||||
|
src-tauri/src/commands.rs Tauri command layer, currently too large
|
||||||
|
src-tauri/tests/* Rust tests
|
||||||
|
scripts/*.ps1 Windows install/control scripts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source of truth
|
||||||
|
|
||||||
|
- Persistent app config/state: `C:\ProgramData\ProxyWarden\config` and `state`.
|
||||||
|
- Generated artifacts: `C:\ProgramData\ProxyWarden\generated`.
|
||||||
|
- Frontend state is not source of truth. It should represent backend state and pending UI edits.
|
||||||
|
- Component detection/runtime status should come from backend, not guessed in UI.
|
||||||
|
|
||||||
|
## First-pass procedure
|
||||||
|
|
||||||
|
1. Identify whether the task is backend, UI, security, Windows service, subscription/routing, or testing/release.
|
||||||
|
2. Read the matching skill file.
|
||||||
|
3. Inspect the relevant source files listed above.
|
||||||
|
4. Determine whether the change crosses the Tauri boundary. If yes, update both Rust DTO/command and TypeScript wrapper/types.
|
||||||
|
5. Determine whether the change touches secrets, service control, generated configs, process execution, filesystem deletion, or network fetch. If yes, apply security checklist.
|
||||||
|
6. Prefer small, isolated changes over broad rewrites.
|
||||||
|
|
||||||
|
## Do not
|
||||||
|
|
||||||
|
- Do not treat `App.tsx` or `commands.rs` as the correct permanent architecture just because they currently contain lots of logic.
|
||||||
|
- Do not introduce a second storage system.
|
||||||
|
- Do not move service/install logic into frontend.
|
||||||
|
- Do not claim Windows service/elevation behavior is verified unless it was actually tested on Windows.
|
||||||
|
|
||||||
|
## Output expectations
|
||||||
|
|
||||||
|
For code changes, final report should include:
|
||||||
|
|
||||||
|
- Changed files.
|
||||||
|
- User-visible behavior changes.
|
||||||
|
- Internal behavior changes.
|
||||||
|
- Tests/checks run.
|
||||||
|
- Known unverified areas.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
106
.agent/skills/rust-tauri-backend/SKILL.md
Normal file
106
.agent/skills/rust-tauri-backend/SKILL.md
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
# Skill: Rust / Tauri Backend
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при изменениях в `src-tauri`, Tauri commands, Rust models, validation, storage, adapters, component detection, subscription fetching, config generation или service orchestration.
|
||||||
|
|
||||||
|
## Главная цель
|
||||||
|
|
||||||
|
Держать backend надежным, типизированным и безопасным. Backend управляет системой пользователя, поэтому «ну вроде работает» здесь примерно как инструкция по посадке самолета, написанная на салфетке.
|
||||||
|
|
||||||
|
## Инварианты
|
||||||
|
|
||||||
|
- Tauri command layer должен быть thin boundary, а не склад всей бизнес-логики.
|
||||||
|
- Долгие/blocking операции не должны выполняться на async runtime thread.
|
||||||
|
- Все ошибки, которые видит UI, должны быть structured and actionable.
|
||||||
|
- Validation должна происходить на backend даже если UI уже проверяет input.
|
||||||
|
- Generated config writes должны быть atomic where practical.
|
||||||
|
- Secrets never logged or fully displayed.
|
||||||
|
|
||||||
|
## Preferred command pattern
|
||||||
|
|
||||||
|
Для тяжелых операций:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn some_command(input: SomeInput) -> Result<SomeOutput, CommandError> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || some_command_impl(input))
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Implementation function должна быть тестируемой без Tauri runtime, если возможно.
|
||||||
|
|
||||||
|
## DTO boundary
|
||||||
|
|
||||||
|
При добавлении или изменении command:
|
||||||
|
|
||||||
|
1. Rust input/output DTO.
|
||||||
|
2. TypeScript DTO in `src/domain/types.ts`.
|
||||||
|
3. Wrapper in `src/api/tauriCommands.ts`.
|
||||||
|
4. UI usage.
|
||||||
|
5. Tests for pure logic.
|
||||||
|
|
||||||
|
Не использовать `serde_json::Value` как permanent API, если структура известна.
|
||||||
|
|
||||||
|
## Error handling
|
||||||
|
|
||||||
|
- Не использовать `unwrap()`/`expect()` в production path.
|
||||||
|
- Возвращать `CommandError { code, message, details }`.
|
||||||
|
- Для validation использовать список проблем, а не первую попавшуюся ошибку.
|
||||||
|
- Internal error text не должен раскрывать secrets.
|
||||||
|
- Если операция partial, вернуть partial state/result where possible.
|
||||||
|
|
||||||
|
## Storage
|
||||||
|
|
||||||
|
При изменении `storage.rs`:
|
||||||
|
|
||||||
|
- Keep tmp + bak write pattern.
|
||||||
|
- Не превращать invalid JSON в default молча. Prefer corruption backup/restore path.
|
||||||
|
- Для critical writes использовать same-directory temp file and rename.
|
||||||
|
- Не хранить derived artifacts как source of truth.
|
||||||
|
- Не хранить raw subscription/proxy secrets в activity log.
|
||||||
|
|
||||||
|
## Refactoring guidance
|
||||||
|
|
||||||
|
`src-tauri/src/commands.rs` слишком большой. Новую логику по возможности выносить:
|
||||||
|
|
||||||
|
```text
|
||||||
|
commands/dto.rs
|
||||||
|
commands/status.rs
|
||||||
|
commands/profiles.rs
|
||||||
|
commands/targets.rs
|
||||||
|
commands/components.rs
|
||||||
|
commands/subscription.rs
|
||||||
|
commands/proxifyre.rs
|
||||||
|
commands/singbox.rs
|
||||||
|
services/elevated.rs
|
||||||
|
services/powershell.rs
|
||||||
|
services/proxifyre_service.rs
|
||||||
|
services/singbox_service.rs
|
||||||
|
```
|
||||||
|
|
||||||
|
При рефакторинге сохранять external command names, чтобы UI не ломался без причины.
|
||||||
|
|
||||||
|
## Validation checklist
|
||||||
|
|
||||||
|
- `cargo fmt --all -- --check`
|
||||||
|
- `cargo clippy --all-targets --all-features -- -D warnings`
|
||||||
|
- `cargo test --all-targets`
|
||||||
|
- Relevant Windows/manual check if touching service/install/elevation.
|
||||||
|
|
||||||
|
Если `cargo` недоступен в среде, честно написать, что backend проверен только статически. Не изображать компилятор, у него и так тяжелая жизнь.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
138
.agent/skills/security-hardening/SKILL.md
Normal file
138
.agent/skills/security-hardening/SKILL.md
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
# Skill: Security Hardening
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при изменениях, связанных с Tauri security, CSP, secrets, subscription fetching, process execution, PowerShell, temporary files, install/uninstall, file writes, generated configs, service control, logs, diagnostics.
|
||||||
|
|
||||||
|
## Threat model
|
||||||
|
|
||||||
|
ProxyWarden — desktop app that can influence network routing and run elevated Windows operations. Главные риски:
|
||||||
|
|
||||||
|
- leaking proxy/subscription credentials;
|
||||||
|
- unsafe local/network fetches;
|
||||||
|
- unsafe generated elevated PowerShell scripts;
|
||||||
|
- unscoped process execution;
|
||||||
|
- corrupting generated/service configs;
|
||||||
|
- deleting wrong directories;
|
||||||
|
- stale component status causing wrong actions;
|
||||||
|
- XSS/webview compromise amplified by privileged backend commands.
|
||||||
|
|
||||||
|
## Non-negotiables
|
||||||
|
|
||||||
|
- `tauri.conf.json` must not use `"csp": null` as final state.
|
||||||
|
- Do not add broad Tauri shell permissions.
|
||||||
|
- Do not execute user-controlled strings as commands.
|
||||||
|
- Do not log full subscription URLs, proxy passwords, userinfo, access tokens, or outbound configs with credentials.
|
||||||
|
- Do not recursively delete directories based only on fuzzy name matching.
|
||||||
|
- Do not treat fuzzy-detected services as managed without verification.
|
||||||
|
|
||||||
|
## CSP guidance
|
||||||
|
|
||||||
|
Prefer a restrictive CSP such as:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"security": {
|
||||||
|
"csp": "default-src 'self'; img-src 'self' asset: data:; style-src 'self' 'unsafe-inline'; script-src 'self'"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Tighten further when possible. If inline styles are removed, remove `'unsafe-inline'`.
|
||||||
|
|
||||||
|
## Secret redaction
|
||||||
|
|
||||||
|
For URLs use a parser, not string splitting. Redacted display should include only:
|
||||||
|
|
||||||
|
- scheme;
|
||||||
|
- host;
|
||||||
|
- port if useful;
|
||||||
|
- generic path marker if necessary.
|
||||||
|
|
||||||
|
Never show:
|
||||||
|
|
||||||
|
- username;
|
||||||
|
- password;
|
||||||
|
- query string;
|
||||||
|
- fragment;
|
||||||
|
- subscription token path;
|
||||||
|
- full proxy credentials.
|
||||||
|
|
||||||
|
Bad:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://user:password@example.com/...
|
||||||
|
```
|
||||||
|
|
||||||
|
Good:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://example.com/...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Subscription fetch hardening
|
||||||
|
|
||||||
|
- Add connect/read timeout.
|
||||||
|
- Accept only `http` and `https` unless explicitly designed otherwise.
|
||||||
|
- Consider blocking loopback/private/link-local/multicast/metadata addresses by default.
|
||||||
|
- Add explicit allow-local option only if needed.
|
||||||
|
- Do not follow redirects into blocked address ranges without re-check.
|
||||||
|
- Avoid storing remote body in logs.
|
||||||
|
|
||||||
|
## Temp/elevated script hardening
|
||||||
|
|
||||||
|
Runtime-generated elevated scripts must:
|
||||||
|
|
||||||
|
- use unpredictable names, preferably UUID/random;
|
||||||
|
- be written to a safe controlled directory where possible;
|
||||||
|
- set restrictive ACL when practical;
|
||||||
|
- be generated from static templates with escaped parameters;
|
||||||
|
- avoid including secrets in command line args;
|
||||||
|
- be cleaned up best-effort;
|
||||||
|
- fail closed if path validation fails.
|
||||||
|
|
||||||
|
Timestamp-only temp names are not enough.
|
||||||
|
|
||||||
|
## Atomic writes
|
||||||
|
|
||||||
|
For config files used by services:
|
||||||
|
|
||||||
|
1. Write to temp file in same directory.
|
||||||
|
2. Validate temp file if validator exists.
|
||||||
|
3. Backup current file.
|
||||||
|
4. Rename temp to final.
|
||||||
|
5. On failure, preserve backup and return actionable error.
|
||||||
|
|
||||||
|
## Safe delete checklist
|
||||||
|
|
||||||
|
Before recursive delete:
|
||||||
|
|
||||||
|
- Is path absolute?
|
||||||
|
- Is it under expected managed root?
|
||||||
|
- Does it contain ProxyWarden marker metadata?
|
||||||
|
- Does service PathName point inside this directory?
|
||||||
|
- Is it not drive root, user profile root, Desktop, ProgramData root, Windows directory, temp root?
|
||||||
|
- Is user action explicit?
|
||||||
|
|
||||||
|
If answer is unclear, do not delete.
|
||||||
|
|
||||||
|
## Final report expectations
|
||||||
|
|
||||||
|
When touching security-sensitive code, report:
|
||||||
|
|
||||||
|
- what threat was addressed;
|
||||||
|
- what was hardened;
|
||||||
|
- what remains unverified;
|
||||||
|
- whether any secrets could appear in logs/UI;
|
||||||
|
- whether Windows elevated path was tested.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
87
.agent/skills/subscriptions-routing/SKILL.md
Normal file
87
.agent/skills/subscriptions-routing/SKILL.md
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# Skill: Subscriptions and Routing
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при изменениях в external SOCKS5 flow, Local sing-box flow, subscription fetching/parsing, server selection, ping/check route, ProxiFyre config generation или sing-box config generation.
|
||||||
|
|
||||||
|
## Mental model
|
||||||
|
|
||||||
|
Supported route shapes:
|
||||||
|
|
||||||
|
```text
|
||||||
|
selected Windows apps -> ProxiFyre -> external SOCKS5 proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
selected Windows apps -> ProxiFyre -> 127.0.0.1:1080 Local sing-box -> selected subscription server
|
||||||
|
```
|
||||||
|
|
||||||
|
ProxiFyre is the per-app router. Sing-box is optional local outbound runtime.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- External SOCKS5 must work without Local sing-box.
|
||||||
|
- Local sing-box route requires installed/configured/running sing-box and selected server.
|
||||||
|
- UI route chain must match generated backend config.
|
||||||
|
- Subscription URL is secret.
|
||||||
|
- Server identity should not rely only on non-unique human tag forever.
|
||||||
|
- Generated config should be validated before apply/start where possible.
|
||||||
|
|
||||||
|
## Subscription rules
|
||||||
|
|
||||||
|
When changing subscription parsing:
|
||||||
|
|
||||||
|
- Preserve JSON outbound support.
|
||||||
|
- Do not claim support for link formats that parser does not implement.
|
||||||
|
- If adding VMess/Trojan/Shadowsocks link parsing, add tests for each.
|
||||||
|
- Keep unsupported outbound types visible as unsupported, not silently dropped if this affects user expectation.
|
||||||
|
- Redact subscription URL and outbound secrets in logs/UI.
|
||||||
|
|
||||||
|
## Ping/check rules
|
||||||
|
|
||||||
|
- Network checks should have timeout.
|
||||||
|
- Checks should be cancel-safe where possible.
|
||||||
|
- Do not make route check mutate config/service state.
|
||||||
|
- Do not store external IP probe result as secret, but avoid over-logging.
|
||||||
|
- Make it clear if check verifies local sing-box only, external proxy only, or full route.
|
||||||
|
|
||||||
|
## Config generation
|
||||||
|
|
||||||
|
For ProxiFyre:
|
||||||
|
|
||||||
|
- Respect selected app targets.
|
||||||
|
- Deduplicate carefully, preferably case-insensitive where Windows semantics apply.
|
||||||
|
- Validate target kind semantics: process name vs exe path vs folder.
|
||||||
|
- Write config atomically.
|
||||||
|
|
||||||
|
For sing-box:
|
||||||
|
|
||||||
|
- Validate selected server/outbound exists.
|
||||||
|
- Avoid duplicate tag ambiguity by introducing stable id if needed.
|
||||||
|
- Run `sing-box check` when binary is available.
|
||||||
|
- Avoid writing secrets to temp files outside safe app directories.
|
||||||
|
|
||||||
|
## Tests to add for changes
|
||||||
|
|
||||||
|
- External route without sing-box.
|
||||||
|
- Local route with selected server.
|
||||||
|
- Missing ProxiFyre blocks apply.
|
||||||
|
- Missing sing-box blocks local route apply.
|
||||||
|
- Duplicate server tags.
|
||||||
|
- Redacted subscription display.
|
||||||
|
- Unsupported subscription formats.
|
||||||
|
- Timeout/fetch failure.
|
||||||
|
- Config generation produces expected route chain.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
104
.agent/skills/testing-ci-release/SKILL.md
Normal file
104
.agent/skills/testing-ci-release/SKILL.md
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
# Skill: Testing, CI and Release
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при добавлении CI, release scripts, build fixes, test changes, dependency updates, packaging changes или перед финальным отчетом по крупной задаче.
|
||||||
|
|
||||||
|
## Minimal local checks
|
||||||
|
|
||||||
|
Frontend:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Rust:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd src-tauri
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo clippy --all-targets --all-features -- -D warnings
|
||||||
|
cargo test --all-targets
|
||||||
|
```
|
||||||
|
|
||||||
|
Tauri:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
npm run tauri -- info
|
||||||
|
npm run tauri -- build
|
||||||
|
```
|
||||||
|
|
||||||
|
PowerShell plan-only:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
& .\scripts\install-control-app.ps1 -PlanOnly
|
||||||
|
& .\scripts\install-proxyfier.ps1 -PlanOnly
|
||||||
|
& .\scripts\install-singbox.ps1 -PlanOnly
|
||||||
|
```
|
||||||
|
|
||||||
|
## CI recommendation
|
||||||
|
|
||||||
|
Add GitHub Actions with at least:
|
||||||
|
|
||||||
|
- frontend build on Windows and Ubuntu if practical;
|
||||||
|
- Rust fmt/clippy/test;
|
||||||
|
- PowerShell syntax/plan-only smoke on Windows;
|
||||||
|
- Tauri build on Windows for release branches/tags;
|
||||||
|
- artifact upload only for trusted release workflow.
|
||||||
|
|
||||||
|
## Dependency updates
|
||||||
|
|
||||||
|
When changing dependencies:
|
||||||
|
|
||||||
|
- Update lockfiles.
|
||||||
|
- Check Tauri v2 compatibility.
|
||||||
|
- Avoid adding large UI/runtime dependencies for tiny tasks.
|
||||||
|
- Avoid adding shell/process libraries that bypass existing backend boundaries.
|
||||||
|
- Note why dependency is needed.
|
||||||
|
|
||||||
|
## Release hygiene
|
||||||
|
|
||||||
|
Before release:
|
||||||
|
|
||||||
|
- Verify app version in `package.json` and Tauri config if applicable.
|
||||||
|
- Verify icons/assets size.
|
||||||
|
- Verify CSP and capabilities.
|
||||||
|
- Verify no raw secrets/test URLs in repo.
|
||||||
|
- Verify installer scripts with `-PlanOnly`.
|
||||||
|
- Verify clean install on Windows VM.
|
||||||
|
- Verify external SOCKS5 flow.
|
||||||
|
- Verify local sing-box subscription flow.
|
||||||
|
- Verify uninstall/safe cleanup behavior.
|
||||||
|
|
||||||
|
## Final report format
|
||||||
|
|
||||||
|
```text
|
||||||
|
Changed:
|
||||||
|
- ...
|
||||||
|
|
||||||
|
Verified:
|
||||||
|
- npm run build
|
||||||
|
- cargo test
|
||||||
|
|
||||||
|
Not verified:
|
||||||
|
- Windows elevated install/uninstall, because ...
|
||||||
|
|
||||||
|
Risks:
|
||||||
|
- ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not write “all tests pass” unless all listed relevant tests actually ran. Humanity has enough fictional dashboards.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
94
.agent/skills/windows-services-powershell/SKILL.md
Normal file
94
.agent/skills/windows-services-powershell/SKILL.md
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
# Skill: Windows Services / PowerShell / Elevation
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
Используй этот skill при изменениях в `scripts/*.ps1`, ProxiFyre install/start/stop/uninstall, sing-box service control, UAC/admin checks, helper/elevation boundary, component detection.
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Сохранять service/install operations явными, безопасными и проверяемыми. Пользователь должен понимать, что приложение собирается менять в системе. Компьютер пользователя — не песочница для творческих экспериментов агента, как ни печально.
|
||||||
|
|
||||||
|
## Инварианты
|
||||||
|
|
||||||
|
- Install/start/stop/uninstall are explicit user actions.
|
||||||
|
- `apply` must not silently install/uninstall/start/stop components unless that behavior is clearly designed and surfaced.
|
||||||
|
- `-PlanOnly` scripts must be side-effect-free.
|
||||||
|
- PowerShell output intended for UI/backend must be structured JSON.
|
||||||
|
- Service detection must distinguish managed service from fuzzy candidate.
|
||||||
|
- Never relax safe-path checks to make uninstall easier.
|
||||||
|
|
||||||
|
## Script rules
|
||||||
|
|
||||||
|
PowerShell scripts should:
|
||||||
|
|
||||||
|
- use `Set-StrictMode -Version Latest` where practical;
|
||||||
|
- set `$ErrorActionPreference = 'Stop'`;
|
||||||
|
- return structured JSON for plan/status paths;
|
||||||
|
- avoid localized text parsing for control flow;
|
||||||
|
- avoid writing secrets to host output;
|
||||||
|
- have clear exit codes;
|
||||||
|
- support `-PlanOnly` for dry-run/status checks;
|
||||||
|
- avoid downloading/executing arbitrary remote scripts.
|
||||||
|
|
||||||
|
## Elevation rules
|
||||||
|
|
||||||
|
When launching elevated PowerShell:
|
||||||
|
|
||||||
|
- keep command fixed and parameters escaped;
|
||||||
|
- avoid user-controlled script text;
|
||||||
|
- avoid predictable temp script names;
|
||||||
|
- do not pass secrets via command line;
|
||||||
|
- verify script path before launch;
|
||||||
|
- clean up temp artifacts best-effort;
|
||||||
|
- return clear error if user cancels UAC.
|
||||||
|
|
||||||
|
## Service detection
|
||||||
|
|
||||||
|
Preferred approach:
|
||||||
|
|
||||||
|
1. Search known managed service names first.
|
||||||
|
2. Read service `PathName` through WMI/CIM.
|
||||||
|
3. Verify binary path and managed install metadata.
|
||||||
|
4. Only then mark as managed/controllable.
|
||||||
|
5. Fuzzy matches should be shown as candidates, not automatically controlled.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Pure logic can be tested cross-platform with mocks.
|
||||||
|
|
||||||
|
Real verification requires Windows:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
& .\scripts\install-control-app.ps1 -PlanOnly
|
||||||
|
& .\scripts\install-proxyfier.ps1 -PlanOnly
|
||||||
|
& .\scripts\install-singbox.ps1 -PlanOnly
|
||||||
|
npm run tauri -- dev
|
||||||
|
```
|
||||||
|
|
||||||
|
For real service tests:
|
||||||
|
|
||||||
|
- Windows 10/11.
|
||||||
|
- Admin/UAC path.
|
||||||
|
- Fresh machine or VM snapshot.
|
||||||
|
- Existing ProxiFyre/sing-box absent.
|
||||||
|
- Existing fuzzy ProxiFyre-like service present, if testing safety.
|
||||||
|
|
||||||
|
## Do not
|
||||||
|
|
||||||
|
- Do not claim actual service operations were tested unless they were run on Windows.
|
||||||
|
- Do not parse human-localized `sc.exe` output if structured WMI/CIM data is available.
|
||||||
|
- Do not delete paths from fuzzy discovery alone.
|
||||||
|
- Do not make scripts silently modify firewall/proxy/system settings outside their stated purpose.
|
||||||
|
|
||||||
|
## Как отчитываться
|
||||||
|
|
||||||
|
Перед финальным ответом применить `.agent/skills/communication-reporting/SKILL.md` и `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
Минимум для нетривиальной задачи:
|
||||||
|
|
||||||
|
- короткая сводка;
|
||||||
|
- таблица файлов `Файл / Что изменилось / Зачем`;
|
||||||
|
- важные места без пересказа каждой строки;
|
||||||
|
- что проверено;
|
||||||
|
- что не проверено;
|
||||||
|
- конкретные риски.
|
||||||
29
.agent/templates/change-report.md
Normal file
29
.agent/templates/change-report.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Change Report
|
||||||
|
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
-
|
||||||
|
-
|
||||||
|
-
|
||||||
|
|
||||||
|
## Файлы
|
||||||
|
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | | |
|
||||||
|
|
||||||
|
## Важные детали
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- ✅/⚠️ `command` — результат простыми словами.
|
||||||
|
|
||||||
|
## Не проверено
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Риски / что потом
|
||||||
|
|
||||||
|
-
|
||||||
30
.agent/templates/concise-change-summary.md
Normal file
30
.agent/templates/concise-change-summary.md
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Concise Change Summary Template
|
||||||
|
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
-
|
||||||
|
-
|
||||||
|
-
|
||||||
|
|
||||||
|
## Что изменилось по файлам
|
||||||
|
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/to/file` | | |
|
||||||
|
|
||||||
|
## Важные места
|
||||||
|
|
||||||
|
- `path/to/file`, функция/секция:
|
||||||
|
- `path/to/file`, функция/секция:
|
||||||
|
|
||||||
|
## Проверено
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Не проверено
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
|
||||||
|
-
|
||||||
20
.agent/templates/file-impact-map.md
Normal file
20
.agent/templates/file-impact-map.md
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# File Impact Map Template
|
||||||
|
|
||||||
|
Используй для плана или ревью, когда нужно заранее показать, какие файлы будут затронуты.
|
||||||
|
|
||||||
|
| Зона | Файлы | Что будет сделано | Почему это нужно | Риск |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Frontend API | `src/api/tauriCommands.ts` | | | Low/Medium/High |
|
||||||
|
| Frontend UI | `src/app/...` | | | Low/Medium/High |
|
||||||
|
| Backend command | `src-tauri/src/...` | | | Low/Medium/High |
|
||||||
|
| Storage/config | `src-tauri/src/storage.rs` | | | Low/Medium/High |
|
||||||
|
| Windows/elevation | `scripts/*.ps1` | | | Low/Medium/High |
|
||||||
|
| Docs/agent | `.agent/...` | | | Low/Medium/High |
|
||||||
|
|
||||||
|
## Что не трогаем
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Как проверить после изменений
|
||||||
|
|
||||||
|
-
|
||||||
27
.agent/templates/investigation-report.md
Normal file
27
.agent/templates/investigation-report.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# Investigation Report
|
||||||
|
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
- Главный вывод:
|
||||||
|
- Где проблема:
|
||||||
|
- Что делать первым:
|
||||||
|
|
||||||
|
## Что смотрел
|
||||||
|
|
||||||
|
| Файл / зона | Зачем смотрел | Вывод |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | | |
|
||||||
|
|
||||||
|
## Находки
|
||||||
|
|
||||||
|
| Приоритет | Где | Что не так | Как исправить |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Критично / Важно / Можно потом / Косметика | `path/file` | | |
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Ограничения анализа
|
||||||
|
|
||||||
|
-
|
||||||
32
.agent/templates/pr-description.md
Normal file
32
.agent/templates/pr-description.md
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
## Коротко
|
||||||
|
|
||||||
|
-
|
||||||
|
-
|
||||||
|
-
|
||||||
|
|
||||||
|
## Файлы / зоны
|
||||||
|
|
||||||
|
| Файл / зона | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | | |
|
||||||
|
|
||||||
|
## Пользовательское поведение
|
||||||
|
|
||||||
|
- Что пользователь увидит:
|
||||||
|
- Что не должно измениться:
|
||||||
|
|
||||||
|
## Технические детали
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
- [ ] `npm run build`
|
||||||
|
- [ ] `cargo fmt --all -- --check`
|
||||||
|
- [ ] `cargo clippy --all-targets --all-features -- -D warnings`
|
||||||
|
- [ ] `cargo test --all-targets`
|
||||||
|
- [ ] Windows manual smoke, если затронуты service/elevation/install/routing
|
||||||
|
|
||||||
|
## Не проверено / риски
|
||||||
|
|
||||||
|
-
|
||||||
27
.agent/templates/user-facing-summary.md
Normal file
27
.agent/templates/user-facing-summary.md
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# User-facing Summary
|
||||||
|
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
-
|
||||||
|
-
|
||||||
|
-
|
||||||
|
|
||||||
|
## Что изменилось простыми словами
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Файлы
|
||||||
|
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | | |
|
||||||
|
|
||||||
|
## Что важно знать
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Проверки и риски
|
||||||
|
|
||||||
|
- ✅ Проверено:
|
||||||
|
- ⚠️ Не проверено:
|
||||||
|
- Риск:
|
||||||
23
.agent/templates/work-plan.md
Normal file
23
.agent/templates/work-plan.md
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# Work Plan
|
||||||
|
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
Сделаю так:
|
||||||
|
|
||||||
|
1.
|
||||||
|
2.
|
||||||
|
3.
|
||||||
|
|
||||||
|
## Какие файлы, вероятно, затрону
|
||||||
|
|
||||||
|
| Файл / зона | Что планируется | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | | |
|
||||||
|
|
||||||
|
## Что проверю
|
||||||
|
|
||||||
|
-
|
||||||
|
|
||||||
|
## Что может остаться непроверенным
|
||||||
|
|
||||||
|
-
|
||||||
32
.cursor/rules/proxywarden.mdc
Normal file
32
.cursor/rules/proxywarden.mdc
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
description: ProxyWarden repository rules for Cursor agents
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# ProxyWarden Cursor Rules
|
||||||
|
|
||||||
|
Read `AGENTS.md` before editing. Use `.agent/skills/*/SKILL.md` for task-specific guidance.
|
||||||
|
|
||||||
|
## Core rules
|
||||||
|
|
||||||
|
- Keep ProxyWarden a standalone Windows desktop utility: Tauri 2 + React/TypeScript + Rust.
|
||||||
|
- Preserve separation between Control App, ProxiFyre and Local sing-box.
|
||||||
|
- External SOCKS5 route must work without sing-box.
|
||||||
|
- UI must call backend through `src/api/tauriCommands.ts`, not direct random `invoke(...)` calls.
|
||||||
|
- Backend must validate all inputs even if UI validates them.
|
||||||
|
- Do not leak subscription URLs, proxy credentials or outbound secrets.
|
||||||
|
- Keep install/start/stop/uninstall explicit.
|
||||||
|
- Do not relax safe deletion or elevated script rules.
|
||||||
|
- Prefer shrinking `src-tauri/src/commands.rs` and `src/app/App.tsx` over adding more logic there.
|
||||||
|
- Run relevant checks and state unverified Windows/elevation behavior honestly.
|
||||||
|
|
||||||
|
## Communication rules
|
||||||
|
|
||||||
|
Before non-trivial answers, follow `.agent/skills/communication-reporting/SKILL.md` and `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
- Write final answers in short, structured Russian unless the user asks otherwise.
|
||||||
|
- Start with `Коротко` for nontrivial work.
|
||||||
|
- For 2+ files, use a table with `Файл / Что изменилось / Зачем`.
|
||||||
|
- Do not dump every diff line. Mention important functions/sections only.
|
||||||
|
- Clearly split `Проверено` and `Не проверено`.
|
||||||
|
- Do not claim Windows/UAC/service checks were done unless they actually ran.
|
||||||
26
.github/copilot-instructions.md
vendored
Normal file
26
.github/copilot-instructions.md
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Copilot Instructions for ProxyWarden
|
||||||
|
|
||||||
|
Read `AGENTS.md` first. Follow the repo invariants there.
|
||||||
|
|
||||||
|
## Key reminders
|
||||||
|
|
||||||
|
- This is a standalone Windows Tauri 2 + React/TypeScript + Rust app.
|
||||||
|
- Do not turn it into a SaaS, gateway, server or cloud control plane.
|
||||||
|
- Do not call `invoke(...)` outside `src/api/tauriCommands.ts`.
|
||||||
|
- Do not make Local sing-box required for external SOCKS5 routing.
|
||||||
|
- Do not hide install/start/stop/uninstall behind apply.
|
||||||
|
- Do not log or display full subscription URLs, proxy credentials or outbound secrets.
|
||||||
|
- Keep Tauri capabilities minimal and CSP enabled.
|
||||||
|
- Treat `commands.rs` and `App.tsx` as large legacy orchestration files that should shrink over time.
|
||||||
|
- For security-sensitive changes, read `.agent/skills/security-hardening/SKILL.md`.
|
||||||
|
- For Windows service/elevation changes, read `.agent/skills/windows-services-powershell/SKILL.md`.
|
||||||
|
|
||||||
|
## Reporting style
|
||||||
|
|
||||||
|
Before non-trivial answers, follow `.agent/skills/communication-reporting/SKILL.md` and `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
- Start with `Коротко`: 2-4 main points.
|
||||||
|
- For code changes, include a `Файл / Что изменилось / Зачем` table.
|
||||||
|
- Explain only important behavior, safety, UX and risk points. Do not retell every line.
|
||||||
|
- Split checks into `Проверено` and `Не проверено`.
|
||||||
|
- State unverified Windows/UAC/service behavior honestly.
|
||||||
60
.github/workflows/ci.yml
vendored
Normal file
60
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["**"]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
windows-baseline:
|
||||||
|
name: Windows baseline
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
|
||||||
|
- name: Set up Rust toolchain
|
||||||
|
run: rustup show
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
|
- name: Run frontend tests
|
||||||
|
run: npm test -- --run
|
||||||
|
|
||||||
|
- name: Build frontend
|
||||||
|
run: npm run build
|
||||||
|
|
||||||
|
- name: Check Rust formatting
|
||||||
|
working-directory: src-tauri
|
||||||
|
run: cargo fmt --all -- --check
|
||||||
|
|
||||||
|
- name: Run Rust lints
|
||||||
|
working-directory: src-tauri
|
||||||
|
run: cargo clippy --all-targets --all-features -- -D warnings
|
||||||
|
|
||||||
|
- name: Run Rust tests
|
||||||
|
working-directory: src-tauri
|
||||||
|
run: cargo test --all-targets
|
||||||
|
|
||||||
|
- name: Check Tauri environment
|
||||||
|
run: npm run tauri -- info
|
||||||
|
|
||||||
|
- name: Plan control app installer
|
||||||
|
shell: pwsh
|
||||||
|
run: .\scripts\install-control-app.ps1 -PlanOnly
|
||||||
|
|
||||||
|
- name: Plan ProxiFyre installer
|
||||||
|
shell: pwsh
|
||||||
|
run: .\scripts\install-proxyfier.ps1 -PlanOnly
|
||||||
|
|
||||||
|
- name: Plan sing-box installer
|
||||||
|
shell: pwsh
|
||||||
|
run: .\scripts\install-singbox.ps1 -PlanOnly
|
||||||
249
AGENTS.md
249
AGENTS.md
@@ -1,72 +1,198 @@
|
|||||||
# Инструкции для агентов
|
# AGENTS.md
|
||||||
|
|
||||||
## Контекст проекта
|
## Назначение
|
||||||
|
|
||||||
ProxyWarden - standalone Windows desktop client в корне репозитория. Это Tauri 2 + React/TypeScript UI + Rust backend для маршрутизации выбранных Windows-приложений через внешний SOCKS5-прокси или опциональный Local sing-box.
|
ProxyWarden — standalone Windows desktop-приложение для удобного per-app proxy routing. Стек: Tauri 2, Rust backend, React/TypeScript frontend, Vite, PowerShell installer/control scripts. Приложение управляет выбранными Windows-приложениями через ProxiFyre и, опционально, через локальный sing-box runtime.
|
||||||
|
|
||||||
Не возвращать старую идею `APP_MODE=windows` и не подключать Windows-клиент к отдельному Node gateway/server. Текущий рабочий путь - `src`, `src-tauri`, `scripts` в корне репозитория.
|
Этот файл — главный контракт для кодового агента. Любой агент, который меняет репозиторий, обязан соблюдать эти правила. Да, даже если ему очень хочется «быстренько поправить одну кнопочку» и случайно переписать половину сетевого стека. Особенно тогда.
|
||||||
|
|
||||||
## Основные инварианты
|
## Продуктовая рамка
|
||||||
|
|
||||||
- Три компонента должны оставаться разделенными: Control App, ProxiFyre, Local sing-box.
|
Проект не должен превращаться в коммерческий SaaS, Node gateway, VPN-провайдер, proxy server или облачный control plane. Это локальная Windows-утилита для себя и друзей.
|
||||||
- ProxiFyre - обязательный слой для per-app routing; Local sing-box - необязательный runtime.
|
|
||||||
- Внешний SOCKS5 flow должен работать без установленного Local sing-box.
|
Цель: надежно и понятно конфигурировать маршрутизацию выбранных приложений через внешний SOCKS5 proxy или через локальный sing-box, не ломая системную сеть и не пряча опасные действия за безобидными кнопками.
|
||||||
- Profile apply не должен скрыто устанавливать, удалять, запускать или чинить компоненты. Install/start/stop/uninstall - только явные действия пользователя.
|
|
||||||
- Source of truth - JSON под `C:\ProgramData\ProxyWarden\config` и `state`.
|
## Архитектурные инварианты
|
||||||
- `C:\ProgramData\ProxyWarden\generated\proxifyre-app-config.json` и `sing-box-config.json` - derived artifacts, их можно пересоздать.
|
|
||||||
- Subscription URL и другие секреты нельзя показывать полностью в UI, diagnostics или логах.
|
- Control App, ProxiFyre и Local sing-box — разные компоненты. Не смешивать их ответственность.
|
||||||
- Summary panel должен оставаться read-only: без apply/install/start/stop/delete/input/subscription mutations.
|
- ProxiFyre — обязательный слой для per-app routing.
|
||||||
|
- Local sing-box — optional runtime. Внешний SOCKS5 flow обязан работать без sing-box.
|
||||||
|
- React UI не пишет generated config напрямую. UI вызывает typed Tauri commands.
|
||||||
|
- `src/api/tauriCommands.ts` — единственная TypeScript-обертка над `invoke(...)`.
|
||||||
|
- Rust backend отвечает за storage, validation, config generation, component detection, service/install orchestration и structured errors.
|
||||||
|
- `C:\ProgramData\ProxyWarden\config` и `C:\ProgramData\ProxyWarden\state` — source of truth.
|
||||||
|
- `C:\ProgramData\ProxyWarden\generated\proxifyre-app-config.json` и `sing-box-config.json` — derived artifacts. Их можно пересоздавать.
|
||||||
|
- Install/start/stop/uninstall — только явные действия пользователя. `apply` не должен скрыто устанавливать, удалять или «чинить» компоненты.
|
||||||
|
- Subscription URL, credentials, proxy passwords и userinfo нельзя выводить полностью в UI, logs, diagnostics, crash text или activity.
|
||||||
|
- Summary panel должен оставаться read-only: без install/start/stop/apply/delete/input/subscription mutations.
|
||||||
|
- Любые elevated операции должны быть максимально явными и проверяемыми.
|
||||||
|
|
||||||
|
## Основная структура
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/
|
||||||
|
api/tauriCommands.ts # typed invoke facade
|
||||||
|
app/App.tsx # текущая UI orchestration зона, слишком крупная
|
||||||
|
app/readiness.ts # apply gating logic
|
||||||
|
app/viewModel.ts # display/view helpers
|
||||||
|
domain/types.ts # TypeScript DTO mirror
|
||||||
|
ui/* # reusable presentational components
|
||||||
|
styles/app.css # основной CSS
|
||||||
|
|
||||||
|
src-tauri/
|
||||||
|
tauri.conf.json # Tauri config, security, window config
|
||||||
|
capabilities/default.json # Tauri permissions/capabilities
|
||||||
|
src/models.rs # Rust domain models/defaults
|
||||||
|
src/validation.rs # normalization/validation
|
||||||
|
src/storage.rs # JSON storage, tmp/bak writes
|
||||||
|
src/activity.rs # activity log
|
||||||
|
src/subscription.rs # subscription fetch/parse
|
||||||
|
src/component_detection.rs # ProxiFyre/sing-box detection
|
||||||
|
src/singbox_service.rs # sing-box Windows service logic
|
||||||
|
src/process.rs # process/system helpers
|
||||||
|
src/helper.rs # helper/elevation boundary
|
||||||
|
src/adapters/* # ProxiFyre/sing-box/proxy-router adapters
|
||||||
|
src/commands.rs # Tauri command handlers; currently too large
|
||||||
|
tests/* # Rust integration/domain tests
|
||||||
|
|
||||||
|
scripts/
|
||||||
|
install-control-app.ps1
|
||||||
|
install-proxyfier.ps1
|
||||||
|
install-singbox.ps1
|
||||||
|
prepare-release.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
## Агентские skill-модули
|
||||||
|
|
||||||
|
Подробные инструкции лежат в `.agent/skills`:
|
||||||
|
|
||||||
|
- `.agent/skills/repository-orientation/SKILL.md` — как быстро понять репозиторий.
|
||||||
|
- `.agent/skills/rust-tauri-backend/SKILL.md` — Rust/Tauri backend changes.
|
||||||
|
- `.agent/skills/react-typescript-ui/SKILL.md` — frontend/UI changes.
|
||||||
|
- `.agent/skills/security-hardening/SKILL.md` — CSP, секреты, temp files, storage, SSRF, elevated boundary.
|
||||||
|
- `.agent/skills/windows-services-powershell/SKILL.md` — Windows service/install/PowerShell изменения.
|
||||||
|
- `.agent/skills/subscriptions-routing/SKILL.md` — subscription, sing-box, ProxiFyre routing.
|
||||||
|
- `.agent/skills/testing-ci-release/SKILL.md` — проверки, CI, release hygiene.
|
||||||
|
- `.agent/skills/communication-reporting/SKILL.md` — короткие понятные планы, ревью и отчеты с таблицами файлов.
|
||||||
|
|
||||||
|
Перед сложным изменением прочитать релевантный skill. Перед любым нетривиальным ответом владельцу проекта — прочитать `communication-reporting`. Да, инструкция про то, как не писать кашу, теперь тоже инструкция. Так мы и живем.
|
||||||
|
|
||||||
|
## Стиль общения агента
|
||||||
|
|
||||||
|
Пользователь — разработчик, но ему не нужен роман о каждом `match`, `useState` и переименованном импорте. Писать надо как для человека, которому нужно быстро принять решение: что изменилось, где изменилось, зачем и что проверить.
|
||||||
|
|
||||||
|
Перед любым нетривиальным ответом прочитать `.agent/skills/communication-reporting/SKILL.md` и перед финальным сообщением пройти `.agent/checklists/communication.md`.
|
||||||
|
|
||||||
|
### Обязательные правила
|
||||||
|
|
||||||
|
- Сначала результат, потом детали.
|
||||||
|
- Короткие абзацы, списки и таблицы вместо полотна текста.
|
||||||
|
- Для нетривиальных изменений использовать таблицу `Файл / Что изменилось / Зачем`.
|
||||||
|
- Не объяснять каждую строку. Объяснять важные места, решения, риски и поведение.
|
||||||
|
- Технические термины использовать только когда они помогают. Сложный термин объяснять одной простой фразой.
|
||||||
|
- Проверки делить на выполненные, не выполненные и требующие Windows/manual check.
|
||||||
|
- Для ревью группировать находки по приоритетам: `Критично`, `Важно`, `Можно потом`, `Косметика`.
|
||||||
|
- Не писать корпоративный туман вроде «улучшена архитектура» без указания, что именно стало проще, безопаснее или понятнее.
|
||||||
|
- Не заявлять “всё проверено”, если Rust tests, Windows service flow, Tauri build или UAC сценарии не запускались.
|
||||||
|
|
||||||
|
### Минимальный формат финального ответа
|
||||||
|
|
||||||
|
```md
|
||||||
|
## Коротко
|
||||||
|
|
||||||
|
- 1-3 главных результата.
|
||||||
|
|
||||||
|
## Файлы
|
||||||
|
|
||||||
|
| Файл | Что изменилось | Зачем |
|
||||||
|
|---|---|---|
|
||||||
|
| `path/file` | простое описание | практическая причина |
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
| Проверка | Статус | Комментарий |
|
||||||
|
|---|---|---|
|
||||||
|
| `command` | выполнено / не выполнено | почему |
|
||||||
|
|
||||||
|
## Риски
|
||||||
|
|
||||||
|
- Что осталось проверить или почему риска нет.
|
||||||
|
```
|
||||||
|
|
||||||
|
Если задача маленькая, формат можно сжать до нескольких строк. Если задача security/service/storage/routing-sensitive, детали обязательны, потому что «ну вроде работает» — это не инженерный метод, а жанр народного фольклора.
|
||||||
|
|
||||||
## Структура
|
|
||||||
|
|
||||||
- `src/app/App.tsx` - основная React-оркестрация, вкладки `Сводка`, `ProxiFyre`, `VPN / Прокси`, вызовы Tauri-команд и transient UI state.
|
|
||||||
- `src/app/readiness.ts` - gating применимости маршрута. Не обходить его локальными проверками в JSX.
|
|
||||||
- `src/app/viewModel.ts` - маленькие display/view-model helpers.
|
|
||||||
- `src/ui/*` - общие presentational-компоненты. Для новых кнопок, вкладок, service rows, pills, полей и лог-дока сначала расширять эти компоненты.
|
|
||||||
- `src/api/tauriCommands.ts` - единственная TypeScript-обертка над `invoke(...)`; держать DTO в синхронизации с Rust.
|
|
||||||
- `src/domain/types.ts` - TypeScript-зеркало доменных DTO.
|
|
||||||
- `src-tauri/src/models.rs` - Rust-модели и default values.
|
|
||||||
- `src-tauri/src/validation.rs` - нормализация входов.
|
|
||||||
- `src-tauri/src/storage.rs` и `activity.rs` - JSON storage, backup/tmp writes, activity cap/sort.
|
|
||||||
- `src-tauri/src/adapters/proxy_router.rs` - adapter boundary для proxy-router.
|
|
||||||
- `src-tauri/src/adapters/proxifyre.rs` - первый adapter, генерирует ProxiFyre `app-config.json`.
|
|
||||||
- `src-tauri/src/adapters/singbox.rs` - генерация локального `sing-box` конфига из subscription cache и выбранного сервера.
|
|
||||||
- `src-tauri/src/component_detection.rs` - detection ProxiFyre/Proxifier/Local sing-box.
|
|
||||||
- `src-tauri/src/commands.rs` - Tauri command handlers, installer/service orchestration, structured errors.
|
|
||||||
- `src-tauri/src/main.rs` - реальная Tauri entrypoint-регистрация команд.
|
|
||||||
- `src-tauri/src/lib.rs` сейчас scaffold/stale; не считать его источником регистрации команд без отдельной cleanup-задачи.
|
|
||||||
- `scripts/*.ps1` - явные installer entrypoints. `-PlanOnly` должен возвращать structured JSON без side effects.
|
|
||||||
|
|
||||||
## Правила изменений
|
## Правила изменений
|
||||||
|
|
||||||
- Не создавать второй источник правды для профилей, targets, components, subscription или activity.
|
### Backend
|
||||||
- Не писать generated config напрямую из React.
|
|
||||||
- Не парсить raw PowerShell/stdout в UI. Backend/helper boundary должен возвращать structured JSON/error DTO.
|
|
||||||
- Не привязывать UI напрямую к деталям ProxiFyre, если изменение относится к общему proxy-router поведению.
|
|
||||||
- Не делать Local sing-box обязательным для external target.
|
|
||||||
- Для service/install операций сохранять UAC/admin boundary и человекочитаемые ошибки.
|
|
||||||
- При удалении install folders сохранять safe-path checks; не ослаблять рекурсивное удаление.
|
|
||||||
- В UI держать стиль компактной Windows-утилиты, а не landing/dashboard. Использовать existing `Button`, `Tabs`, `ServiceControlRow`, `StatusPill`, `Field`, `ActionMenu`, `LogDock`.
|
|
||||||
- Всплывающие подсказки при наведении делать быстрыми, кастомными и читаемыми: темная compact-плашка с мягкой рамкой/тенью, появление ~120ms, без нативного browser `title` как основного UI. Для иконок расширять общий `IconButton`/tooltip-паттерн, а не дублировать JSX/CSS локально.
|
|
||||||
- Apply actions должны быть disabled с объяснением, когда нет приложений, ProxiFyre отсутствует, proxy input неверный или local route не готов.
|
|
||||||
- Не оставлять dev-серверы (`npm run dev`, `npm run tauri -- dev`, preview-серверы) запущенными после проверки. Если сервер был поднят агентом, остановить его перед финальным ответом.
|
|
||||||
|
|
||||||
## Проверка
|
- Не добавлять новую Tauri command без typed wrapper в `src/api/tauriCommands.ts` и соответствующего TypeScript DTO в `src/domain/types.ts`, если command используется UI.
|
||||||
|
- Не возвращать raw strings для сложных ошибок. Использовать structured error DTO: `code`, `message`, `details`.
|
||||||
|
- Тяжелые или блокирующие операции должны быть `async` command + `tauri::async_runtime::spawn_blocking`.
|
||||||
|
- Не вызывать network/process/service/file-heavy logic прямо из async runtime thread.
|
||||||
|
- Не использовать `unwrap()`/`expect()` в production path, кроме очевидно невозможных bootstrap cases с комментарием.
|
||||||
|
- Не писать generated configs неатомарно. Использовать temp + backup + rename where practical.
|
||||||
|
- Не расширять `commands.rs` без необходимости. Для новой логики предпочитать отдельные модули и thin command wrapper.
|
||||||
|
|
||||||
Минимум для frontend/UI:
|
### Frontend
|
||||||
|
|
||||||
|
- Не увеличивать `App.tsx`, если можно вынести hook/helper/component.
|
||||||
|
- Не вызывать `invoke(...)` напрямую вне `src/api/tauriCommands.ts`.
|
||||||
|
- Не дублировать apply-readiness проверки в JSX. Расширять `src/app/readiness.ts`.
|
||||||
|
- Для UI использовать существующие компоненты из `src/ui`.
|
||||||
|
- Apply/start/install/delete buttons должны иметь disabled state и понятную причину.
|
||||||
|
- Не показывать secrets. Для subscription/proxy URL использовать redacted display values.
|
||||||
|
- UI должен оставаться compact Windows utility, а не SaaS dashboard с иллюзией корпоративной важности.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- Не отключать CSP. Если CSP мешает, исправлять source policy, а не ставить `csp: null`.
|
||||||
|
- Не добавлять Tauri shell permissions без жесткого scope и отдельного обоснования.
|
||||||
|
- Не запускать произвольные команды из UI input.
|
||||||
|
- Runtime-generated elevated scripts должны использовать непредсказуемые имена, safe directory/ACL и cleanup best-effort.
|
||||||
|
- Удаление директорий допускается только после safe-path/marker/service-path checks.
|
||||||
|
- Subscription fetch должен иметь timeout и защиту от очевидно опасных/local metadata адресов либо explicit allow-mode.
|
||||||
|
|
||||||
|
### Windows/service boundary
|
||||||
|
|
||||||
|
- `-PlanOnly` у PowerShell scripts должен оставаться side-effect-free и возвращать structured JSON.
|
||||||
|
- Install/start/stop/uninstall должны быть явными user actions.
|
||||||
|
- Fuzzy-detected service не считать managed service без проверки `PathName`/metadata.
|
||||||
|
- В Linux/macOS CI не пытаться «проверить» Windows service operations как реальные. Тестировать pure logic/mocks.
|
||||||
|
|
||||||
|
## Известный технический долг
|
||||||
|
|
||||||
|
- `src-tauri/src/commands.rs` слишком большой. Главная цель рефакторинга: разрезать на модули по use-case.
|
||||||
|
- `src/app/App.tsx` слишком большой. Главная цель frontend-рефакторинга: hooks/components/view-model helpers.
|
||||||
|
- `tauri.conf.json` сейчас требует security review, особенно CSP и window resize settings.
|
||||||
|
- JSON storage молча возвращает default при invalid JSON. Нужен corruption recovery через `.bak` и user-visible warning.
|
||||||
|
- ProxiFyre config apply должен стать atomic.
|
||||||
|
- Subscription URL redaction должен исключать userinfo/password.
|
||||||
|
- Link subscription parser сейчас ориентирован на VLESS; не обещать больше, чем реально поддерживается.
|
||||||
|
- Ping/select по server tag может ломаться при duplicate tags. Нужен stable server id.
|
||||||
|
|
||||||
|
## Минимальная проверка перед ответом
|
||||||
|
|
||||||
|
Для docs-only изменений достаточно проверить структуру файлов и отсутствие очевидных Markdown/JSON ошибок.
|
||||||
|
|
||||||
|
Для frontend изменений:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
|
npm ci
|
||||||
npm run build
|
npm run build
|
||||||
```
|
```
|
||||||
|
|
||||||
Rust/backend:
|
Для Rust/backend изменений:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
cd D:\repos\ProxyWarden\src-tauri
|
cd src-tauri
|
||||||
cargo test
|
cargo fmt --all -- --check
|
||||||
|
cargo clippy --all-targets --all-features -- -D warnings
|
||||||
|
cargo test --all-targets
|
||||||
```
|
```
|
||||||
|
|
||||||
Tauri/toolchain:
|
Для Tauri/toolchain:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
npm run tauri -- info
|
npm run tauri -- info
|
||||||
@@ -74,7 +200,7 @@ npm run tauri -- dev
|
|||||||
npm run tauri -- build
|
npm run tauri -- build
|
||||||
```
|
```
|
||||||
|
|
||||||
Installer boundaries:
|
Для installer boundaries:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
& .\scripts\install-control-app.ps1 -PlanOnly
|
& .\scripts\install-control-app.ps1 -PlanOnly
|
||||||
@@ -82,10 +208,25 @@ Installer boundaries:
|
|||||||
& .\scripts\install-singbox.ps1 -PlanOnly
|
& .\scripts\install-singbox.ps1 -PlanOnly
|
||||||
```
|
```
|
||||||
|
|
||||||
Для UI-изменений проверять browser-preview на desktop и narrow viewport. Browser-preview не доказывает native Tauri commands или elevated service lane.
|
Не оставлять dev/preview/Tauri dev servers запущенными после проверки.
|
||||||
|
|
||||||
## Известные риски
|
## Формат отчета агента
|
||||||
|
|
||||||
- Реальные elevated install/start/stop/uninstall операции для ProxiFyre и Local sing-box считаются `implemented but unproven`, пока они не проверены на Windows с UAC/admin confirmation.
|
Использовать один из шаблонов:
|
||||||
- Исторические planning/evidence файлы лежат в ignored `docs`-папках и не должны попадать в коммиты.
|
|
||||||
- Старые документы могут ссылаться на `apps/windows-client`; текущая структура репозитория - standalone client в корне.
|
- `.agent/templates/work-plan.md` — короткий план перед работой.
|
||||||
|
- `.agent/templates/change-report.md` — отчет после изменения кода.
|
||||||
|
- `.agent/templates/investigation-report.md` — аудит, расследование, разбор проблемы.
|
||||||
|
- `.agent/templates/user-facing-summary.md` — краткая сводка для владельца проекта.
|
||||||
|
- `.agent/templates/pr-description.md` — описание PR.
|
||||||
|
|
||||||
|
Каждый нетривиальный ответ должен отвечать на вопросы:
|
||||||
|
|
||||||
|
1. Что поменялось или найдено?
|
||||||
|
2. В каких файлах?
|
||||||
|
3. Зачем это нужно?
|
||||||
|
4. Что проверено?
|
||||||
|
5. Что не проверено?
|
||||||
|
6. Где остался риск?
|
||||||
|
|
||||||
|
Не писать «всё готово», если Windows/elevated/service flow не проверялся на Windows. Эта фраза и так слишком много навредила миру.
|
||||||
|
|||||||
60
docs/agent/ARCHITECTURE-NOTES.md
Normal file
60
docs/agent/ARCHITECTURE-NOTES.md
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
# ProxyWarden Architecture Notes for Agents
|
||||||
|
|
||||||
|
## Current design
|
||||||
|
|
||||||
|
ProxyWarden is a local Windows control app. It does not proxy traffic by itself. It orchestrates:
|
||||||
|
|
||||||
|
1. ProxiFyre for per-app routing.
|
||||||
|
2. Optional local sing-box for subscription-based outbound routing.
|
||||||
|
3. External SOCKS5 target for direct proxy routing.
|
||||||
|
|
||||||
|
## Route modes
|
||||||
|
|
||||||
|
External SOCKS5:
|
||||||
|
|
||||||
|
```text
|
||||||
|
selected Windows apps -> ProxiFyre -> external SOCKS5
|
||||||
|
```
|
||||||
|
|
||||||
|
Local sing-box:
|
||||||
|
|
||||||
|
```text
|
||||||
|
selected Windows apps -> ProxiFyre -> 127.0.0.1:1080 -> sing-box selected outbound
|
||||||
|
```
|
||||||
|
|
||||||
|
## Main risks
|
||||||
|
|
||||||
|
- Large orchestration files: `commands.rs` and `App.tsx`.
|
||||||
|
- Security-sensitive elevated operations.
|
||||||
|
- Secrets in subscription/proxy config.
|
||||||
|
- Non-atomic writes to generated configs.
|
||||||
|
- Stale component status.
|
||||||
|
- Duplicate sing-box server tags.
|
||||||
|
- UI/business logic entanglement.
|
||||||
|
|
||||||
|
## Desired direction
|
||||||
|
|
||||||
|
Backend:
|
||||||
|
|
||||||
|
- Thin Tauri command handlers.
|
||||||
|
- Use-case modules.
|
||||||
|
- Testable pure functions.
|
||||||
|
- Structured errors.
|
||||||
|
- Atomic writes and hardened temp/elevation handling.
|
||||||
|
|
||||||
|
Frontend:
|
||||||
|
|
||||||
|
- Smaller `App.tsx`.
|
||||||
|
- Extracted hooks/components.
|
||||||
|
- Typed API boundary.
|
||||||
|
- Testable readiness/snapshot/proxy parsing logic.
|
||||||
|
- Clear UX for pending changes and service state.
|
||||||
|
|
||||||
|
Security:
|
||||||
|
|
||||||
|
- CSP enabled.
|
||||||
|
- Minimal Tauri capabilities.
|
||||||
|
- No broad shell permission.
|
||||||
|
- Redacted secrets.
|
||||||
|
- Safe deletion.
|
||||||
|
- Explicit Windows service control.
|
||||||
456
package-lock.json
generated
456
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "proxywarden",
|
"name": "proxywarden",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "proxywarden",
|
"name": "proxywarden",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fontsource-variable/jetbrains-mono": "^5.2.8",
|
"@fontsource-variable/jetbrains-mono": "^5.2.8",
|
||||||
"@tauri-apps/api": "^2.0.0",
|
"@tauri-apps/api": "^2.0.0",
|
||||||
@@ -21,7 +21,8 @@
|
|||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
"typescript": "^5.8.0",
|
"typescript": "^5.8.0",
|
||||||
"vite": "^7.0.0"
|
"vite": "^7.0.0",
|
||||||
|
"vitest": "^3.2.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame": {
|
"node_modules/@babel/code-frame": {
|
||||||
@@ -1499,6 +1500,24 @@
|
|||||||
"@babel/types": "^7.28.2"
|
"@babel/types": "^7.28.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/chai": {
|
||||||
|
"version": "5.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
|
||||||
|
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/deep-eql": "*",
|
||||||
|
"assertion-error": "^2.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/deep-eql": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/estree": {
|
"node_modules/@types/estree": {
|
||||||
"version": "1.0.9",
|
"version": "1.0.9",
|
||||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
|
||||||
@@ -1547,6 +1566,131 @@
|
|||||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
|
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@vitest/expect": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/chai": "^5.2.2",
|
||||||
|
"@vitest/spy": "3.2.7",
|
||||||
|
"@vitest/utils": "3.2.7",
|
||||||
|
"chai": "^5.2.0",
|
||||||
|
"tinyrainbow": "^2.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/mocker": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@vitest/spy": "3.2.7",
|
||||||
|
"estree-walker": "^3.0.3",
|
||||||
|
"magic-string": "^0.30.17"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"msw": "^2.4.9",
|
||||||
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"msw": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"vite": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/pretty-format": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tinyrainbow": "^2.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/runner": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@vitest/utils": "3.2.7",
|
||||||
|
"pathe": "^2.0.3",
|
||||||
|
"strip-literal": "^3.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/snapshot": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@vitest/pretty-format": "3.2.7",
|
||||||
|
"magic-string": "^0.30.17",
|
||||||
|
"pathe": "^2.0.3"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/spy": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tinyspy": "^4.0.3"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@vitest/utils": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@vitest/pretty-format": "3.2.7",
|
||||||
|
"loupe": "^3.1.4",
|
||||||
|
"tinyrainbow": "^2.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/assertion-error": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/baseline-browser-mapping": {
|
"node_modules/baseline-browser-mapping": {
|
||||||
"version": "2.10.41",
|
"version": "2.10.41",
|
||||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.41.tgz",
|
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.41.tgz",
|
||||||
@@ -1594,6 +1738,16 @@
|
|||||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/cac": {
|
||||||
|
"version": "6.7.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
|
||||||
|
"integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/caniuse-lite": {
|
"node_modules/caniuse-lite": {
|
||||||
"version": "1.0.30001800",
|
"version": "1.0.30001800",
|
||||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001800.tgz",
|
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001800.tgz",
|
||||||
@@ -1615,6 +1769,33 @@
|
|||||||
],
|
],
|
||||||
"license": "CC-BY-4.0"
|
"license": "CC-BY-4.0"
|
||||||
},
|
},
|
||||||
|
"node_modules/chai": {
|
||||||
|
"version": "5.3.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
|
||||||
|
"integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"assertion-error": "^2.0.1",
|
||||||
|
"check-error": "^2.1.1",
|
||||||
|
"deep-eql": "^5.0.1",
|
||||||
|
"loupe": "^3.1.0",
|
||||||
|
"pathval": "^2.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/check-error": {
|
||||||
|
"version": "2.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
|
||||||
|
"integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 16"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/convert-source-map": {
|
"node_modules/convert-source-map": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||||
@@ -1647,6 +1828,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/deep-eql": {
|
||||||
|
"version": "5.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
|
||||||
|
"integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/electron-to-chromium": {
|
"node_modules/electron-to-chromium": {
|
||||||
"version": "1.5.385",
|
"version": "1.5.385",
|
||||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.385.tgz",
|
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.385.tgz",
|
||||||
@@ -1654,6 +1845,13 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/es-module-lexer": {
|
||||||
|
"version": "1.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
|
||||||
|
"integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/esbuild": {
|
"node_modules/esbuild": {
|
||||||
"version": "0.28.1",
|
"version": "0.28.1",
|
||||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
|
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
|
||||||
@@ -1706,6 +1904,26 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/estree-walker": {
|
||||||
|
"version": "3.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
|
||||||
|
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/estree": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/expect-type": {
|
||||||
|
"version": "1.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||||
|
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/fdir": {
|
"node_modules/fdir": {
|
||||||
"version": "6.5.0",
|
"version": "6.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||||
@@ -1782,6 +2000,13 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/loupe": {
|
||||||
|
"version": "3.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
|
||||||
|
"integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/lru-cache": {
|
"node_modules/lru-cache": {
|
||||||
"version": "5.1.1",
|
"version": "5.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
|
||||||
@@ -1801,6 +2026,16 @@
|
|||||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/magic-string": {
|
||||||
|
"version": "0.30.21",
|
||||||
|
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||||
|
"integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/sourcemap-codec": "^1.5.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/ms": {
|
"node_modules/ms": {
|
||||||
"version": "2.1.3",
|
"version": "2.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||||
@@ -1837,6 +2072,23 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/pathe": {
|
||||||
|
"version": "2.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
||||||
|
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pathval": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 14.16"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/picocolors": {
|
"node_modules/picocolors": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||||
@@ -1978,6 +2230,13 @@
|
|||||||
"semver": "bin/semver.js"
|
"semver": "bin/semver.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/siginfo": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
"node_modules/source-map-js": {
|
"node_modules/source-map-js": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||||
@@ -1988,6 +2247,54 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/stackback": {
|
||||||
|
"version": "0.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
|
||||||
|
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/std-env": {
|
||||||
|
"version": "3.10.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
|
||||||
|
"integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/strip-literal": {
|
||||||
|
"version": "3.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",
|
||||||
|
"integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"js-tokens": "^9.0.1"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/antfu"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/strip-literal/node_modules/js-tokens": {
|
||||||
|
"version": "9.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
|
||||||
|
"integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/tinybench": {
|
||||||
|
"version": "2.9.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||||
|
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/tinyexec": {
|
||||||
|
"version": "0.3.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
|
||||||
|
"integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/tinyglobby": {
|
"node_modules/tinyglobby": {
|
||||||
"version": "0.2.17",
|
"version": "0.2.17",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||||
@@ -2005,6 +2312,36 @@
|
|||||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tinypool": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.0.0 || >=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tinyrainbow": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/tinyspy": {
|
||||||
|
"version": "4.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
|
||||||
|
"integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/typescript": {
|
"node_modules/typescript": {
|
||||||
"version": "5.9.3",
|
"version": "5.9.3",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||||
@@ -2125,6 +2462,119 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/vite-node": {
|
||||||
|
"version": "3.2.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",
|
||||||
|
"integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cac": "^6.7.14",
|
||||||
|
"debug": "^4.4.1",
|
||||||
|
"es-module-lexer": "^1.7.0",
|
||||||
|
"pathe": "^2.0.3",
|
||||||
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"vite-node": "vite-node.mjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/vitest": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/chai": "^5.2.2",
|
||||||
|
"@vitest/expect": "3.2.7",
|
||||||
|
"@vitest/mocker": "3.2.7",
|
||||||
|
"@vitest/pretty-format": "^3.2.7",
|
||||||
|
"@vitest/runner": "3.2.7",
|
||||||
|
"@vitest/snapshot": "3.2.7",
|
||||||
|
"@vitest/spy": "3.2.7",
|
||||||
|
"@vitest/utils": "3.2.7",
|
||||||
|
"chai": "^5.2.0",
|
||||||
|
"debug": "^4.4.1",
|
||||||
|
"expect-type": "^1.2.1",
|
||||||
|
"magic-string": "^0.30.17",
|
||||||
|
"pathe": "^2.0.3",
|
||||||
|
"picomatch": "^4.0.2",
|
||||||
|
"std-env": "^3.9.0",
|
||||||
|
"tinybench": "^2.9.0",
|
||||||
|
"tinyexec": "^0.3.2",
|
||||||
|
"tinyglobby": "^0.2.14",
|
||||||
|
"tinypool": "^1.1.1",
|
||||||
|
"tinyrainbow": "^2.0.0",
|
||||||
|
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",
|
||||||
|
"vite-node": "3.2.4",
|
||||||
|
"why-is-node-running": "^2.3.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"vitest": "vitest.mjs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^18.0.0 || ^20.0.0 || >=22.0.0"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://opencollective.com/vitest"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@edge-runtime/vm": "*",
|
||||||
|
"@types/debug": "^4.1.12",
|
||||||
|
"@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
|
||||||
|
"@vitest/browser": "3.2.7",
|
||||||
|
"@vitest/ui": "3.2.7",
|
||||||
|
"happy-dom": "*",
|
||||||
|
"jsdom": "*"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@edge-runtime/vm": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/debug": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/node": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@vitest/browser": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@vitest/ui": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"happy-dom": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"jsdom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/why-is-node-running": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"siginfo": "^2.0.0",
|
||||||
|
"stackback": "0.0.2"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"why-is-node-running": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/yallist": {
|
"node_modules/yallist": {
|
||||||
"version": "3.1.1",
|
"version": "3.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "proxywarden",
|
"name": "proxywarden",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Standalone Windows desktop proxy management app for ProxyWarden.",
|
"description": "Standalone Windows desktop proxy management app for ProxyWarden.",
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc && vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
|
"test": "vitest",
|
||||||
"tauri": "tauri"
|
"tauri": "tauri"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -24,6 +25,7 @@
|
|||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
"@vitejs/plugin-react": "^5.0.0",
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
"typescript": "^5.8.0",
|
"typescript": "^5.8.0",
|
||||||
|
"vitest": "^3.2.4",
|
||||||
"vite": "^7.0.0"
|
"vite": "^7.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
3
rust-toolchain.toml
Normal file
3
rust-toolchain.toml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
[toolchain]
|
||||||
|
channel = "stable"
|
||||||
|
components = ["rustfmt", "clippy"]
|
||||||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
@@ -2314,7 +2314,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proxywarden"
|
name = "proxywarden"
|
||||||
version = "1.0.1"
|
version = "1.0.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "proxywarden"
|
name = "proxywarden"
|
||||||
version = "1.0.1"
|
version = "1.0.2"
|
||||||
description = "Standalone Windows desktop proxy management app for ProxyWarden."
|
description = "Standalone Windows desktop proxy management app for ProxyWarden."
|
||||||
authors = ["ProxyWarden"]
|
authors = ["ProxyWarden"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|||||||
@@ -12,12 +12,14 @@ use crate::component_detection::{
|
|||||||
proxyfier_component_from_detection, singbox_component_from_detection, DetectedProxyfier,
|
proxyfier_component_from_detection, singbox_component_from_detection, DetectedProxyfier,
|
||||||
DetectedSingBox, ProxyfierDetectionHost, SystemProxyfierDetectionHost,
|
DetectedSingBox, ProxyfierDetectionHost, SystemProxyfierDetectionHost,
|
||||||
};
|
};
|
||||||
|
use crate::elevated_scripts;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
ActivityEntry, ActivityLevel, ComponentId, ComponentState, ComponentStatus, LocalSingBoxConfig,
|
ActivityEntry, ActivityLevel, ComponentId, ComponentState, ComponentStatus, LocalSingBoxConfig,
|
||||||
Profile, ProfileInput, ProfileItem, ProfileItemInput, ProfileItemType, Protocol, ProxyProtocol,
|
Profile, ProfileInput, ProfileItem, ProfileItemInput, ProfileItemType, Protocol, ProxyProtocol,
|
||||||
SubscriptionCache, SubscriptionServer, Target, TargetInput, TargetKind,
|
SubscriptionCache, SubscriptionServer, Target, TargetInput, TargetKind,
|
||||||
};
|
};
|
||||||
use crate::process::command_no_window;
|
use crate::process::command_no_window;
|
||||||
|
use crate::safe_fs;
|
||||||
use crate::singbox_service::{
|
use crate::singbox_service::{
|
||||||
build_singbox_setup_status, ensure_safe_singbox_install_dir,
|
build_singbox_setup_status, ensure_safe_singbox_install_dir,
|
||||||
parse_service_command_output as parse_singbox_service_command_output, service_control_script,
|
parse_service_command_output as parse_singbox_service_command_output, service_control_script,
|
||||||
@@ -718,54 +720,71 @@ pub fn select_singbox_server(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn ping_singbox_server(
|
pub async fn ping_singbox_server(
|
||||||
state: tauri::State<'_, CommandState>,
|
state: tauri::State<'_, CommandState>,
|
||||||
input: PingSingBoxServerInputDto,
|
input: PingSingBoxServerInputDto,
|
||||||
) -> Result<PingServerResponse, CommandError> {
|
) -> Result<PingServerResponse, CommandError> {
|
||||||
ping_singbox_server_in_storage(&state.storage(), input)
|
let storage = state.storage();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || ping_singbox_server_in_storage(&storage, input))
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn ping_all_singbox_servers(
|
pub async fn ping_all_singbox_servers(
|
||||||
state: tauri::State<'_, CommandState>,
|
state: tauri::State<'_, CommandState>,
|
||||||
) -> Result<Vec<PingServerResponse>, CommandError> {
|
) -> Result<Vec<PingServerResponse>, CommandError> {
|
||||||
ping_all_singbox_servers_in_storage(&state.storage())
|
let storage = state.storage();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || ping_all_singbox_servers_in_storage(&storage))
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn ping_proxy_target(
|
pub async fn ping_proxy_target(
|
||||||
input: PingProxyTargetInputDto,
|
input: PingProxyTargetInputDto,
|
||||||
) -> Result<ProxyTargetCheckResponse, CommandError> {
|
) -> Result<ProxyTargetCheckResponse, CommandError> {
|
||||||
ping_proxy_target_endpoint(input)
|
tauri::async_runtime::spawn_blocking(move || ping_proxy_target_endpoint(input))
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn generate_singbox_config(
|
pub async fn generate_singbox_config(
|
||||||
state: tauri::State<'_, CommandState>,
|
state: tauri::State<'_, CommandState>,
|
||||||
) -> Result<GenerateSingBoxConfigResponse, CommandError> {
|
) -> Result<GenerateSingBoxConfigResponse, CommandError> {
|
||||||
|
let storage = state.storage();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let detected = detect_singbox_install();
|
let detected = detect_singbox_install();
|
||||||
let binary_path = detected
|
let binary_path = detected
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|detected| detected.executable_path.as_path());
|
.map(|detected| detected.executable_path.as_path());
|
||||||
generate_singbox_config_with_services(
|
generate_singbox_config_with_services(
|
||||||
&state.storage(),
|
&storage,
|
||||||
&SingBoxAdapter::default(),
|
&SingBoxAdapter::default(),
|
||||||
&SingBoxCommandChecker,
|
&SingBoxCommandChecker,
|
||||||
&SystemClock,
|
&SystemClock,
|
||||||
binary_path,
|
binary_path,
|
||||||
)
|
)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn apply_profiles(
|
pub async fn apply_profiles(
|
||||||
state: tauri::State<'_, CommandState>,
|
state: tauri::State<'_, CommandState>,
|
||||||
) -> Result<ApplyProfilesResponse, CommandError> {
|
) -> Result<ApplyProfilesResponse, CommandError> {
|
||||||
let storage = state.storage();
|
let storage = state.storage();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
let adapter = ProxiFyreAdapter::default();
|
let adapter = ProxiFyreAdapter::default();
|
||||||
let helper = DetectedProxyApplyHelper::system();
|
let helper = DetectedProxyApplyHelper::system();
|
||||||
let clock = SystemClock;
|
let clock = SystemClock;
|
||||||
|
|
||||||
apply_profiles_with_services(&storage, &adapter, &helper, &clock)
|
apply_profiles_with_services(&storage, &adapter, &helper, &clock)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(background_task_error)?
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -2193,11 +2212,7 @@ fn write_elevated_singbox_service_script(
|
|||||||
config_source: Option<&Path>,
|
config_source: Option<&Path>,
|
||||||
config_target: Option<&Path>,
|
config_target: Option<&Path>,
|
||||||
) -> Result<PathBuf, CommandError> {
|
) -> Result<PathBuf, CommandError> {
|
||||||
let nonce = SystemTime::now()
|
let script_path = elevated_scripts::temp_script_path("proxywarden-singbox-service");
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map(|duration| duration.as_millis())
|
|
||||||
.unwrap_or(0);
|
|
||||||
let script_path = env::temp_dir().join(format!("proxywarden-singbox-service-{nonce}.ps1"));
|
|
||||||
let script =
|
let script =
|
||||||
elevated_singbox_service_script(action, service_name, config_source, config_target);
|
elevated_singbox_service_script(action, service_name, config_source, config_target);
|
||||||
|
|
||||||
@@ -2374,10 +2389,6 @@ fn run_elevated_singbox_package_script(
|
|||||||
installer_args: Vec<String>,
|
installer_args: Vec<String>,
|
||||||
artifact_dir: &Path,
|
artifact_dir: &Path,
|
||||||
) -> Result<(), CommandError> {
|
) -> Result<(), CommandError> {
|
||||||
let nonce = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map(|duration| duration.as_millis())
|
|
||||||
.unwrap_or(0);
|
|
||||||
fs::create_dir_all(artifact_dir).map_err(|error| {
|
fs::create_dir_all(artifact_dir).map_err(|error| {
|
||||||
CommandError::new(
|
CommandError::new(
|
||||||
action.error_code(),
|
action.error_code(),
|
||||||
@@ -2388,18 +2399,12 @@ fn run_elevated_singbox_package_script(
|
|||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let installer_path = artifact_dir.join(format!(
|
let prefix = format!("proxywarden-singbox-{}", action.file_label());
|
||||||
"proxywarden-singbox-{}-{nonce}.ps1",
|
let installer_path = elevated_scripts::artifact_path(artifact_dir, &prefix, "ps1");
|
||||||
action.file_label()
|
let runner_path =
|
||||||
));
|
elevated_scripts::artifact_path(artifact_dir, &format!("{prefix}.runner"), "ps1");
|
||||||
let runner_path = artifact_dir.join(format!(
|
let result_path =
|
||||||
"proxywarden-singbox-{}-{nonce}.runner.ps1",
|
elevated_scripts::artifact_path(artifact_dir, &format!("{prefix}.result"), "log");
|
||||||
action.file_label()
|
|
||||||
));
|
|
||||||
let result_path = artifact_dir.join(format!(
|
|
||||||
"proxywarden-singbox-{}-{nonce}.log",
|
|
||||||
action.file_label()
|
|
||||||
));
|
|
||||||
|
|
||||||
write_powershell_script(&installer_path, installer_body).map_err(|error| {
|
write_powershell_script(&installer_path, installer_body).map_err(|error| {
|
||||||
CommandError::new(
|
CommandError::new(
|
||||||
@@ -2735,10 +2740,7 @@ fn resolved_app(item: &ProfileItem, warnings: &mut Vec<String>) -> ResolvedAppDt
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn write_generated_config(path: &Path, contents: &str) -> Result<(), CommandError> {
|
fn write_generated_config(path: &Path, contents: &str) -> Result<(), CommandError> {
|
||||||
if let Some(parent) = path.parent() {
|
safe_fs::write_with_backup(path, contents.as_bytes()).map_err(storage_error)
|
||||||
fs::create_dir_all(parent).map_err(storage_error)?;
|
|
||||||
}
|
|
||||||
fs::write(path, contents).map_err(storage_error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_file_or_select(path: &Path) -> Result<(), CommandError> {
|
fn open_file_or_select(path: &Path) -> Result<(), CommandError> {
|
||||||
@@ -3041,11 +3043,7 @@ fn write_elevated_service_script(
|
|||||||
action: ServiceControlAction,
|
action: ServiceControlAction,
|
||||||
service_names: &[String],
|
service_names: &[String],
|
||||||
) -> Result<PathBuf, CommandError> {
|
) -> Result<PathBuf, CommandError> {
|
||||||
let nonce = SystemTime::now()
|
let script_path = elevated_scripts::temp_script_path("proxywarden-proxifyre-service");
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map(|duration| duration.as_millis())
|
|
||||||
.unwrap_or(0);
|
|
||||||
let script_path = env::temp_dir().join(format!("proxywarden-proxifyre-service-{nonce}.ps1"));
|
|
||||||
let script = elevated_service_script(action, service_names);
|
let script = elevated_service_script(action, service_names);
|
||||||
|
|
||||||
write_powershell_script(&script_path, &script).map_err(|error| {
|
write_powershell_script(&script_path, &script).map_err(|error| {
|
||||||
@@ -3405,10 +3403,6 @@ fn run_elevated_package_script(
|
|||||||
body: String,
|
body: String,
|
||||||
artifact_dir: &Path,
|
artifact_dir: &Path,
|
||||||
) -> Result<(), CommandError> {
|
) -> Result<(), CommandError> {
|
||||||
let nonce = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.map(|duration| duration.as_millis())
|
|
||||||
.unwrap_or(0);
|
|
||||||
fs::create_dir_all(artifact_dir).map_err(|error| {
|
fs::create_dir_all(artifact_dir).map_err(|error| {
|
||||||
CommandError::new(
|
CommandError::new(
|
||||||
action.error_code(),
|
action.error_code(),
|
||||||
@@ -3418,14 +3412,10 @@ fn run_elevated_package_script(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let script_path = artifact_dir.join(format!(
|
let prefix = format!("proxywarden-proxifyre-{}", action.file_label());
|
||||||
"proxywarden-proxifyre-{}-{nonce}.ps1",
|
let script_path = elevated_scripts::artifact_path(artifact_dir, &prefix, "ps1");
|
||||||
action.file_label()
|
let result_path =
|
||||||
));
|
elevated_scripts::artifact_path(artifact_dir, &format!("{prefix}.result"), "log");
|
||||||
let result_path = artifact_dir.join(format!(
|
|
||||||
"proxywarden-proxifyre-{}-{nonce}.log",
|
|
||||||
action.file_label()
|
|
||||||
));
|
|
||||||
let script = wrap_elevated_package_script(&body, &result_path);
|
let script = wrap_elevated_package_script(&body, &result_path);
|
||||||
|
|
||||||
write_powershell_script(&script_path, &script).map_err(|error| {
|
write_powershell_script(&script_path, &script).map_err(|error| {
|
||||||
@@ -3617,8 +3607,126 @@ pub fn install_proxifyre_script(generated_config_path: &Path) -> String {
|
|||||||
return 'x86'
|
return 'x86'
|
||||||
}
|
}
|
||||||
|
|
||||||
function Invoke-Download([string]$uri, [string]$path) {
|
function Get-SafeUriForLog([string]$uri) {
|
||||||
Invoke-WebRequest -UseBasicParsing -Uri $uri -OutFile $path -Headers @{ 'User-Agent' = 'proxywarden' }
|
try {
|
||||||
|
$parsed = [Uri]$uri
|
||||||
|
$port = if ($parsed.IsDefaultPort) { '' } else { ":$($parsed.Port)" }
|
||||||
|
return "$($parsed.Scheme)://$($parsed.Host)$port$($parsed.AbsolutePath)"
|
||||||
|
} catch {
|
||||||
|
return '<invalid-url>'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-ReleaseApi([string]$uri, [string]$label) {
|
||||||
|
$safeUri = Get-SafeUriForLog $uri
|
||||||
|
$headers = @{ 'User-Agent' = 'proxywarden'; 'Accept' = 'application/vnd.github+json' }
|
||||||
|
$lastError = $null
|
||||||
|
|
||||||
|
foreach ($attempt in 1..3) {
|
||||||
|
try {
|
||||||
|
return Invoke-RestMethod -Uri $uri -Headers $headers -TimeoutSec 60 -MaximumRedirection 10
|
||||||
|
} catch {
|
||||||
|
$lastError = $_.Exception.Message
|
||||||
|
if ($attempt -lt 3) {
|
||||||
|
Start-Sleep -Seconds ([Math]::Min(10, $attempt * 2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw "Не удалось получить metadata для $label ($safeUri): $lastError"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Complete-Download([string]$partialPath, [string]$path, [string]$label) {
|
||||||
|
if (-not (Test-Path -LiteralPath $partialPath)) {
|
||||||
|
throw "${label}: файл не был создан."
|
||||||
|
}
|
||||||
|
|
||||||
|
$item = Get-Item -LiteralPath $partialPath
|
||||||
|
if ($item.Length -le 0) {
|
||||||
|
throw "${label}: скачанный файл пустой."
|
||||||
|
}
|
||||||
|
|
||||||
|
Move-Item -LiteralPath $partialPath -Destination $path -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-WebClientDownload([string]$uri, [string]$partialPath) {
|
||||||
|
$client = New-Object System.Net.WebClient
|
||||||
|
try {
|
||||||
|
$client.Headers.Add('User-Agent', 'proxywarden')
|
||||||
|
$client.Headers.Add('Accept', 'application/octet-stream,*/*')
|
||||||
|
$client.DownloadFile($uri, $partialPath)
|
||||||
|
} finally {
|
||||||
|
$client.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-CurlDownload([string]$uri, [string]$partialPath) {
|
||||||
|
$curl = Get-Command 'curl.exe' -ErrorAction SilentlyContinue
|
||||||
|
if ($null -eq $curl) {
|
||||||
|
throw 'curl.exe не найден.'
|
||||||
|
}
|
||||||
|
|
||||||
|
$curlOutput = & $curl.Source --silent --show-error --fail --location --retry 2 --retry-delay 2 --connect-timeout 30 --max-time 180 --user-agent 'proxywarden' --output $partialPath --url $uri 2>&1
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
$curlMessage = ($curlOutput | Out-String).Trim()
|
||||||
|
if ([string]::IsNullOrWhiteSpace($curlMessage)) {
|
||||||
|
throw "curl.exe завершился с кодом $LASTEXITCODE."
|
||||||
|
}
|
||||||
|
|
||||||
|
throw "curl.exe завершился с кодом ${LASTEXITCODE}: $curlMessage"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-Download([string]$uri, [string]$path, [string]$label) {
|
||||||
|
$safeUri = Get-SafeUriForLog $uri
|
||||||
|
$partialPath = "$path.part"
|
||||||
|
$headers = @{ 'User-Agent' = 'proxywarden'; 'Accept' = 'application/octet-stream,*/*' }
|
||||||
|
$webRequestError = $null
|
||||||
|
$webClientError = $null
|
||||||
|
$curlError = $null
|
||||||
|
|
||||||
|
foreach ($attempt in 1..3) {
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
try {
|
||||||
|
Invoke-WebRequest -UseBasicParsing -Uri $uri -OutFile $partialPath -Headers $headers -TimeoutSec 180 -MaximumRedirection 10
|
||||||
|
Complete-Download $partialPath $path $label
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
$webRequestError = $_.Exception.Message
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
if ($attempt -lt 3) {
|
||||||
|
Start-Sleep -Seconds ([Math]::Min(10, $attempt * 2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
Invoke-WebClientDownload $uri $partialPath
|
||||||
|
Complete-Download $partialPath $path $label
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
$webClientError = $_.Exception.Message
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
Invoke-CurlDownload $uri $partialPath
|
||||||
|
Complete-Download $partialPath $path $label
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
$curlError = $_.Exception.Message
|
||||||
|
Remove-Item -LiteralPath $partialPath -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
$errors = @()
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($webRequestError)) { $errors += "Invoke-WebRequest: $webRequestError" }
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($webClientError)) { $errors += "WebClient: $webClientError" }
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($curlError)) { $errors += "curl.exe: $curlError" }
|
||||||
|
$details = if ($errors.Count -gt 0) { $errors -join ' | ' } else { 'неизвестная ошибка' }
|
||||||
|
|
||||||
|
throw "Не удалось скачать $label ($safeUri): $details"
|
||||||
}
|
}
|
||||||
|
|
||||||
function Select-Asset($assets, [string]$pattern, [string]$label) {
|
function Select-Asset($assets, [string]$pattern, [string]$label) {
|
||||||
@@ -3682,7 +3790,7 @@ pub fn install_proxifyre_script(generated_config_path: &Path) -> String {
|
|||||||
if (-not (Test-VcRuntime $arch)) {
|
if (-not (Test-VcRuntime $arch)) {
|
||||||
$vcRedistPath = Join-Path $workDir 'vc_redist.exe'
|
$vcRedistPath = Join-Path $workDir 'vc_redist.exe'
|
||||||
$vcRedistUrl = if ($arch -eq 'x86') { $vcRedistX86Url } else { $vcRedistX64Url }
|
$vcRedistUrl = if ($arch -eq 'x86') { $vcRedistX86Url } else { $vcRedistX64Url }
|
||||||
Invoke-Download $vcRedistUrl $vcRedistPath
|
Invoke-Download $vcRedistUrl $vcRedistPath 'Microsoft Visual C++ Runtime'
|
||||||
$vcProcess = Start-Process -FilePath $vcRedistPath -ArgumentList @('/install', '/quiet', '/norestart') -Wait -PassThru -WindowStyle Hidden
|
$vcProcess = Start-Process -FilePath $vcRedistPath -ArgumentList @('/install', '/quiet', '/norestart') -Wait -PassThru -WindowStyle Hidden
|
||||||
if ($vcProcess.ExitCode -ne 0 -and $vcProcess.ExitCode -ne 3010 -and $vcProcess.ExitCode -ne 1638 -and -not (Test-VcRuntime $arch)) {
|
if ($vcProcess.ExitCode -ne 0 -and $vcProcess.ExitCode -ne 3010 -and $vcProcess.ExitCode -ne 1638 -and -not (Test-VcRuntime $arch)) {
|
||||||
throw "Visual C++ Runtime завершился с кодом $($vcProcess.ExitCode)."
|
throw "Visual C++ Runtime завершился с кодом $($vcProcess.ExitCode)."
|
||||||
@@ -3690,12 +3798,12 @@ pub fn install_proxifyre_script(generated_config_path: &Path) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-WindowsPacketFilter)) {
|
if (-not (Test-WindowsPacketFilter)) {
|
||||||
$ndisRelease = Invoke-RestMethod -Uri $ndisapiReleaseApi -Headers @{ 'User-Agent' = 'proxywarden' }
|
$ndisRelease = Invoke-ReleaseApi $ndisapiReleaseApi 'Windows Packet Filter'
|
||||||
$ndisPattern = if ($arch -eq 'ARM64') { 'ARM64\.msi$' } elseif ($arch -eq 'x86') { 'x86\.msi$' } else { 'x64\.msi$' }
|
$ndisPattern = if ($arch -eq 'ARM64') { 'ARM64\.msi$' } elseif ($arch -eq 'x86') { 'x86\.msi$' } else { 'x64\.msi$' }
|
||||||
$ndisAsset = Select-Asset $ndisRelease.assets $ndisPattern 'Windows Packet Filter'
|
$ndisAsset = Select-Asset $ndisRelease.assets $ndisPattern 'Windows Packet Filter'
|
||||||
$ndisPath = Join-Path $workDir $ndisAsset.name
|
$ndisPath = Join-Path $workDir $ndisAsset.name
|
||||||
$ndisLogPath = Join-Path $workDir 'windows-packet-filter-install.log'
|
$ndisLogPath = Join-Path $workDir 'windows-packet-filter-install.log'
|
||||||
Invoke-Download $ndisAsset.browser_download_url $ndisPath
|
Invoke-Download $ndisAsset.browser_download_url $ndisPath 'Windows Packet Filter'
|
||||||
Verify-AssetHash $ndisPath $ndisAsset
|
Verify-AssetHash $ndisPath $ndisAsset
|
||||||
$ndisProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', $ndisPath, '/qn', '/norestart', '/L*v', $ndisLogPath) -Wait -PassThru -WindowStyle Hidden
|
$ndisProcess = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', $ndisPath, '/qn', '/norestart', '/L*v', $ndisLogPath) -Wait -PassThru -WindowStyle Hidden
|
||||||
if ($ndisProcess.ExitCode -ne 0 -and $ndisProcess.ExitCode -ne 3010 -and -not (Test-WindowsPacketFilter)) {
|
if ($ndisProcess.ExitCode -ne 0 -and $ndisProcess.ExitCode -ne 3010 -and -not (Test-WindowsPacketFilter)) {
|
||||||
@@ -3704,11 +3812,11 @@ pub fn install_proxifyre_script(generated_config_path: &Path) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$proxifyreRelease = Invoke-RestMethod -Uri $proxifyreReleaseApi -Headers @{ 'User-Agent' = 'proxywarden' }
|
$proxifyreRelease = Invoke-ReleaseApi $proxifyreReleaseApi 'ProxiFyre'
|
||||||
$proxifyrePattern = if ($arch -eq 'ARM64') { 'ARM64-signed\.zip$' } elseif ($arch -eq 'x86') { 'x86-signed\.zip$' } else { 'x64-signed\.zip$' }
|
$proxifyrePattern = if ($arch -eq 'ARM64') { 'ARM64-signed\.zip$' } elseif ($arch -eq 'x86') { 'x86-signed\.zip$' } else { 'x64-signed\.zip$' }
|
||||||
$proxifyreAsset = Select-Asset $proxifyreRelease.assets $proxifyrePattern 'ProxiFyre'
|
$proxifyreAsset = Select-Asset $proxifyreRelease.assets $proxifyrePattern 'ProxiFyre'
|
||||||
$proxifyreZipPath = Join-Path $workDir $proxifyreAsset.name
|
$proxifyreZipPath = Join-Path $workDir $proxifyreAsset.name
|
||||||
Invoke-Download $proxifyreAsset.browser_download_url $proxifyreZipPath
|
Invoke-Download $proxifyreAsset.browser_download_url $proxifyreZipPath 'ProxiFyre'
|
||||||
Verify-AssetHash $proxifyreZipPath $proxifyreAsset
|
Verify-AssetHash $proxifyreZipPath $proxifyreAsset
|
||||||
|
|
||||||
Expand-Archive -LiteralPath $proxifyreZipPath -DestinationPath $extractDir -Force
|
Expand-Archive -LiteralPath $proxifyreZipPath -DestinationPath $extractDir -Force
|
||||||
@@ -3845,46 +3953,17 @@ fn apply_to_detected_proxyfier(
|
|||||||
return staged_apply_result(request);
|
return staged_apply_result(request);
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(parent) = config_path.parent() {
|
safe_fs::write_with_backup(config_path, request.config_contents.as_bytes()).map_err(
|
||||||
fs::create_dir_all(parent).map_err(|error| {
|
|error| {
|
||||||
CommandError::new(
|
CommandError::new(
|
||||||
"proxyfier_apply_failed",
|
"proxyfier_apply_failed",
|
||||||
format!(
|
format!(
|
||||||
"Не удалось создать папку конфига ProxiFyre '{}': {error}",
|
"Не удалось безопасно записать конфиг ProxiFyre '{}': {error}",
|
||||||
parent.display()
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if config_path.exists() {
|
|
||||||
let backup_path = config_path.with_file_name(format!(
|
|
||||||
"{}.bak",
|
|
||||||
config_path
|
|
||||||
.file_name()
|
|
||||||
.and_then(|value| value.to_str())
|
|
||||||
.unwrap_or("app-config.json")
|
|
||||||
));
|
|
||||||
fs::copy(config_path, backup_path).map_err(|error| {
|
|
||||||
CommandError::new(
|
|
||||||
"proxyfier_apply_failed",
|
|
||||||
format!(
|
|
||||||
"Не удалось создать backup текущего конфига ProxiFyre '{}': {error}",
|
|
||||||
config_path.display()
|
config_path.display()
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
})?;
|
},
|
||||||
}
|
)?;
|
||||||
|
|
||||||
fs::write(config_path, request.config_contents).map_err(|error| {
|
|
||||||
CommandError::new(
|
|
||||||
"proxyfier_apply_failed",
|
|
||||||
format!(
|
|
||||||
"Не удалось записать конфиг ProxiFyre '{}': {error}",
|
|
||||||
config_path.display()
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(HelperApplyResult {
|
Ok(HelperApplyResult {
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
19
src-tauri/src/elevated_scripts.rs
Normal file
19
src-tauri/src/elevated_scripts.rs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub fn temp_script_path(prefix: &str) -> PathBuf {
|
||||||
|
env::temp_dir().join(unique_file_name(prefix, "ps1"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn artifact_path(artifact_dir: &Path, prefix: &str, extension: &str) -> PathBuf {
|
||||||
|
artifact_dir.join(unique_file_name(prefix, extension))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unique_file_name(prefix: &str, extension: &str) -> String {
|
||||||
|
let extension = extension.trim_start_matches('.');
|
||||||
|
format!(
|
||||||
|
"{prefix}-{}.{}",
|
||||||
|
uuid::Uuid::new_v4().hyphenated(),
|
||||||
|
extension
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
pub mod activity;
|
pub mod activity;
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
pub mod component_detection;
|
pub mod component_detection;
|
||||||
|
pub mod elevated_scripts;
|
||||||
pub mod helper;
|
pub mod helper;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod process;
|
pub mod process;
|
||||||
|
pub mod safe_fs;
|
||||||
pub mod singbox_service;
|
pub mod singbox_service;
|
||||||
pub mod storage;
|
pub mod storage;
|
||||||
pub mod subscription;
|
pub mod subscription;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use percent_encoding::percent_decode_str;
|
use percent_encoding::percent_decode_str;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
pub const DEFAULT_LOCAL_SINGBOX_LISTEN_HOST: &str = "127.0.0.1";
|
pub const DEFAULT_LOCAL_SINGBOX_LISTEN_HOST: &str = "127.0.0.1";
|
||||||
pub const DEFAULT_LOCAL_SINGBOX_LISTEN_PORT: u16 = 1080;
|
pub const DEFAULT_LOCAL_SINGBOX_LISTEN_PORT: u16 = 1080;
|
||||||
@@ -293,24 +294,22 @@ pub fn redact_subscription_url(raw_url: &str) -> String {
|
|||||||
return String::new();
|
return String::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
match trimmed.split_once("://") {
|
let Ok(parsed) = Url::parse(trimmed) else {
|
||||||
Some((scheme, rest)) => {
|
return "***".to_string();
|
||||||
let host = rest
|
};
|
||||||
.split(['/', '?', '#'])
|
|
||||||
.next()
|
let host = parsed.host_str().unwrap_or("subscription");
|
||||||
.filter(|value| !value.is_empty())
|
let host = if host.contains(':') && !host.starts_with('[') {
|
||||||
.unwrap_or("subscription");
|
format!("[{host}]")
|
||||||
format!("{scheme}://{host}/...")
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
let visible = trimmed.chars().take(18).collect::<String>();
|
|
||||||
if trimmed.chars().count() <= 18 {
|
|
||||||
"***".to_string()
|
|
||||||
} else {
|
} else {
|
||||||
format!("{visible}...")
|
host.to_string()
|
||||||
}
|
};
|
||||||
}
|
let port = parsed
|
||||||
}
|
.port()
|
||||||
|
.map(|port| format!(":{port}"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
format!("{}://{}{}/...", parsed.scheme(), host, port)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decode_percent_encoded_utf8(value: &str) -> String {
|
pub fn decode_percent_encoded_utf8(value: &str) -> String {
|
||||||
|
|||||||
53
src-tauri/src/safe_fs.rs
Normal file
53
src-tauri/src/safe_fs.rs
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::io;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub fn backup_path(path: &Path) -> PathBuf {
|
||||||
|
sibling_with_suffix(path, "bak")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn corrupt_path(path: &Path) -> PathBuf {
|
||||||
|
sibling_with_suffix(
|
||||||
|
path,
|
||||||
|
&format!("corrupt.{}", uuid::Uuid::new_v4().hyphenated()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn temp_path(path: &Path) -> PathBuf {
|
||||||
|
sibling_with_suffix(path, &format!("tmp.{}", uuid::Uuid::new_v4().hyphenated()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn write_with_backup(path: &Path, contents: &[u8]) -> io::Result<()> {
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let temp_path = temp_path(path);
|
||||||
|
fs::write(&temp_path, contents)?;
|
||||||
|
|
||||||
|
let backup_path = backup_path(path);
|
||||||
|
if path.exists() {
|
||||||
|
fs::copy(path, &backup_path)?;
|
||||||
|
fs::remove_file(path)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
match fs::rename(&temp_path, path) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(error) => {
|
||||||
|
let _ = fs::remove_file(&temp_path);
|
||||||
|
if !path.exists() && backup_path.exists() {
|
||||||
|
let _ = fs::copy(&backup_path, path);
|
||||||
|
}
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sibling_with_suffix(path: &Path, suffix: &str) -> PathBuf {
|
||||||
|
let file_name = path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|value| value.to_str())
|
||||||
|
.unwrap_or("proxywarden-file");
|
||||||
|
|
||||||
|
path.with_file_name(format!("{file_name}.{suffix}"))
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ use crate::activity::{append_activity, cap_activity, DEFAULT_ACTIVITY_LIMIT};
|
|||||||
use crate::models::{
|
use crate::models::{
|
||||||
ActivityEntry, ComponentStatus, LocalSingBoxConfig, Profile, SubscriptionCache, Target,
|
ActivityEntry, ComponentStatus, LocalSingBoxConfig, Profile, SubscriptionCache, Target,
|
||||||
};
|
};
|
||||||
|
use crate::safe_fs;
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, ErrorKind};
|
use std::io::{self, ErrorKind};
|
||||||
@@ -144,10 +145,9 @@ impl JsonStorage {
|
|||||||
T: DeserializeOwned + Default,
|
T: DeserializeOwned + Default,
|
||||||
{
|
{
|
||||||
match fs::read_to_string(path) {
|
match fs::read_to_string(path) {
|
||||||
Ok(contents) => match serde_json::from_str(&contents) {
|
Ok(contents) => {
|
||||||
Ok(value) => Ok(value),
|
parse_json(path, &contents).or_else(|error| recover_corrupt_json(path, error))
|
||||||
Err(_) => Ok(T::default()),
|
}
|
||||||
},
|
|
||||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()),
|
Err(error) if error.kind() == ErrorKind::NotFound => Ok(T::default()),
|
||||||
Err(error) => Err(error),
|
Err(error) => Err(error),
|
||||||
}
|
}
|
||||||
@@ -167,7 +167,9 @@ impl JsonStorage {
|
|||||||
T: DeserializeOwned,
|
T: DeserializeOwned,
|
||||||
{
|
{
|
||||||
match fs::read_to_string(path) {
|
match fs::read_to_string(path) {
|
||||||
Ok(contents) => Ok(serde_json::from_str(&contents).ok()),
|
Ok(contents) => parse_json(path, &contents)
|
||||||
|
.map(Some)
|
||||||
|
.or_else(|error| recover_corrupt_json(path, error).map(Some)),
|
||||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
||||||
Err(error) => Err(error),
|
Err(error) => Err(error),
|
||||||
}
|
}
|
||||||
@@ -181,40 +183,72 @@ impl Default for JsonStorage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn backup_path(path: &Path) -> PathBuf {
|
pub fn backup_path(path: &Path) -> PathBuf {
|
||||||
sibling_with_suffix(path, "bak")
|
safe_fs::backup_path(path)
|
||||||
}
|
|
||||||
|
|
||||||
fn temp_path(path: &Path) -> PathBuf {
|
|
||||||
sibling_with_suffix(path, "tmp")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sibling_with_suffix(path: &Path, suffix: &str) -> PathBuf {
|
|
||||||
let file_name = path
|
|
||||||
.file_name()
|
|
||||||
.and_then(|value| value.to_str())
|
|
||||||
.unwrap_or("storage.json");
|
|
||||||
|
|
||||||
path.with_file_name(format!("{file_name}.{suffix}"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_atomic(path: &Path, contents: &[u8]) -> io::Result<()> {
|
fn write_atomic(path: &Path, contents: &[u8]) -> io::Result<()> {
|
||||||
if let Some(parent) = path.parent() {
|
safe_fs::write_with_backup(path, contents)
|
||||||
fs::create_dir_all(parent)?;
|
}
|
||||||
|
|
||||||
|
fn parse_json<T>(path: &Path, contents: &str) -> io::Result<T>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned,
|
||||||
|
{
|
||||||
|
serde_json::from_str(contents).map_err(|error| {
|
||||||
|
io::Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
format!("Invalid JSON in '{}': {error}", path.display()),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recover_corrupt_json<T>(path: &Path, parse_error: io::Error) -> io::Result<T>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned,
|
||||||
|
{
|
||||||
|
let corrupt_path = safe_fs::corrupt_path(path);
|
||||||
|
move_corrupt_file(path, &corrupt_path)?;
|
||||||
|
|
||||||
|
let backup_path = backup_path(path);
|
||||||
|
if backup_path.exists() {
|
||||||
|
let backup_contents = fs::read_to_string(&backup_path)?;
|
||||||
|
match parse_json(&backup_path, &backup_contents) {
|
||||||
|
Ok(value) => {
|
||||||
|
fs::copy(&backup_path, path)?;
|
||||||
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
Err(backup_error) => Err(io::Error::new(
|
||||||
let temp_path = temp_path(path);
|
ErrorKind::InvalidData,
|
||||||
fs::write(&temp_path, contents)?;
|
format!(
|
||||||
|
"Invalid JSON in '{}'; corrupt file moved to '{}'; backup '{}' could not be restored: {backup_error}; original error: {parse_error}",
|
||||||
if path.exists() {
|
path.display(),
|
||||||
fs::copy(path, backup_path(path))?;
|
corrupt_path.display(),
|
||||||
fs::remove_file(path)?;
|
backup_path.display()
|
||||||
|
),
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
Err(io::Error::new(
|
||||||
|
ErrorKind::InvalidData,
|
||||||
|
format!(
|
||||||
|
"Invalid JSON in '{}'; corrupt file moved to '{}'; no valid backup available: {parse_error}",
|
||||||
|
path.display(),
|
||||||
|
corrupt_path.display()
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
match fs::rename(&temp_path, path) {
|
fn move_corrupt_file(path: &Path, corrupt_path: &Path) -> io::Result<()> {
|
||||||
|
match fs::rename(path, corrupt_path) {
|
||||||
Ok(()) => Ok(()),
|
Ok(()) => Ok(()),
|
||||||
Err(error) => {
|
Err(rename_error) => {
|
||||||
let _ = fs::remove_file(&temp_path);
|
fs::copy(path, corrupt_path)?;
|
||||||
Err(error)
|
fs::remove_file(path)?;
|
||||||
|
if !corrupt_path.exists() {
|
||||||
|
return Err(rename_error);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
use crate::models::{decode_percent_encoded_utf8, SubscriptionCache, SubscriptionServer};
|
use crate::models::{decode_percent_encoded_utf8, SubscriptionCache, SubscriptionServer};
|
||||||
use base64::{engine::general_purpose, Engine};
|
use base64::{engine::general_purpose, Engine};
|
||||||
|
use reqwest::redirect;
|
||||||
use serde_json::{json, Map, Value};
|
use serde_json::{json, Map, Value};
|
||||||
|
use std::net::{IpAddr, Ipv6Addr};
|
||||||
|
use std::time::Duration;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
const SUPPORTED_PROXY_TYPES: &[&str] = &["vless", "vmess", "trojan", "shadowsocks", "hysteria2"];
|
const SUPPORTED_PROXY_TYPES: &[&str] = &["vless", "vmess", "trojan", "shadowsocks", "hysteria2"];
|
||||||
const DEFAULT_APP_NAME: &str = "ProxyWarden";
|
const DEFAULT_APP_NAME: &str = "ProxyWarden";
|
||||||
|
const SUBSCRIPTION_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const SUBSCRIPTION_REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct SubscriptionError {
|
pub struct SubscriptionError {
|
||||||
@@ -34,6 +39,11 @@ pub struct ParsedSubscription {
|
|||||||
pub servers: Vec<SubscriptionServer>,
|
pub servers: Vec<SubscriptionServer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||||
|
pub struct SubscriptionFetchPolicy {
|
||||||
|
pub allow_unsafe_local_urls: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct SubscriptionFetchIdentity {
|
pub struct SubscriptionFetchIdentity {
|
||||||
pub device_hwid: Option<String>,
|
pub device_hwid: Option<String>,
|
||||||
@@ -134,16 +144,35 @@ pub fn fetch_subscription(url: &str) -> Result<SubscriptionCache, SubscriptionEr
|
|||||||
pub fn fetch_subscription_with_identity(
|
pub fn fetch_subscription_with_identity(
|
||||||
url: &str,
|
url: &str,
|
||||||
identity: &SubscriptionFetchIdentity,
|
identity: &SubscriptionFetchIdentity,
|
||||||
|
) -> Result<SubscriptionCache, SubscriptionError> {
|
||||||
|
fetch_subscription_with_identity_and_policy(url, identity, SubscriptionFetchPolicy::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fetch_subscription_with_identity_and_policy(
|
||||||
|
url: &str,
|
||||||
|
identity: &SubscriptionFetchIdentity,
|
||||||
|
policy: SubscriptionFetchPolicy,
|
||||||
) -> Result<SubscriptionCache, SubscriptionError> {
|
) -> Result<SubscriptionCache, SubscriptionError> {
|
||||||
let parsed_url =
|
let parsed_url =
|
||||||
Url::parse(url).map_err(|_| SubscriptionError::new("Invalid subscription URL"))?;
|
Url::parse(url).map_err(|_| SubscriptionError::new("Invalid subscription URL"))?;
|
||||||
if !matches!(parsed_url.scheme(), "http" | "https") {
|
validate_subscription_fetch_url(&parsed_url, policy)?;
|
||||||
return Err(SubscriptionError::new(
|
|
||||||
"Subscription URL must use http or https",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut request = reqwest::blocking::Client::new().get(parsed_url);
|
let redirect_policy = redirect::Policy::custom(move |attempt| {
|
||||||
|
if validate_subscription_fetch_url(attempt.url(), policy).is_ok() {
|
||||||
|
attempt.follow()
|
||||||
|
} else {
|
||||||
|
attempt.stop()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.connect_timeout(SUBSCRIPTION_CONNECT_TIMEOUT)
|
||||||
|
.timeout(SUBSCRIPTION_REQUEST_TIMEOUT)
|
||||||
|
.redirect(redirect_policy)
|
||||||
|
.build()
|
||||||
|
.map_err(|error| {
|
||||||
|
SubscriptionError::new(format!("Subscription client setup failed: {error}"))
|
||||||
|
})?;
|
||||||
|
let mut request = client.get(parsed_url);
|
||||||
|
|
||||||
for (name, value) in identity.request_headers_without_device_hwid() {
|
for (name, value) in identity.request_headers_without_device_hwid() {
|
||||||
request = request.header(name, value);
|
request = request.header(name, value);
|
||||||
@@ -189,6 +218,69 @@ pub fn fetch_subscription_with_identity(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn validate_subscription_fetch_url(
|
||||||
|
parsed_url: &Url,
|
||||||
|
policy: SubscriptionFetchPolicy,
|
||||||
|
) -> Result<(), SubscriptionError> {
|
||||||
|
if !matches!(parsed_url.scheme(), "http" | "https") {
|
||||||
|
return Err(SubscriptionError::new(
|
||||||
|
"Subscription URL must use http or https",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !policy.allow_unsafe_local_urls && is_unsafe_subscription_host(parsed_url) {
|
||||||
|
return Err(SubscriptionError::new(
|
||||||
|
"Subscription URL host is local, private, link-local, multicast, or metadata-only",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unsafe_subscription_host(parsed_url: &Url) -> bool {
|
||||||
|
let Some(host) = parsed_url.host_str() else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
|
||||||
|
|
||||||
|
if matches!(host.as_str(), "localhost" | "metadata.google.internal")
|
||||||
|
|| host.ends_with(".localhost")
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
host.parse::<IpAddr>().is_ok_and(is_unsafe_ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unsafe_ip(ip: IpAddr) -> bool {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V4(ip) => {
|
||||||
|
ip.is_loopback()
|
||||||
|
|| ip.is_private()
|
||||||
|
|| ip.is_link_local()
|
||||||
|
|| ip.is_multicast()
|
||||||
|
|| ip.is_broadcast()
|
||||||
|
|| ip.is_unspecified()
|
||||||
|
|| ip.octets() == [169, 254, 169, 254]
|
||||||
|
}
|
||||||
|
IpAddr::V6(ip) => {
|
||||||
|
ip.is_loopback()
|
||||||
|
|| ip.is_unspecified()
|
||||||
|
|| ip.is_multicast()
|
||||||
|
|| is_unique_local_ipv6(ip)
|
||||||
|
|| is_unicast_link_local_ipv6(ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unique_local_ipv6(ip: Ipv6Addr) -> bool {
|
||||||
|
(ip.segments()[0] & 0xfe00) == 0xfc00
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unicast_link_local_ipv6(ip: Ipv6Addr) -> bool {
|
||||||
|
(ip.segments()[0] & 0xffc0) == 0xfe80
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_link_subscription(body: &str) -> Result<Value, SubscriptionError> {
|
fn parse_link_subscription(body: &str) -> Result<Value, SubscriptionError> {
|
||||||
let decoded = maybe_decode_base64(body);
|
let decoded = maybe_decode_base64(body);
|
||||||
let links = decoded
|
let links = decoded
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "ProxyWarden",
|
"productName": "ProxyWarden",
|
||||||
"version": "1.0.1",
|
"version": "1.0.2",
|
||||||
"identifier": "ru.dokops.proxywarden.windows",
|
"identifier": "ru.dokops.proxywarden.windows",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
@@ -13,16 +13,16 @@
|
|||||||
"windows": [
|
"windows": [
|
||||||
{
|
{
|
||||||
"title": "ProxyWarden",
|
"title": "ProxyWarden",
|
||||||
"width": 820,
|
"width": 920,
|
||||||
"height": 760,
|
"height": 760,
|
||||||
"minWidth": 820,
|
"minWidth": 760,
|
||||||
"maxWidth": 820,
|
"maxWidth": 1200,
|
||||||
"minHeight": 560,
|
"minHeight": 560,
|
||||||
"resizable": true
|
"resizable": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"security": {
|
"security": {
|
||||||
"csp": null
|
"csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost; img-src 'self' asset: http://asset.localhost data:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"bundle": {
|
"bundle": {
|
||||||
|
|||||||
@@ -251,6 +251,35 @@ fn proxifyre_install_script_parses_as_powershell() {
|
|||||||
cleanup(&root);
|
cleanup(&root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn proxifyre_install_script_uses_resilient_download_helpers() {
|
||||||
|
let root = test_root("proxifyre-install-script-downloads");
|
||||||
|
let script = commands::install_proxifyre_script(&root.join("proxifyre-app-config.json"));
|
||||||
|
|
||||||
|
assert!(script.contains("function Get-SafeUriForLog([string]$uri)"));
|
||||||
|
assert!(script.contains("function Invoke-ReleaseApi([string]$uri, [string]$label)"));
|
||||||
|
assert!(
|
||||||
|
script.contains("function Invoke-Download([string]$uri, [string]$path, [string]$label)")
|
||||||
|
);
|
||||||
|
assert!(script.contains("foreach ($attempt in 1..3)"));
|
||||||
|
assert!(script.contains("Invoke-WebClientDownload $uri $partialPath"));
|
||||||
|
assert!(script.contains("Invoke-CurlDownload $uri $partialPath"));
|
||||||
|
assert!(script.contains("--user-agent 'proxywarden' --output $partialPath --url $uri"));
|
||||||
|
assert!(script.contains("Move-Item -LiteralPath $partialPath -Destination $path -Force"));
|
||||||
|
assert!(script
|
||||||
|
.contains("Invoke-Download $vcRedistUrl $vcRedistPath 'Microsoft Visual C++ Runtime'"));
|
||||||
|
assert!(script.contains("Invoke-ReleaseApi $ndisapiReleaseApi 'Windows Packet Filter'"));
|
||||||
|
assert!(script.contains(
|
||||||
|
"Invoke-Download $ndisAsset.browser_download_url $ndisPath 'Windows Packet Filter'"
|
||||||
|
));
|
||||||
|
assert!(script.contains("Invoke-ReleaseApi $proxifyreReleaseApi 'ProxiFyre'"));
|
||||||
|
assert!(script.contains(
|
||||||
|
"Invoke-Download $proxifyreAsset.browser_download_url $proxifyreZipPath 'ProxiFyre'"
|
||||||
|
));
|
||||||
|
|
||||||
|
cleanup(&root);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn singbox_runner_preserves_installer_args_with_spaces() {
|
fn singbox_runner_preserves_installer_args_with_spaces() {
|
||||||
let script = commands::singbox_installer_runner_script(
|
let script = commands::singbox_installer_runner_script(
|
||||||
@@ -400,11 +429,14 @@ fn detected_proxy_apply_helper_writes_proxifyre_app_config() {
|
|||||||
|
|
||||||
let applied =
|
let applied =
|
||||||
fs::read_to_string(install_dir.join("app-config.json")).expect("read applied app-config");
|
fs::read_to_string(install_dir.join("app-config.json")).expect("read applied app-config");
|
||||||
|
let backup =
|
||||||
|
fs::read_to_string(install_dir.join("app-config.json.bak")).expect("read backup config");
|
||||||
|
|
||||||
assert!(result.success);
|
assert!(result.success);
|
||||||
assert!(result.changed);
|
assert!(result.changed);
|
||||||
assert_eq!(result.action, "proxifyre.apply-detected-config");
|
assert_eq!(result.action, "proxifyre.apply-detected-config");
|
||||||
assert_eq!(applied, r#"{"proxies":[]}"#);
|
assert_eq!(applied, r#"{"proxies":[]}"#);
|
||||||
|
assert_eq!(backup, "{}");
|
||||||
assert!(install_dir.join("app-config.json.bak").exists());
|
assert!(install_dir.join("app-config.json.bak").exists());
|
||||||
|
|
||||||
cleanup(&root);
|
cleanup(&root);
|
||||||
|
|||||||
@@ -159,7 +159,7 @@ fn reads_percent_encoded_singbox_tags_as_utf8() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_subscription_cache_falls_back_to_none() {
|
fn invalid_subscription_cache_without_backup_returns_error_and_moves_corrupt_file() {
|
||||||
let root = test_root("invalid-subscription-cache");
|
let root = test_root("invalid-subscription-cache");
|
||||||
let storage = JsonStorage::new(root.clone());
|
let storage = JsonStorage::new(root.clone());
|
||||||
fs::create_dir_all(&storage.paths().state_dir).expect("create state dir");
|
fs::create_dir_all(&storage.paths().state_dir).expect("create state dir");
|
||||||
@@ -169,27 +169,62 @@ fn invalid_subscription_cache_falls_back_to_none() {
|
|||||||
)
|
)
|
||||||
.expect("write invalid cache");
|
.expect("write invalid cache");
|
||||||
|
|
||||||
assert_eq!(
|
let error = storage
|
||||||
storage
|
|
||||||
.read_singbox_subscription_cache()
|
.read_singbox_subscription_cache()
|
||||||
.expect("invalid cache fallback"),
|
.expect_err("invalid cache should not silently fallback");
|
||||||
None
|
|
||||||
);
|
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||||
|
assert!(!storage.paths().singbox_subscription_cache_file.exists());
|
||||||
|
assert!(has_corrupt_sibling(
|
||||||
|
&storage.paths().singbox_subscription_cache_file
|
||||||
|
));
|
||||||
|
|
||||||
cleanup(&root);
|
cleanup(&root);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_json_falls_back_to_empty_collection() {
|
fn invalid_json_without_backup_returns_error_and_moves_corrupt_file() {
|
||||||
let root = test_root("invalid-json");
|
let root = test_root("invalid-json-no-backup");
|
||||||
let storage = JsonStorage::new(root.clone());
|
let storage = JsonStorage::new(root.clone());
|
||||||
fs::create_dir_all(&storage.paths().config_dir).expect("create config dir");
|
fs::create_dir_all(&storage.paths().config_dir).expect("create config dir");
|
||||||
fs::write(&storage.paths().profiles_file, "{not valid json").expect("write invalid json");
|
fs::write(&storage.paths().profiles_file, "{not valid json").expect("write invalid json");
|
||||||
|
|
||||||
|
let error = storage
|
||||||
|
.read_profiles()
|
||||||
|
.expect_err("invalid profiles should not silently fallback");
|
||||||
|
|
||||||
|
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||||
|
assert!(!storage.paths().profiles_file.exists());
|
||||||
|
assert!(has_corrupt_sibling(&storage.paths().profiles_file));
|
||||||
|
|
||||||
|
cleanup(&root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_json_recovers_from_valid_backup() {
|
||||||
|
let root = test_root("invalid-json-valid-backup");
|
||||||
|
let storage = JsonStorage::new(root.clone());
|
||||||
|
let backup_profiles = vec![sample_profile("backup")];
|
||||||
|
let current_profiles = vec![sample_profile("current")];
|
||||||
|
|
||||||
|
storage
|
||||||
|
.write_profiles(&backup_profiles)
|
||||||
|
.expect("write first profiles");
|
||||||
|
storage
|
||||||
|
.write_profiles(¤t_profiles)
|
||||||
|
.expect("write second profiles");
|
||||||
|
fs::write(&storage.paths().profiles_file, "{not valid json").expect("corrupt live json");
|
||||||
|
|
||||||
|
let recovered = storage
|
||||||
|
.read_profiles()
|
||||||
|
.expect("invalid profiles should recover from valid backup");
|
||||||
|
|
||||||
|
assert_eq!(recovered, backup_profiles);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
storage.read_profiles().expect("invalid profiles fallback"),
|
storage.read_profiles().expect("restored live profiles"),
|
||||||
Vec::<Profile>::new()
|
backup_profiles
|
||||||
);
|
);
|
||||||
|
assert!(has_corrupt_sibling(&storage.paths().profiles_file));
|
||||||
|
|
||||||
cleanup(&root);
|
cleanup(&root);
|
||||||
}
|
}
|
||||||
@@ -279,6 +314,26 @@ fn write_json<T: serde::Serialize + ?Sized>(path: &Path, value: &T) {
|
|||||||
fs::write(path, contents).expect("write json");
|
fs::write(path, contents).expect("write json");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn has_corrupt_sibling(path: &Path) -> bool {
|
||||||
|
let Some(parent) = path.parent() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let prefix = format!("{file_name}.corrupt.");
|
||||||
|
|
||||||
|
fs::read_dir(parent)
|
||||||
|
.expect("read sibling dir")
|
||||||
|
.filter_map(Result::ok)
|
||||||
|
.any(|entry| {
|
||||||
|
entry
|
||||||
|
.file_name()
|
||||||
|
.to_str()
|
||||||
|
.is_some_and(|name| name.starts_with(&prefix))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn sample_profile(id: &str) -> Profile {
|
fn sample_profile(id: &str) -> Profile {
|
||||||
Profile {
|
Profile {
|
||||||
id: id.to_string(),
|
id: id.to_string(),
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use base64::{engine::general_purpose, Engine};
|
|||||||
use proxywarden_lib::models::redact_subscription_url;
|
use proxywarden_lib::models::redact_subscription_url;
|
||||||
use proxywarden_lib::subscription::{
|
use proxywarden_lib::subscription::{
|
||||||
self, parse_subscription_body, parse_user_info, SubscriptionFetchIdentity,
|
self, parse_subscription_body, parse_user_info, SubscriptionFetchIdentity,
|
||||||
|
SubscriptionFetchPolicy,
|
||||||
};
|
};
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
@@ -91,6 +92,25 @@ fn rejects_invalid_or_non_http_subscription_url_before_network() {
|
|||||||
assert!(unsupported.message.contains("http or https"));
|
assert!(unsupported.message.contains("http or https"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unsafe_local_subscription_urls_before_network() {
|
||||||
|
for url in [
|
||||||
|
"http://127.0.0.1:9/subscription",
|
||||||
|
"http://localhost/subscription",
|
||||||
|
"http://169.254.169.254/latest/meta-data",
|
||||||
|
"http://192.168.0.1/subscription",
|
||||||
|
"http://[::1]/subscription",
|
||||||
|
] {
|
||||||
|
let error = subscription::fetch_subscription(url)
|
||||||
|
.expect_err("unsafe local URL should fail before request");
|
||||||
|
assert!(
|
||||||
|
error.message.contains("local, private"),
|
||||||
|
"unexpected error for {url}: {}",
|
||||||
|
error.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fetch_subscription_sends_device_hwid_header_when_identity_is_set() {
|
fn fetch_subscription_sends_device_hwid_header_when_identity_is_set() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind local test listener");
|
let listener = TcpListener::bind("127.0.0.1:0").expect("bind local test listener");
|
||||||
@@ -129,7 +149,13 @@ fn fetch_subscription_sends_device_hwid_header_when_identity_is_set() {
|
|||||||
|
|
||||||
let mut identity = SubscriptionFetchIdentity::with_device_hwid(Some("hwid-abc123"));
|
let mut identity = SubscriptionFetchIdentity::with_device_hwid(Some("hwid-abc123"));
|
||||||
identity.device_os_version = Some("Windows 11 Pro | 25H2 | build 26200.8655".to_string());
|
identity.device_os_version = Some("Windows 11 Pro | 25H2 | build 26200.8655".to_string());
|
||||||
let cache = subscription::fetch_subscription_with_identity(&url, &identity)
|
let cache = subscription::fetch_subscription_with_identity_and_policy(
|
||||||
|
&url,
|
||||||
|
&identity,
|
||||||
|
SubscriptionFetchPolicy {
|
||||||
|
allow_unsafe_local_urls: true,
|
||||||
|
},
|
||||||
|
)
|
||||||
.expect("fetch subscription through local test server");
|
.expect("fetch subscription through local test server");
|
||||||
let request = request_thread.join().expect("request thread");
|
let request = request_thread.join().expect("request thread");
|
||||||
|
|
||||||
@@ -151,7 +177,13 @@ fn redacts_subscription_url_for_display() {
|
|||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
redact_subscription_url("vless://uuid@example.test"),
|
redact_subscription_url("vless://uuid@example.test"),
|
||||||
"vless://uuid@example.test/..."
|
"vless://example.test/..."
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
redact_subscription_url(
|
||||||
|
"https://user:password@sub.example.test:8443/path?token=secret#frag"
|
||||||
|
),
|
||||||
|
"https://sub.example.test:8443/..."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
} from '../api/tauriCommands';
|
} from '../api/tauriCommands';
|
||||||
import type { ComponentStatus, Profile, ProfileItemInput, ProfileItemType, SubscriptionServer, Target } from '../domain/types';
|
import type { ComponentStatus, Profile, ProfileItemInput, ProfileItemType, SubscriptionServer, Target } from '../domain/types';
|
||||||
import { BusyRing, Button, DetailsPopover, IconButton, LogDock, ServiceControlRow, Tabs } from '../ui';
|
import { BusyRing, Button, DetailsPopover, IconButton, LogDock, ServiceControlRow, Tabs } from '../ui';
|
||||||
|
import { parseProxy, type ParsedProxy } from './lib/parseProxy';
|
||||||
import { getApplyReadiness } from './readiness';
|
import { getApplyReadiness } from './readiness';
|
||||||
import { serviceControlState } from './viewModel';
|
import { serviceControlState } from './viewModel';
|
||||||
|
|
||||||
@@ -1641,12 +1642,6 @@ export function App() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ParsedProxy {
|
|
||||||
protocol: 'socks5';
|
|
||||||
host: string;
|
|
||||||
port: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SummaryStateInput {
|
interface SummaryStateInput {
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
isDetectingComponents: boolean;
|
isDetectingComponents: boolean;
|
||||||
@@ -2337,35 +2332,6 @@ function changesApplyButtonLabel(
|
|||||||
return 'Применить изменения';
|
return 'Применить изменения';
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseProxy(rawValue: string): ParsedProxy {
|
|
||||||
const value = rawValue.trim();
|
|
||||||
if (!value) throw new Error('Введи адрес прокси.');
|
|
||||||
|
|
||||||
const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `socks5://${value}`;
|
|
||||||
let parsed: URL;
|
|
||||||
try {
|
|
||||||
parsed = new URL(withProtocol);
|
|
||||||
} catch {
|
|
||||||
throw new Error('Формат: socks5://host:port или host:port.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const protocol = parsed.protocol.replace(':', '').toLowerCase();
|
|
||||||
if (protocol !== 'socks5') {
|
|
||||||
throw new Error('Сейчас поддерживается только SOCKS5.');
|
|
||||||
}
|
|
||||||
if (parsed.username || parsed.password) {
|
|
||||||
throw new Error('Прокси с логином и паролем пока не поддерживаются.');
|
|
||||||
}
|
|
||||||
|
|
||||||
const host = parsed.hostname.replace(/^\[|\]$/g, '');
|
|
||||||
const port = Number(parsed.port);
|
|
||||||
if (!host || !Number.isInteger(port) || port < 1 || port > 65535) {
|
|
||||||
throw new Error('Укажи хост и порт прокси.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return { protocol: 'socks5', host, port };
|
|
||||||
}
|
|
||||||
|
|
||||||
function routeProxyCheckTarget(
|
function routeProxyCheckTarget(
|
||||||
routeMode: RouteMode,
|
routeMode: RouteMode,
|
||||||
proxyInput: string,
|
proxyInput: string,
|
||||||
|
|||||||
43
src/app/lib/parseProxy.test.ts
Normal file
43
src/app/lib/parseProxy.test.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { parseProxy } from './parseProxy';
|
||||||
|
|
||||||
|
describe('parseProxy', () => {
|
||||||
|
it('parses host and port without explicit protocol', () => {
|
||||||
|
expect(parseProxy('proxy.example.test:1080')).toEqual({
|
||||||
|
protocol: 'socks5',
|
||||||
|
host: 'proxy.example.test',
|
||||||
|
port: 1080,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses socks5 URLs', () => {
|
||||||
|
expect(parseProxy('socks5://127.0.0.1:1080')).toEqual({
|
||||||
|
protocol: 'socks5',
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: 1080,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses bracketed IPv6 hosts', () => {
|
||||||
|
expect(parseProxy('socks5://[::1]:1080')).toEqual({
|
||||||
|
protocol: 'socks5',
|
||||||
|
host: '::1',
|
||||||
|
port: 1080,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unsupported schemes', () => {
|
||||||
|
expect(() => parseProxy('http://proxy.example.test:8080')).toThrow('SOCKS5');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects missing or invalid ports', () => {
|
||||||
|
expect(() => parseProxy('proxy.example.test')).toThrow('хост и порт');
|
||||||
|
expect(() => parseProxy('proxy.example.test:70000')).toThrow('Формат');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects userinfo credentials', () => {
|
||||||
|
expect(() => parseProxy('socks5://user:password@proxy.example.test:1080')).toThrow(
|
||||||
|
'логином и паролем',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
34
src/app/lib/parseProxy.ts
Normal file
34
src/app/lib/parseProxy.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
export interface ParsedProxy {
|
||||||
|
protocol: 'socks5';
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseProxy(rawValue: string): ParsedProxy {
|
||||||
|
const value = rawValue.trim();
|
||||||
|
if (!value) throw new Error('Введи адрес прокси.');
|
||||||
|
|
||||||
|
const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : `socks5://${value}`;
|
||||||
|
let parsed: URL;
|
||||||
|
try {
|
||||||
|
parsed = new URL(withProtocol);
|
||||||
|
} catch {
|
||||||
|
throw new Error('Формат: socks5://host:port или host:port.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const protocol = parsed.protocol.replace(':', '').toLowerCase();
|
||||||
|
if (protocol !== 'socks5') {
|
||||||
|
throw new Error('Сейчас поддерживается только SOCKS5.');
|
||||||
|
}
|
||||||
|
if (parsed.username || parsed.password) {
|
||||||
|
throw new Error('Прокси с логином и паролем пока не поддерживаются.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = parsed.hostname.replace(/^\[|\]$/g, '');
|
||||||
|
const port = Number(parsed.port);
|
||||||
|
if (!host || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
|
throw new Error('Укажи хост и порт прокси.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { protocol: 'socks5', host, port };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user