Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8b467baba8 | |||
| 40d2be72db | |||
| ce3c917f8a | |||
| a70339bf32 | |||
| da72c64b50 | |||
| 883811bd55 | |||
| ba75930510 | |||
| f63e0b9fd9 | |||
| 0ac0a36598 | |||
| 996eb7ab29 | |||
| 8e40c49fa4 | |||
| a7a9f720e1 | |||
| a062f41a2e | |||
| 5b55b3e935 | |||
| 41a0bfa59d | |||
| 48fa5d6bed | |||
| c6fb96254a | |||
| aa377d56fd | |||
| 9fee5f283b | |||
| 053680a695 | |||
| 76ac754acd | |||
| 904fd64911 | |||
| 7ebdd96bcf | |||
| eb9cedb10a | |||
| c860bf195c | |||
| cbdc714ab8 | |||
| f92408b136 | |||
| d391e32f4f | |||
| 343f8cc1cd | |||
| 03806d7b10 | |||
| 7c7f7b15a0 | |||
| 7783f3c27d |
3
.gitignore
vendored
3
.gitignore
vendored
@ -13,4 +13,5 @@ yarn-debug.log*
|
||||
yarn-error.log*
|
||||
fe-app-netshift/.yarn/
|
||||
fe-app-netshift/.yarnrc.yml
|
||||
fe-app-netshift/.pnp.*
|
||||
fe-app-netshift/.pnp.*
|
||||
agent/
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
FROM itdoginfo/openwrt-sdk-ipk:24.10.6
|
||||
|
||||
ARG NETSHIFT_VERSION
|
||||
ENV NETSHIFT_VERSION=${NETSHIFT_VERSION}
|
||||
|
||||
COPY ./netshift /builder/package/feeds/utilities/netshift
|
||||
COPY ./luci-app-netshift /builder/package/feeds/luci/luci-app-netshift
|
||||
|
||||
RUN export NETSHIFT_VERSION="v${NETSHIFT_VERSION}" && \
|
||||
make defconfig && \
|
||||
RUN make defconfig && \
|
||||
make package/netshift/compile V=s -j4 && \
|
||||
make package/luci-app-netshift/compile V=s -j4
|
||||
|
||||
151
README.md
151
README.md
@ -6,7 +6,7 @@
|
||||
<img src="./docs/icon.png" alt="Clash" width="128" />
|
||||
<br>
|
||||
<br>
|
||||
<a href="https://github.com/yandexru45/netshift/releases">
|
||||
<a href="https://uralgit.ru/ural/netshift/releases">
|
||||
<img src="https://img.shields.io/github/release/yandexru45/netshift/all.svg">
|
||||
</a>
|
||||
</p>
|
||||
@ -32,10 +32,14 @@
|
||||
|
||||
## Функции
|
||||
|
||||
- [x] **Маршрутизация по доменам и подсетям** - нужное в туннель, остальное напрямую<br><sub>VLESS · Shadowsocks · Trojan · Hysteria2 · готовые community-списки</sub>
|
||||
- [x] **Subscription URL** - ссылки подписки от провайдера с автообновлением и автовыбором лучшего сервера<br><sub>любая подписка remnawave · 3x-ui · marzban · github</sub>
|
||||
- [x] **Переключаемое ядро sing-box** - стабильное ↔ sing-box-extended прямо из веб-интерфейса<br><sub>клиентский транспорт xhttp · установка и откат в один клик</sub>
|
||||
- [x] **Веб-интерфейс LuCI** - дашборд, диагностика и настройки без ручной правки конфигов<br><sub>статус серверов · проверка соединения · логи</sub>
|
||||
- [x] **Маршрутизация по доменам и подсетям** - нужное в туннель, остальное напрямую<br><sub>VLESS · Shadowsocks · Trojan · Hysteria2 · VMess · SOCKS · готовые community-списки</sub>
|
||||
- [x] **Subscription URL** - ссылки подписки от провайдера с автообновлением и автовыбором лучшего сервера<br><sub>любая подписка remnawave · 3x-ui · marzban · github · форматы base64 / URI / Clash / Xray JSON</sub>
|
||||
- [x] **Несколько подписок и фильтры** - несколько фидов в одной секции, фильтр серверов по ключевым словам (include / exclude)<br><sub>объединение без дублей · регистронезависимо · работает и по эмодзи</sub>
|
||||
- [x] **Группировка серверов** - по флагу страны или по префиксу имени, с авто-выбором «⚡ Самый быстрый» среди всех групп<br><sub>URLTest внутри группы · URLTest над группами · ручной выбор сохранён</sub>
|
||||
- [x] **Переключаемое ядро sing-box** - стабильное ↔ sing-box-extended прямо из веб-интерфейса<br><sub>клиентский транспорт xhttp · самовосстановление и автооткат · установка в один клик</sub>
|
||||
- [x] **Самообновление из веб-интерфейса** - проверка и установка обновлений NetShift прямо из LuCI<br><sub>асинхронно · бэкап конфига · без риска «окирпичивания»</sub>
|
||||
- [x] **Веб-интерфейс LuCI** - дашборд, менеджер компонентов, диагностика и настройки без ручной правки конфигов<br><sub>статус серверов · проверка соединения · логи · вкладки-карточки</sub>
|
||||
- [x] **IPv6, блокировка DoH, глобальный прокси** - полная маршрутизация v6 через туннель, защита DNS роутера, режим «весь трафик в туннель»<br><sub>v6 tproxy / DNS / FakeIP · DNS через прокси · фоновый watchdog sing-box</sub>
|
||||
- [x] **Автоматическая миграция** - обновление со старого podkop переносит конфиг без перенастройки
|
||||
|
||||
|
||||
@ -54,8 +58,9 @@
|
||||
<details open>
|
||||
<summary><b>Системные требования</b></summary>
|
||||
|
||||
- OpenWrt **24.10** или выше.
|
||||
- OpenWrt **24.10** или выше (поддерживаются и сборки на `opkg`/`.ipk`, и новые на `apk`/`.apk` - OpenWrt 25.12+).
|
||||
- Минимум **25 МБ** свободного места. Устройства с флеш-памятью 16 МБ не поддерживаются.
|
||||
- На устройстве: `sing-box >= 1.12.0`, `jq >= 1.7.1`, `coreutils-base64 >= 9.7` (ставятся как зависимости пакета).
|
||||
|
||||
</details>
|
||||
|
||||
@ -95,7 +100,7 @@
|
||||
|
||||
```sh
|
||||
mv /etc/config/netshift /etc/config/netshift-070
|
||||
wget -O /etc/config/netshift https://raw.githubusercontent.com/yandexru45/netshift/refs/heads/main/netshift/files/etc/config/netshift
|
||||
wget -O /etc/config/netshift https://uralgit.ru/ural/netshift/raw/branch/main/netshift/files/etc/config/netshift
|
||||
# затем настроить заново через LuCI или UCI
|
||||
```
|
||||
|
||||
@ -108,19 +113,34 @@ wget -O /etc/config/netshift https://raw.githubusercontent.com/yandexru45/netshi
|
||||
Для установки и обновления достаточно одного скрипта:
|
||||
|
||||
```sh
|
||||
sh <(wget -O - https://raw.githubusercontent.com/yandexru45/netshift/refs/heads/main/install.sh)
|
||||
sh <(wget -O - https://uralgit.ru/ural/netshift/raw/branch/main/install.sh)
|
||||
```
|
||||
|
||||
Интерфейс появится в LuCI: **Services → NetShift**.
|
||||
|
||||
<details>
|
||||
<summary><b>Готовые community-списки</b></summary>
|
||||
|
||||
Готовые наборы доменов/подсетей, которые можно добавить в секцию через `community_lists` (в UI - чекбоксами). Списки обновляются автоматически:
|
||||
|
||||
`russia_inside` · `russia_outside` · `ukraine_inside` · `geoblock` · `block` · `porn` · `news` · `anime` · `youtube` · `hdrezka` · `tiktok` · `google_ai` · `google_play` · `hodca` · `discord` · `meta` · `twitter` · `cloudflare` · `cloudfront` · `digitalocean` · `hetzner` · `ovh` · `telegram` · `roblox`
|
||||
|
||||
```sh
|
||||
uci add_list netshift.my_sub.community_lists='youtube'
|
||||
uci add_list netshift.my_sub.community_lists='telegram'
|
||||
uci commit netshift
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Настройка подписки (Subscription URL) через UCI</b></summary>
|
||||
|
||||
При скачивании подписки отправляются заголовки:
|
||||
Поддерживаются любые подписки (remnawave · 3x-ui · marzban · github) в форматах **base64 · список URI · Clash · Xray JSON**, в т.ч. **gzip-сжатые** ответы. При скачивании подписки отправляются заголовки:
|
||||
|
||||
| Заголовок | Значение |
|
||||
|---|---|
|
||||
| `User-Agent` | `singbox/<версия>` |
|
||||
| `User-Agent` | подбирается автоматически (`singbox/<версия>` или клиентский, см. формат) |
|
||||
| `X-HWID` | уникальный идентификатор роутера |
|
||||
| `X-Device-OS` | `OpenWrt Linux` |
|
||||
| `X-Device-Model` | модель роутера |
|
||||
@ -136,26 +156,113 @@ uci add_list netshift.my_sub.community_lists='russia_inside'
|
||||
uci commit netshift
|
||||
```
|
||||
|
||||
Ручное обновление подписки:
|
||||
**Несколько подписок** в одной секции - добавьте `subscription_url` списком (в UI - поле с «+»); все фиды скачиваются и объединяются в один набор узлов без дублей:
|
||||
|
||||
```sh
|
||||
/usr/bin/netshift subscription_update
|
||||
uci add_list netshift.my_sub.subscription_url='https://provider-a.com/sub'
|
||||
uci add_list netshift.my_sub.subscription_url='https://provider-b.com/sub'
|
||||
```
|
||||
|
||||
**Фильтр серверов** по ключевым словам - белый/чёрный список (регистр не важен, работает и по эмодзи):
|
||||
|
||||
```sh
|
||||
uci add_list netshift.my_sub.subscription_filter_include='🇩🇪'
|
||||
uci add_list netshift.my_sub.subscription_filter_exclude='trial'
|
||||
```
|
||||
|
||||
**Группировка серверов** - собирает узлы в URLTest-группы и добавляет авто-выбор «⚡ Самый быстрый» среди всех групп (при ≥2 группах он же выбор по умолчанию; ручной выбор группы сохраняется):
|
||||
|
||||
```sh
|
||||
# off | country (по флагу страны) | prefix (по первым N символам имени)
|
||||
uci set netshift.my_sub.subscription_group_mode='country'
|
||||
# для prefix: сколько первых символов имени брать (по умолчанию 2)
|
||||
uci set netshift.my_sub.subscription_group_prefix_len='2'
|
||||
```
|
||||
|
||||
**Предпочтительный формат** - для панелей, которые отдают нужные узлы (например xhttp / Hysteria2) только под определённым клиентом:
|
||||
|
||||
```sh
|
||||
# auto | xray (Xray JSON, UA как у Happ) | singbox
|
||||
uci set netshift.my_sub.subscription_format_preference='auto'
|
||||
```
|
||||
|
||||
**Подписки по IP-хосту и «кривой» HTTPS** - можно указать подписку с IP вместо домена (например `https://22.23.43.52:2096/sub/xxxx`); для панелей с самоподписанным / несовпадающим сертификатом включите небезопасный TLS:
|
||||
|
||||
```sh
|
||||
uci set netshift.my_sub.subscription_allow_insecure='1'
|
||||
```
|
||||
|
||||
Ручное обновление подписки и очистка кеша:
|
||||
|
||||
```sh
|
||||
/usr/bin/netshift subscription_update # перечитать и применить
|
||||
# Очистка кеша всех подписок и повторное скачивание - кнопка во вкладке «Диагностика»
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Ядро sing-box-extended (xhttp)</b></summary>
|
||||
<summary><b>Менеджер компонентов: ядро sing-box-extended (xhttp) и самообновление</b></summary>
|
||||
|
||||
Переключение ядра между стабильным sing-box и сборкой **sing-box-extended** прямо из вкладки **Diagnostics** в LuCI:
|
||||
Вкладка **Менеджер компонентов** в LuCI управляет NetShift и ядром sing-box в одном месте - три карточки: **NetShift** / **sing-box (stock)** / **sing-box (extended)**. Установленная версия видна сразу, статус (актуально / устарело / не установлено) и кнопка «Проверить обновление» - по нажатию.
|
||||
|
||||
- **Install extended** - установить расширенное ядро sing-box-extended.
|
||||
**Переключение ядра** между стабильным sing-box и сборкой **sing-box-extended**:
|
||||
|
||||
- **Install extended** - расширенное ядро (даёт клиентский транспорт **xhttp**, только клиентский режим). Также поддерживается **VMess**.
|
||||
- **Install stable** - вернуться на стабильное ядро.
|
||||
|
||||
После установки расширенного ядра становится доступен клиентский транспорт **xhttp** (только клиентский режим, не серверный). По умолчанию ставится стабильное ядро - extended включается по желанию.
|
||||
Смена ядра безопасна: перед переключением проверяется и при необходимости чинится связь, делается бэкап; при сбое - **автооткат**, роутер никогда не остаётся без рабочего ядра. По умолчанию стоит стабильное - extended включается по желанию.
|
||||
|
||||
**Самообновление NetShift** - кнопка обновления прямо из веб-интерфейса: асинхронно, с бэкапом конфига, проверкой фактической версии после установки и без риска «окирпичивания». Русская локализация обновляется только если уже установлена.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Дополнительные настройки (IPv6, блокировка DoH, глобальный прокси, DNS через прокси)</b></summary>
|
||||
|
||||
Все опции - в секции `settings` (`0` - выкл, `1` - вкл):
|
||||
|
||||
```sh
|
||||
# Полная маршрутизация IPv6 через туннель (v6 tproxy / DNS / FakeIP). По умолчанию выкл.
|
||||
uci set netshift.settings.enable_ipv6='1'
|
||||
|
||||
# Блокировка DoH: клиенты в сети не обойдут DNS роутера через DNS-over-HTTPS
|
||||
# (режет известные DoH-эндпоинты IPv4 + IPv6 на уровне маршрутов sing-box).
|
||||
uci set netshift.settings.block_doh='1'
|
||||
|
||||
# Глобальный прокси: ВЕСЬ трафик через выбранный outbound (а не только избранное).
|
||||
# Только при явном включении - иначе действует выборочная маршрутизация.
|
||||
uci set netshift.settings.global_proxy='1'
|
||||
|
||||
# DNS через прокси (detour): DNS-запросы идут через туннель.
|
||||
uci set netshift.settings.dns_via_outbound='1'
|
||||
|
||||
# Блокировать QUIC (заставляет приложения откатываться на TCP/TLS).
|
||||
uci set netshift.settings.disable_quic='1'
|
||||
|
||||
uci commit netshift
|
||||
```
|
||||
|
||||
> По умолчанию NetShift гонит в sing-box **только** проксируемые подсети/домены, остальное - напрямую (выборочная маркировка). Режим «весь трафик в туннель» включается **только** опцией `global_proxy`.
|
||||
|
||||
</details>
|
||||
|
||||
## История изменений
|
||||
|
||||
Полный список изменений по версиям - на странице [Releases](https://github.com/yandexru45/netshift/releases). Анонсы обновлений публикуются в [Telegram-канале](https://t.me/netshift_news).
|
||||
|
||||
Коротко о крупных вехах:
|
||||
|
||||
| Версия | Главное |
|
||||
|---|---|
|
||||
| **0.9.1** | Авто-выбор «⚡ Самый быстрый» среди групп (URLTest над URLTest'ами) |
|
||||
| **0.9.0** | Меньше ошибок «лимит GitHub API» (обход через redirect-путь github.com); фикс старого `option subscription_url` |
|
||||
| **0.8.9** | Универсальная группировка подписки (страна / префикс имени); поддержка gzip-подписок; фикс ложного «версия устарела» |
|
||||
| **0.8.7-0.8.8** | Критфикс маршрутизации 2-й секции; выборочная маркировка (меньше нагрузки CPU); Hysteria2 + xhttp везде; несколько подписок; надёжное самообновление |
|
||||
| **0.8.6** | IPv6 · блокировка DoH · вкладка «Менеджер компонентов» · самообновление · подписки по IP / небезопасный TLS · глобальный прокси · DNS через прокси · watchdog |
|
||||
| **0.8.5** | VMess (extended) · надёжная смена ядра с автооткатом · фильтр серверов по ключевым словам · Xray JSON + автоподбор User-Agent |
|
||||
| **0.8.0** | Переименование podkop → NetShift с авто-миграцией конфигов; sing-box-extended (xhttp) из веб-интерфейса |
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
@ -188,7 +295,7 @@ uci commit netshift
|
||||
|
||||
## Build Artifacts
|
||||
|
||||
Пакеты собираются в Docker-образе OpenWrt SDK (24.10) и публикуются как релиз при push git-тега ([`.github/workflows/build.yml`](.github/workflows/build.yml)).
|
||||
Пакеты собираются в Docker-образах OpenWrt SDK (`.ipk` - 24.10, `.apk` - 25.12) и публикуются как релиз при push git-тега ([`.github/workflows/build.yml`](.github/workflows/build.yml)).
|
||||
|
||||
| Пакет | Формат | Назначение |
|
||||
|---|---|---|
|
||||
@ -199,14 +306,14 @@ uci commit netshift
|
||||
Локальная сборка:
|
||||
|
||||
```sh
|
||||
# ipk (большинство устройств OpenWrt 24.10)
|
||||
docker build -f Dockerfile-ipk --build-arg NETSHIFT_VERSION=0.8.0 -t netshift:ipk .
|
||||
# ipk (OpenWrt 24.10, opkg)
|
||||
docker build -f Dockerfile-ipk --build-arg NETSHIFT_VERSION=0.9.1 -t netshift:ipk .
|
||||
|
||||
# apk (новые сборки OpenWrt на apk)
|
||||
docker build -f Dockerfile-apk --build-arg NETSHIFT_VERSION=0.8.0 -t netshift:apk .
|
||||
# apk (новые сборки OpenWrt 25.12+, apk)
|
||||
docker build -f Dockerfile-apk --build-arg NETSHIFT_VERSION=0.9.1 -t netshift:apk .
|
||||
```
|
||||
|
||||
> Требуется sing-box >= 1.12.0 и jq >= 1.7.1 на целевом устройстве.
|
||||
> Требуется sing-box >= 1.12.0, jq >= 1.7.1 и coreutils-base64 >= 9.7 на целевом устройстве.
|
||||
|
||||
## Star History
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -64,3 +64,12 @@ append recurring findings; keep under ~200 lines.
|
||||
- Frontend barrel exposure: anything added to src/helpers/index.ts (or any export* barrel reaching main.ts) AND actually used appears in the generated main.js baseclass.extend block as a main.* symbol; unused re-exports get tree-shaken. So internal-only helper + added to barrel + used = it WILL leak to main.*. To keep a helper truly internal, place it in the consuming module, not the barrel.
|
||||
|
||||
- OpenWrt jq ascii_downcase only folds ASCII A-Z; case-insensitive matching on Cyrillic/Unicode names needs an inline codepoint fold (explode/map/implode: ASCII 65-90 +32, Cyrillic 1040-1071 +32, Yo 1025->1105). When reviewing such a fold: (a) already-lowercase ranges excluded (no double-fold), (b) def before first use when the program does NOT import helpers.jq, (c) a pure-emoji-keyword exact-match test proves non-folded codepoints pass through unchanged on both sides. (task-010)
|
||||
|
||||
- Package-manager rc is NOT a reliable success signal on opkg: rc=0 for "Not downgrading"/"already installed"/"up to date". A self-update/install that trusts only rc silently no-ops (the v→no-v rename trap: legacy `v0.8.6` sorts ABOVE `0.8.7` in opkg's compare, so `opkg install` refuses the "downgrade" and returns 0). When reviewing a package-install path, require: (a) `--force-downgrade --force-reinstall` on the opkg branch (apk overwrites by default); AND (b) verify-after-install — RE-READ the installed version (opkg `list-installed | grep "^pkg "`, apk `list --installed`; grep/awk only, NO Oniguruma jq) and compare v-stripped semver (`${x#v}`, `${x%%-*}`) with `==` OR `is_min_package_version installed target`; empty-installed must fail-safe to success:false. Keep install.sh `pkg_install` and updater.sh `updates_pkg_install_file` opkg branches ALIGNED. (task-041/042)
|
||||
- Async self-update worker landmine: the `_*_core` worker MUST `return 1` (NEVER `exit`) on failure so the public wrapper's always-run `updates_restore_after_swap` epilogue + finished-job-state write still execute. Verify the wrapper captures core rc/JSON to a temp file then unconditionally restores. Smoke assertions for these must be in the MAIN shell body (direct `if…pass/fail`), never inside `cmd | while read` (subshell swallows PASS/FAIL — harness-wide landmine). (task-041)
|
||||
|
||||
- UCI option→list rewrites: the `uci add_list "key=value"` CLI form splits on the FIRST `=` and SILENTLY LOSES query-string URLs (`?token=abc&x=1`) — reproduced on hardware (rc=1, list empty). Require the `uci_add_list <cfg> <sec> <opt> "<val>"` SHELL HELPER (separate-arg, preserves `=`/`&`). For delete-then-add rewrites, verify a failed add RESTORES the scalar AND that the change-flag gates the `uci commit` (an uncommitted in-memory delete must never persist). (task-048 [B1])
|
||||
- When RE-reviewing a fix round, also diff the developer's MEMORY note: it is frequently written against the PRE-fix code and re-seeds the very anti-pattern that was just fixed (task-048 [M2]: note still showed the `key=value` form + "non-gating piped-while" after both were fixed). Flag a stale memory note as a (minor) condition.
|
||||
- Test-gating landmine: a smoke test whose assertions run on the RHS of a pipe (`cmd | while read; pass/fail`) does NOT gate CI (subshell counter loss) — a FAIL token prints red but the suite exits 0. Require current-shell parsing (`while read < tmpfile`). The 178→190 count jump when task-048 fixed this is the tell. (task-048 [S1])
|
||||
|
||||
- Rate-limit avoidance via redirect path (task-049): version-check/self-update/install can read the latest tag from `github.com/<repo>/releases/latest` (302 -> /releases/tag/<tag>, served by the github.com FRONTEND, NOT the 60/hr-per-IP api.github.com) instead of the API. Tag extracted with `curl -sI -o /dev/null -w '%{redirect_url}'` then `case`/param-expansion `${r##*/releases/tag/}` — when reviewing such code REQUIRE: (a) the tag is rejected if empty OR `/`-containing (path-traversal/injection guard) via `case "$tag" in ''|*/*) tag="" ;;`; (b) the tag is only used quoted inside a URL string / passed quoted to helpers, never `eval`'d or used as a bare filesystem path; (c) curl-absent / non-match degrades to the API fallback (no hard-fail/exit); (d) the file-download helper uses `curl -fsSL`/`-L` so the CDN 302 on `releases/download/<tag>/<asset>` is followed. busybox wget on-device is STRIPPED (no -S/--max-redirect/header read) so redirect reading MUST use curl (hard +curl dep). Keep the sing-box-EXTENDED releases-LIST path on the API (a redirect can't give draft/prerelease/per-arch).
|
||||
|
||||
@ -186,3 +186,739 @@ append findings; keep under ~200 lines.
|
||||
`#`) case proving base64-body whitespace is still rejected.
|
||||
- main.js diff for this fix is exactly the `validateVmessUrl` function body
|
||||
(body/b64 split + whitespace-on-b64 + pad b64) — expected-only.
|
||||
|
||||
## settings.js section-picker pattern + DNS-via-outbound (task-015)
|
||||
|
||||
- `settings.js` is a HAND-WRITTEN LuCI view (NOT bundled by tsup → editing it
|
||||
yields NO main.js diff). The reusable "pick a proxy/vpn section" dropdown
|
||||
pattern: `form.ListValue` + `o.depends(<flag>,'1')` + `o.cfgvalue` reading
|
||||
`uci.get('netshift',section_id,<opt>)` + custom `o.load` that walks
|
||||
`this.map?.data?.state?.values?.netshift ?? {}`, pushes secName to
|
||||
`this.keylist`/`this.vallist` when `sec['.type']==='section'` AND
|
||||
`connection_type` is NOT `block`/`exclusion`, returns `Promise.resolve()`.
|
||||
Mirrors `download_lists_via_proxy_section` (settings.js ~294-321).
|
||||
- `dns_outbound_section` uses `rmempty=true` (empty = backend falls back to
|
||||
first outbound) — intentionally differs from the download-proxy clone's
|
||||
`rmempty=false`. Don't "normalize" it.
|
||||
- R3 trap: the spec called the diagnostic field "type-only ⇒ no main.js diff",
|
||||
but adding the field to `types.ts` is type-only (erased at build) WHILE the
|
||||
paired `runDnsCheck.ts` `insertIf` render IS RUNTIME CODE → it DOES produce a
|
||||
legit main.js diff (the 10-line insertIf block). That regenerated main.js is
|
||||
the deliverable; a second build is idempotent (no further diff). "No diff"
|
||||
only holds if you skip the runDnsCheck.ts edit.
|
||||
- locales: ran `node {extract-calls,generate-pot,generate-po ru,
|
||||
distribute-locales}.js` (NOT yarn → no corepack). New ru text goes in the
|
||||
SOURCE `locales/netshift.ru.po` empty `msgstr`, then `distribute-locales.js`
|
||||
copies to `po/ru/netshift.po` + `po/templates/netshift.pot`. Regen touches
|
||||
calls.json/pot broadly (line-ref reshuffle + POT-Creation-Date header) but is
|
||||
PURELY ADDITIVE — verified at msgid level: 5 added, 0 removed.
|
||||
- ENCODING TRAP (Windows/PS5.1): `git show HEAD:file > tmp` re-encodes the blob
|
||||
to UTF-16 and MANGLES UTF-8 (emoji/Cyrillic) — gives FALSE "removed/added"
|
||||
noise. Use `cmd /c "git ... > %TEMP%\f"` (preserves raw bytes) OR compare via
|
||||
`git diff` directly. The committed .pot/.po ARE valid UTF-8; don't panic.
|
||||
- Console prints po/pot Cyrillic as mojibake — that's PS display only; verify
|
||||
on-disk via `node -e "require('./locales/calls.json')...includes(...)"` or
|
||||
UTF-8 byte reads, not the terminal.
|
||||
- New i18n keys (task-015) + ru: "Route main DNS through proxy/VPN"→"Основной
|
||||
DNS через прокси/VPN"; "DNS outbound section"→"Секция outbound для DNS";
|
||||
"Main DNS via outbound"→"Основной DNS через outbound"; long descriptions
|
||||
translated equivalently.
|
||||
|
||||
## validateIPV6 rewrite + concat-_() i18n (task-015 PR#11 fixes)
|
||||
|
||||
- The OLD `validateIPV6` (two loose regexes + `colons>=2&&<=7` guard) WRONGLY
|
||||
accepted `:::`, `1:2:::3`, `1::2::3` (multiple `::`), `1:2:3:4:5:6:7`
|
||||
(incomplete 7-group). Replaced with a small functional checker (no `any`):
|
||||
count `::` via `stripped.split('::').length-1` (reject >1); split into
|
||||
head/tail, `countGroups(side)` splits on `:` and validates each as
|
||||
`/^[0-9a-fA-F]{1,4}$/` hextet; group-count rule = exactly 8 when no `::`,
|
||||
≤7 when one `::` (it stands for ≥1 zero group). `''` side → 0 groups (so `::`
|
||||
unspecified and `::1` work). Helpers `isHextet`/`countGroups`/`isEmbeddedIPv4`
|
||||
are module-private (NOT in barrel) → no `main.*` export leak; verified diff
|
||||
has no new bare export lines.
|
||||
- F-04 DECISION: ACCEPT IPv4-embedded IPv6 (`::ffff:192.168.1.1`,
|
||||
`2001:db8::192.168.1.1`) — valid per RFC 4291. `countGroups` treats a LAST
|
||||
group containing `.` as an embedded IPv4 (validated via `validateIPV4`) that
|
||||
occupies TWO 16-bit groups (so it adds +1 to the group count). Tested both
|
||||
positive and the malformed negatives.
|
||||
- main.js diff for this is EXACTLY the validateIPV6 function body + 3 private
|
||||
helpers (52+/7- lines); second build idempotent. Expected runtime-code diff.
|
||||
- I18N CONCAT GOTCHA (F-02): `_('foo ' + 'bar')` is NOT extracted (gettext sees
|
||||
only literal args; the `+` makes it an expression). The established repo
|
||||
convention (see section.js community_lists ~415) is
|
||||
`_('foo') + ' ' + _('bar')` — the SPACE lives OUTSIDE `_()`, and each literal
|
||||
has NO trailing/leading space. `extract-calls.js` line 55 does `arg.value.trim()`
|
||||
so a trailing space INSIDE `_('foo ')` is trimmed in the catalog → runtime
|
||||
lookup of `'foo '` MISSES. So ALWAYS put separators outside `_()`. Fixed
|
||||
global_proxy (section.js ~310), block_doh + enable_ipv6 (settings.js ~463/481).
|
||||
- locales regen: ran `node {extract-calls,generate-pot,generate-po ru,
|
||||
distribute-locales}.js` (NOT yarn). `generate-pot.js` calls
|
||||
`git config user.name`/`user.email` and CRASHES if unset → set them locally
|
||||
(`git config --local user.name "..."`, email may be empty string which returns
|
||||
rc=0). POT header churns (POT-Creation-Date timezone + `<>` from empty email)
|
||||
— cosmetic, accepted; msgid-level diff was PURELY ADDITIVE (10 added, 0
|
||||
removed). 10 new ru msgstrs filled in SOURCE locales/netshift.ru.po then
|
||||
distributed to po/ru + po/templates (both end up byte-identical to source).
|
||||
- The 10 new ru fragments are the split sentences of the 3 flag descriptions
|
||||
(global proxy / block DoH / enable IPv6) — translated formally/technically
|
||||
matching neighbours. All catalogs LF, no empty non-header msgstr remained.
|
||||
|
||||
## Component Manager tab (task-018)
|
||||
|
||||
- NEW TAB = 5-file pattern mirroring `tabs/diagnostic`: `manager/{index,render,
|
||||
initController,styles}.ts` + a hand-written `view/netshift/manager.js`
|
||||
(`form.DummyValue _mount_node`, `o.rawhtml=true`, `cfgvalue` →
|
||||
`main.ManagerTab.initController()` + `return main.ManagerTab.render()`).
|
||||
Register in `netshift.js`: add `"require view.netshift.manager as manager"`
|
||||
+ a `form.TypedSection` block (`anonymous=true`, `addremove=false`,
|
||||
`cfgsections=()=>["manager"]`). NB the tab UCI section name (`manager`,
|
||||
`diagnostic`, `dashboard`) need NOT exist in `/etc/config/netshift` — LuCI
|
||||
renders the virtual TypedSection anyway (diagnostic/dashboard prove it).
|
||||
- Barrel: add `export * from './manager';` to `tabs/index.ts` → `ManagerTab`
|
||||
reaches `main.ManagerTab` (verified in the export block at the bottom of
|
||||
main.js). Wire `ManagerTab.styles` into `src/styles.ts` `GlobalStyles` next to
|
||||
Dashboard/Diagnostic. Styles use theme vars WITH fallbacks; CBI selector is
|
||||
`#cbi-netshift-manager-_mount_node > div` + hide `#cbi-netshift-manager > h3`.
|
||||
- LIFECYCLE: mirror diagnostic exactly but guard re-init with module-level
|
||||
`*Registered`/`*Initialized`/`*Mounted` booleans since the
|
||||
lazy-mount listener can fire repeatedly. `onMount('manager-status')` →
|
||||
`registerLifecycleListeners()` (subscribe on `tabService.current==='manager'`)
|
||||
→ `onPageMount` subscribes store + renders + fetches systemInfo;
|
||||
`onPageUnmount` resets `['managerActions','managerChecks']`.
|
||||
- INSTALLED-NOW / LATEST-ON-DEMAND: installed versions come from
|
||||
`diagnosticsSystemInfo` (reuse the diagnostic `getSystemInfo()`→store slice);
|
||||
latest is fetched ONLY on a "Check update" click. Pure card builder
|
||||
`cards.ts:getComponentCards(systemInfo, checks)` + `getCheckTag(status)` +
|
||||
`isSingBoxInstalled` are DOM/store-free (import only `normalizeCompiledVersion`
|
||||
leaf + `NetShift` types) → unit-testable WITHOUT the MutationObserver collect
|
||||
crash. Controller maps descriptors→DOM+click handlers. 3 cards: netshift,
|
||||
sing_box_stock, sing_box_extended; inactive core → "Not installed" + switch.
|
||||
- BACKEND CONTRACT (task-017, STABLE): both SING-BOX checks (`check_update`
|
||||
extended / `check_update_stable` stock) return `{success,current_version,
|
||||
latest_version,status:"latest"|"outdated"|"dev"|"not_installed"}`. The
|
||||
PRE-EXISTING `singBoxComponentAction('check_update')` only parsed `{success,
|
||||
version,message}` (DROPPED status/latest) — do NOT route the manager check
|
||||
through it. Added ONE `singBoxCheckUpdate(action)` method parsing the FULL
|
||||
contract via a pure `parseComponentCheckUpdate.ts` (types-only import, status
|
||||
whitelisted). Install/switch reuse the existing async
|
||||
`singBoxComponentAction('install_*')` + `pollSingBoxComponentAction`.
|
||||
- C1 (review fix) — THERE IS NO `netshift:check_update` BACKEND ACTION. NetShift
|
||||
latest comes ONLY from `get_system_info.netshift_latest_version`. So the
|
||||
NetShift card's "Check update" must NOT route through `singBoxCheckUpdate` (that
|
||||
would run the sing-box EXTENDED check and write its status into
|
||||
`managerChecks.netshift` → wrong). Fix: give the NetShift check a DISTINCT
|
||||
`kind:'check_netshift'` (no `backendAction`) so `handleManagerAction` routes it
|
||||
to `runNetshiftCheck`, which RE-FETCHES systemInfo + `resetCheckResult
|
||||
('netshift')` and derives the badge/toast from installed-vs-latest. NetShift
|
||||
status is derived PURELY from systemInfo (`netshiftStatus(systemInfo)` no longer
|
||||
reads `managerChecks.netshift`). Regression guards in cards.test.js: NetShift
|
||||
action kind is `check_netshift`, has NO `backendAction`, and status ignores a
|
||||
bogus `managerChecks.netshift`. LESSON: when a card's "latest" comes from a
|
||||
DIFFERENT source than its siblings, give it its own action kind so the shared
|
||||
dispatcher can't misroute it to the wrong backend method.
|
||||
- S1 (review fix) — keep ONE check method per concern: removed the dead
|
||||
`singBoxCheckUpdateStable()` (0 callers; controller uses
|
||||
`singBoxCheckUpdate('check_update_stable')`). No dead exports.
|
||||
- M2 (review fix) — `ManagerComponentKey` defined ONCE in `tabs/manager/cards.ts`
|
||||
(the pure module) and `export type`-re-exported from `store.service.ts` (which
|
||||
`import type`s it) so store consumers keep their path; safe because cards.ts
|
||||
imports NO store (no cycle). M1 (self-update timeout reusing 'Core switch
|
||||
timed out' wording) left as-is — non-blocking, and the shared
|
||||
`pollSingBoxComponentAction` wording is approved for the core-switch path.
|
||||
- SELF-UPDATE lenient polling: `netshiftSelfUpdate()` starts
|
||||
`component_action_async netshift self_update`; once a `job_id` is returned, the
|
||||
poll `fetchStatus` callback SWALLOWS exec/parse errors and returns a synthetic
|
||||
`{running:true}` (instead of `null`, which the pure poll treats as terminal
|
||||
failure). This prevents the mid-job `/usr/bin/netshift` binary swap from
|
||||
misreporting success as failure; `MAX_POLLS` still bounds it. On success: a
|
||||
warning-style toast then `window.location.reload()` after 1200ms.
|
||||
- MOVED core-switch OUT of Diagnostics: removed `handleInstallSingBox` +
|
||||
`singBoxInstall`/`singBoxExtended` from `diagnostic/initController.ts` and the
|
||||
`singBoxInstall` block + props from `renderAvailableActions.ts`, and the
|
||||
`singBoxInstall` slice from BOTH `StoreType` and `diagnostic.store.ts`. Net
|
||||
i18n effect: msgids "Install stable"/"Install extended" were DROPPED (now-dead)
|
||||
and replaced by manager's "Switch to stable"/"Switch to extended"/"Install %s"
|
||||
— so the ru.po diff is NOT purely additive this time (2 removed, ~16 added);
|
||||
that is correct. `renderRotateCcwIcon24` stays imported (still used by Restart).
|
||||
- i18n: 16 new ru msgstrs filled in SOURCE `locales/netshift.ru.po`, then
|
||||
`node distribute-locales.js`. "%s" placeholder strings ("Install %s") are
|
||||
single literals (no concat); progress/result toasts concatenate the version
|
||||
OUTSIDE `_()` (`` `${_('NetShift updated, version:')} ${v}` ``). Ran the
|
||||
locales scripts via `node {extract-calls,generate-pot,generate-po ru,
|
||||
distribute-locales}.js`. yarn here was classic 1.22.22 (NOT corepack) so
|
||||
`yarn ci` was safe — verified yarn.lock unchanged + no `.yarn/.yarnrc.yml`.
|
||||
- main.js: +756/-… runtime diff (new tab + methods + core-switch removal),
|
||||
second build idempotent (byte-identical), banner + `return baseclass.extend`
|
||||
intact, only `ManagerTab` added to the export block (pure helpers imported by
|
||||
direct path → no leak). `tsc --noEmit` flags ONE pre-existing error in
|
||||
`getNetshiftVersionRow.test.ts` (sing_box_extended optionality) — NOT in CI
|
||||
(yarn ci = format/lint/vitest/build, no tsc), pre-existing, ignore.
|
||||
|
||||
## Drop stale nft "mangle output counters" check (task-020b)
|
||||
|
||||
- Backend 020a removed `rules_mangle_output_counters` from `check_nft` JSON
|
||||
(router-output traffic is intentionally DIRECT now → that chain's counter is
|
||||
legitimately 0, so the non-zero assertion was a FALSE positive). New STABLE
|
||||
7-key shape: `{table_exist, rules_mangle_exist, rules_mangle_counters,
|
||||
rules_mangle_output_exist, rules_proxy_exist, rules_proxy_counters,
|
||||
rules_other_mark_exist}` — `rules_mangle_output_exist` KEPT.
|
||||
- FE removal touched exactly 2 source files: `runNftCheck.ts` (drop the field
|
||||
from the allGood `&&` chain, the atLeastOneGood `||` chain, and its `items[]`
|
||||
row — keep the "Rules mangle output exist" row) + `types.ts`
|
||||
`NftRulesCheckResult` (drop `rules_mangle_output_counters: 0 | 1;`).
|
||||
- main.js: runtime diff is the removed Boolean()s + the dropped items[] row;
|
||||
second build BYTE-IDENTICAL (idempotent), banner + `return baseclass.extend`
|
||||
intact; `grep -c rules_mangle_output_counters main.js` == 0.
|
||||
- locales: ran `node {extract-calls,generate-pot,generate-po ru,
|
||||
distribute-locales}.js` (NOT yarn → no corepack). The unused
|
||||
`_('Rules mangle output counters')` msgid dropped cleanly from ALL 5 catalogs
|
||||
(calls.json, locales/netshift.{pot,ru.po}, po/{templates/netshift.pot,
|
||||
ru/netshift.po}). msgid-level delta = PURELY a removal (1 removed, 0 added);
|
||||
"Rules mangle output exist" stays. generate-po reported 325/323 (2 stale
|
||||
translations retained in source ru.po — harmless, additive-preserving).
|
||||
- yarn was classic 1.22.22 → `yarn ci` safe; verified `git diff --exit-code --
|
||||
yarn.lock` clean and NO `.yarn`/`.yarnrc.yml`. No vitest referenced the field.
|
||||
|
||||
## validateUrl accepts IP host + subscription_insecure checkbox (task-021a)
|
||||
|
||||
- `validateUrl.ts` REWRITE: old regex required an ALPHA TLD so an IPv4/IPv6 host
|
||||
was rejected ("Invalid URL format"). New approach mirrors `validateSocksUrl`:
|
||||
keep the protocol check (default `['http:','https:']`), then a pure
|
||||
module-private `extractHost(url)` strips `scheme://` (indexOf '://'), the
|
||||
`/path?query#frag` (`rest.search(/[/?#]/)` — first of `/ ? #`), optional
|
||||
`userinfo@` (`lastIndexOf('@')`), and the `:port`. BRACKETED IPv6:
|
||||
if `rest.startsWith('[')`, return the substring between `[` and the first `]`
|
||||
(so `[2001:db8::1]:2096` → `2001:db8::1`); else strip trailing `:port` via
|
||||
`lastIndexOf(':')`. Then accept if `validateIPV4(host).valid ||
|
||||
validateIPV6(host).valid || validateDomain(host).valid`. Kept the 3 existing
|
||||
messages verbatim (`Invalid URL format`, the protocol message, `Valid`).
|
||||
- NB `validateIPV6` ALREADY unwraps brackets internally (`.replace(/^\[/,'')`),
|
||||
but extractHost must unwrap anyway so the `:port` after `]` is dropped before
|
||||
the validator sees it. `extractHost` is NOT barrel-exported (module-private) →
|
||||
no `main.*` leak; main.js diff is +30/-4 (the helper + the host-check), second
|
||||
build BYTE-IDENTICAL, banner + `return baseclass.extend({` intact.
|
||||
- This single fix covers ALL FOUR callers (subscription_url, urltest_testing_url,
|
||||
remote_domain_lists, remote_subnet_lists) — callers unchanged.
|
||||
- TESTS: `validateDomain` accepts a trailing path (`example.com/path` regex has
|
||||
`(?:\/[^\s]*)?$`), so existing domain-with-path valid cases still pass through
|
||||
the domain branch. Added valid: `https://91.199.111.52:2096/sub/abc`,
|
||||
`http://10.0.0.1/x`, `https://[2001:db8::1]:2096/sub`. Added invalid:
|
||||
`https://999.1.1.1/x` (bad IPv4 → not domain either), `ftp://1.2.3.4` (protocol
|
||||
fails first), `https://` (extractHost → '' → "Invalid URL format"). Kept
|
||||
`https://google` invalid (no TLD, not an IP).
|
||||
- section.js (HAND-WRITTEN, NOT bundled → 0 in main.js): added `form.Flag`
|
||||
`subscription_insecure` right AFTER subscription_url (~line 113), default `"0"`,
|
||||
`rmempty=false`, `depends({connection_type:'proxy',proxy_config_type:
|
||||
'subscription'})` exactly like its siblings (no `subscription_user_agent` exists
|
||||
here despite the spec mention). Multi-sentence description = three `_()` calls
|
||||
joined with `+ " " +` OUTSIDE `_()` (F-02 rule). UCI contract option name
|
||||
`subscription_insecure` (0|1) consumed by backend 021b.
|
||||
- locales: `node {extract-calls,generate-pot,generate-po ru,distribute-locales}.js`
|
||||
(NOT yarn). 4 new msgids (1 label + 3 description sentences), PURELY additive
|
||||
(4 added, 0 removed at msgid level). Filled RU in SOURCE `locales/netshift.ru.po`
|
||||
then distributed → po/ru + po/templates byte-identical to source. Only the PO
|
||||
HEADER msgstr stays empty (`grep -nB1 'msgstr ""'` shows just line 6/7).
|
||||
- yarn classic 1.22.22 → `yarn ci` green (format/lint --max-warnings=0/471 tests/
|
||||
build); verified yarn.lock unchanged + NO `.yarn`/`.yarnrc.yml`. The
|
||||
`netshift/files/**` + `tests/**` changes in git status are 021b (other agent),
|
||||
not mine.
|
||||
|
||||
## subscription_url → form.DynamicList (multi-URL) (task-023)
|
||||
|
||||
- Converted `subscription_url` from `form.Value` to `form.DynamicList` in
|
||||
section.js (~88-111), modelled EXACTLY on `remote_domain_lists` (:721-742):
|
||||
same per-row validate (`!value||value.length===0 → true`, else
|
||||
`main.validateUrl(value)`), `rmempty=true` (was `false`; the empty-row guard
|
||||
already short-circuited so emptiness was never enforced; backend keeps the
|
||||
"no URL" guard). Kept option name `subscription_url`, depends
|
||||
`{connection_type:'proxy',proxy_config_type:'subscription'}`, placeholder
|
||||
`https://example.com/api/sub`. Title → plural `_("Subscription URLs")`;
|
||||
description → single literal `_("Add one or more subscription URLs to fetch
|
||||
proxy configurations from. All feeds are downloaded and merged.")`.
|
||||
- types.ts:120 `subscription_url: string` → `string[]` (kept required, matches
|
||||
sibling list fields `selector_proxy_links`/`urltest_proxy_links`).
|
||||
- PURE TYPE-ONLY CHANGE: nothing in the FE reads `subscription_url` back (verified
|
||||
repo-wide) → `tsup` build produced ZERO main.js diff (confirmed via
|
||||
`git diff --exit-code main.js`). This is correct, NOT a missed rebuild. Still
|
||||
ran the build to confirm. (Same lesson as the type-only note in i18n section.)
|
||||
- locales: `node {extract-calls,generate-pot,generate-po ru,distribute-locales}.js`
|
||||
(NOT yarn → no corepack). msgid delta = clean SWAP: removed "Subscription URL"
|
||||
+ "Enter the subscription URL...provider"; added "Subscription URLs" + the new
|
||||
merged-feeds description. Filled 2 ru msgstr in SOURCE locales/netshift.ru.po
|
||||
("URL подписок" / "Добавьте один или несколько URL подписок...объединяются.")
|
||||
then distribute → po/ru + po/templates byte-identical to source (verified via
|
||||
diff). Only header msgstr empty (line 7). 5 catalog files touched: calls.json,
|
||||
locales/netshift.{pot,ru.po}, po/{templates/netshift.pot,ru/netshift.po}.
|
||||
- yarn classic 1.22.22 again but ran inner gate via node_modules/.bin
|
||||
(prettier/eslint/vitest/tsup) to be safe; yarn.lock unchanged, no .yarn/.yarnrc.
|
||||
|
||||
## UI design-system foundation: .card + tokens + toasts (task-024)
|
||||
|
||||
- DESIGN TOKENS (STABLE — task-025/026 reference these; do NOT rename) defined
|
||||
in `src/styles.ts` `GlobalStyles` on `:root, .cbi-map`:
|
||||
`--ns-card-border` (var(--background-color-low, lightgray)),
|
||||
`--ns-card-border-width` (2px), `--ns-card-radius` (4px), `--ns-gap` (10px),
|
||||
`--ns-card-padding` (var(--ns-gap)), `--ns-success`/`--ns-warning`/`--ns-error`/
|
||||
`--ns-info` (layered over success/warn/error-color-medium + primary-color-high
|
||||
with hex fallbacks #28a745/#f0ad4e/#dc3545/#2196f3).
|
||||
- `.card` primitive = `border: var(--ns-card-border-width) solid
|
||||
var(--ns-card-border); border-radius: var(--ns-card-radius); padding:
|
||||
var(--ns-card-padding); min-width:0`. Mirrors Manager's component card EXACTLY
|
||||
(2px/4px/10px/min-width:0) — that's the standardised look, NOT the 1px/8px from
|
||||
the spec's illustrative example.
|
||||
- CASCADE RULE: `.card` MUST be defined in GlobalStyles BEFORE the
|
||||
`${DashboardTab.styles}${DiagnosticTab.styles}${ManagerTab.styles}`
|
||||
interpolations. The per-tab colored-border MODIFIERS (`.pdk_diagnostic_alert
|
||||
--warning/--error/--loading/--success`, `__wiki--warning/--error`, outbound-grid
|
||||
`--active`/`--selectable:hover`) are same-specificity single-class rules that
|
||||
win ONLY via source order. Since injectGlobalStyles emits ONE `<style>` with
|
||||
GlobalStyles, and the template renders tokens+`.card` first THEN the interpolated
|
||||
tab CSS, the modifiers correctly override `.card`'s neutral border. (File
|
||||
byte-offset of `.card` in main.js is LATER than the modifiers because
|
||||
`DashboardTab.styles` is a separate `var stylesN` module — but runtime template
|
||||
concatenation order is what matters, and that's correct.)
|
||||
- REFACTOR PATTERN: removed the duplicated `border/border-radius/padding` (and
|
||||
manager's `min-width:0`) from the per-tab `styles.ts`, added `class:'card …'` in
|
||||
the RENDER `.ts`. Card boxes touched (more than the spec's "4" — there were
|
||||
these render sites): dashboard renderWidget (3 states), renderSections
|
||||
(failed/loading/default outbound-section + outbound-grid item), diagnostic
|
||||
renderWikiDisclaimer (className array — prepend 'card'), renderAvailableActions,
|
||||
renderSystemInfo, renderCheckSection (all 5 alert states incl. `--skipped` which
|
||||
has NO modifier so it relies on `.card`), manager initController component.
|
||||
`.card` adds `min-width:0` to dashboard/diagnostic boxes (was absent) — harmless
|
||||
overflow hardening, visually identical.
|
||||
- showToast union widened to `'success'|'error'|'warning'|'info'`
|
||||
(showToast.ts:3). Added `.toast-warning`(--ns-warning) + `.toast-info`(--ns-info)
|
||||
CSS; converted existing `.toast-success/.toast-error` to `var(--ns-success/error,
|
||||
#hex)` (themeable, same fallback hex → visually identical). The
|
||||
PREVIOUS memory note "showToast type is only success|error — use 'success' for
|
||||
in-progress" is now SUPERSEDED: use `'info'` for in-progress, `'warning'` for
|
||||
long/destructive-ish. Converted the 2 abuse sites in manager/initController.ts I
|
||||
was already in: "Switching sing-box core…"→'info', "Updating NetShift…page will
|
||||
reload"→'warning'. DEFERRED (not in touched files / debatable): manager line
|
||||
~155 "Latest version is unknown" still 'success' (check-result, not in-progress);
|
||||
diagnostic/initController.ts had only 'error' toasts (nothing to fix).
|
||||
- RAW BUTTON KILLED: dashboard renderSections.ts "Test latency" raw
|
||||
`<button class="btn">` → `renderButton({text:_('Test latency'), onClick:
|
||||
()=>testLatency(), classNames:['dashboard-sections-grid-item-test-latency']})`.
|
||||
renderButton already adds `btn`, so only the custom class goes in classNames.
|
||||
- IMPORT-ORDER MAIN.JS CHURN (IMPORTANT): adding `import {renderButton} from
|
||||
'../../../../partials'` into the DASHBOARD subtree (which previously never
|
||||
imported the global `src/partials` barrel) makes esbuild REORDER ~every bundled
|
||||
module block → a huge SYMMETRIC main.js diff (~1600/1600 lines) that is PURELY
|
||||
cosmetic module reordering. Verified safe: build is IDEMPOTENT (same md5 twice),
|
||||
banner intact, `return baseclass.extend({` intact, and the export-symbol SET is
|
||||
BYTE-IDENTICAL to HEAD (diff /tmp/exports_old vs new = empty) → no barrel leak,
|
||||
no new public API. Direct-path import (`…/partials/button/renderButton`) barely
|
||||
reduced churn — the reorder is inherent to introducing the cross-subtree dep, so
|
||||
I kept the barrel import for consistency with the 3 diagnostic callers. When a
|
||||
reviewer sees a giant main.js diff for a tiny TS change, CHECK export-set
|
||||
equality + idempotency before worrying.
|
||||
- TAB REORDER: netshift.js (hand-written, edit directly) — moved the Dashboard
|
||||
`form.TypedSection` block to FIRST. New order: Dashboard · Sections · Settings ·
|
||||
Component Manager · Diagnostics. ONLY block order changed; all 5 sections + their
|
||||
cfgsections/anonymous/addremove wiring identical. coreService/TabService track by
|
||||
`data-tab` (the active section name e.g. `current==='dashboard'`), NOT
|
||||
registration index (tab.service.ts getActiveTabId reads `.cbi-tab:not(
|
||||
.cbi-tab-disabled)` dataset.tab; dashboard initController keys on
|
||||
`tabService.current==='dashboard'`) → reorder is SAFE, tracking unaffected.
|
||||
- VISUAL VERIFY caveat: no chromium available in this env (playwright launch
|
||||
failed: chrome not found), so screenshots were NOT possible. Verified instead by
|
||||
CSS-cascade reasoning + programmatic checks: `.card` precedes modifiers in the
|
||||
runtime-concatenated GlobalStyles, no `background-color-low` base border remains
|
||||
in any per-tab styles.ts (all neutral borders now come from `.card`), colored
|
||||
modifiers keep their 2px width matching `.card`. FLAG: visual confirmation is
|
||||
reasoned, not screenshotted.
|
||||
- yarn classic 1.22.22; ran gate via node_modules/.bin (prettier --write src clean
|
||||
/ eslint --max-warnings=0 / vitest 471 pass / tsup build). yarn.lock unchanged,
|
||||
no `.yarn`/`.yarnrc.yml`. No locales change (no NEW user-facing literals — the
|
||||
switching/updating toast strings already existed).
|
||||
|
||||
## task-025 — section.js → 4 native CBI tabs (taboption)
|
||||
|
||||
- CBI native tabs: `section.tab('name', _('Title'), _('descr'))` defines a tab,
|
||||
then EVERY field MUST be `section.taboption('name', form.X, 'key', ...)`. HARD
|
||||
RULE confirmed: once a section has `.tab()`, any leftover `section.option(...)`
|
||||
silently renders nothing. Verified count: 36 taboption, 0 plain option (the
|
||||
only `section.option(` grep hit was my own comment line).
|
||||
- Conversion is mechanical & low-risk: only the constructor call line changes
|
||||
(`section.option(\n form.X,` → `section.taboption(\n "tab",\n form.X,`).
|
||||
All `.depends()` (33), `.validate` (17), `.value()`, defaults, placeholders,
|
||||
and the `community_lists.onchange` (REGIONAL_OPTIONS/ALLOWED_WITH_RUSSIA_INSIDE
|
||||
/DOMAIN_LIST_OPTIONS/getUIElement) stayed byte-identical. depends() works
|
||||
across tabs; an all-depends-hidden tab auto-hides from the strip (Subscription
|
||||
tab hides for proxy/url) — desired, no extra code.
|
||||
- `widgets.DeviceSelect` (`interface`) works fine inside a taboption — just pass
|
||||
the widget class as the 2nd arg after the tab name.
|
||||
- Tab map (4 tabs, 36 fields): connection=11, subscription=10, routing=12,
|
||||
advanced=3.
|
||||
- SMART-LIST UNIFICATION: did the LOW-RISK visual grouping (NOT a single-widget
|
||||
merge). Kept all 4 UCI keys + 2 *_list_type selectors. Achieved "one control"
|
||||
feel by renaming the two list-type selector TITLES to group headings
|
||||
("Custom domains"/"Custom subnets") with descriptions naming the modes;
|
||||
depends() already shows only the chosen input below. Deeper merge deferred
|
||||
(would risk UCI/validator changes). NOTE: renaming a selector title drops its
|
||||
old msgid from catalogs — fill the new ones.
|
||||
- RU-HARDCODE FIX: `subscription_group_by_countries` had `_("Группировать по
|
||||
странам")` as the SOURCE literal (msgid). Replaced with English `_("Group by
|
||||
countries")` + English descr; moved the Russian into the ru.po msgstr. After
|
||||
this the Cyrillic appears ONLY as msgstr, never as msgid.
|
||||
- section.js is NOT in the `yarn ci` prettier scope (CI formats only `src`).
|
||||
section.js uses DOUBLE QUOTES (LuCI convention) and does NOT pass the project
|
||||
`.prettierrc` (singleQuote) — confirmed the ORIGINAL also failed prettier.
|
||||
So: match the file's existing double-quote/2-space style; do NOT run prettier
|
||||
on section.js (it would fight the whole file).
|
||||
- i18n flow: `node extract-calls.js && node generate-pot.js && node
|
||||
generate-po.js ru && node distribute-locales.js`. generate-po keys by msgid &
|
||||
carries forward old msgstr; NEW/renamed msgids land empty → fill them in
|
||||
fe-app-netshift/locales/netshift.ru.po, then RE-RUN distribute-locales.js to
|
||||
copy into luci-app-netshift/po/{ru/netshift.po, templates/netshift.pot}.
|
||||
Verify byte-consistency with `diff -q` (both fe↔luci pairs). 13 new strings
|
||||
this task; all ru filled; 0 empty msgstr after.
|
||||
- main.js drift rule confirmed: section.js-only + catalog changes need NO main.js
|
||||
rebuild. I touched styles.ts so rebuilt — the ONLY main.js delta vs the
|
||||
task-024 baseline was my new CSS block (#cbi-netshift-section
|
||||
.cbi-section-node-tabbed card + ul.cbi-tabmenu margin). Build reproducible.
|
||||
- styles.ts: reused task-024 --ns-* tokens; added `#cbi-netshift-section
|
||||
.cbi-section-node-tabbed` (card border/radius/padding) + `ul.cbi-tabmenu`
|
||||
margin. Existing h3-hide (`> h3:nth-child(1)`) and remove-button hack
|
||||
(`> .cbi-section-remove { margin-bottom:-32px }`) left intact (new rules added
|
||||
after them; both still valid — remove button is a direct child, unaffected by
|
||||
the tabbed pane styling).
|
||||
- VISUAL VERIFY caveat persists: no browser in env. Confirmed structurally
|
||||
(taboption count/mapping, depends/validate counts == original, onchange grep
|
||||
intact, catalog diff). FLAG for human: actual tab-strip/card rendering +
|
||||
auto-hide behaviour of the Subscription/Advanced tabs not screenshot-verified.
|
||||
|
||||
## task-026 — settings.js → 5 native CBI tabs (taboption)
|
||||
|
||||
- Same mechanics as task-025. Converted ALL 27 settings options to
|
||||
`section.taboption('tab', form.X, 'key', …)`. Verified: 27 taboption, 0 plain
|
||||
`section.option(` (the 1 grep hit is my comment line). Tab map (5 tabs, 27):
|
||||
dns(6)=dns_type,dns_server,bootstrap_dns_server,dns_via_outbound,
|
||||
dns_outbound_section,dns_rewrite_ttl · network(6)=source_network_interfaces,
|
||||
enable_output_network_interface,output_network_interface,
|
||||
enable_badwan_interface_monitoring,badwan_monitored_interfaces,
|
||||
badwan_reload_delay · lists(4)=update_interval,download_lists_via_proxy,
|
||||
download_lists_via_proxy_section,routing_excluded_ips · yacd(3)=enable_yacd,
|
||||
enable_yacd_wan_access,yacd_secret_key · advanced(8)=disable_quic,
|
||||
dont_touch_dhcp,exclude_ntp,block_doh,enable_ipv6,config_path,cache_path,
|
||||
log_level.
|
||||
- YACD DECISION: kept as its OWN tab (3 fields), NOT folded into Advanced.
|
||||
Rationale: self-contained feature w/ clean depends() chain
|
||||
(enable_yacd→wan_access→secret_key); folding into an 11-field Advanced would
|
||||
recreate the wall. Tab title is `_("Dashboard")` (already-existing msgid),
|
||||
internal tab name "yacd". Documented.
|
||||
- All 7 depends() preserved verbatim (only line order changed — irrelevant):
|
||||
dns_outbound_section dep dns_via_outbound=1; output_network_interface dep
|
||||
enable_output_network_interface=1; badwan_monitored_interfaces +
|
||||
badwan_reload_delay dep enable_badwan_interface_monitoring=1;
|
||||
enable_yacd_wan_access dep enable_yacd=1; yacd_secret_key dep
|
||||
enable_yacd_wan_access=1; download_lists_via_proxy_section dep
|
||||
download_lists_via_proxy=1. 6 validators + 3 custom widgets (2 DeviceSelect,
|
||||
1 NetworkSelect) intact; cfgvalue/load section-picker closures unchanged.
|
||||
- HELP TRIM: block_doh was a 4-paragraph `_()+ " " +_()…` concat. Replaced with
|
||||
ONE single-literal description "Block direct connections to known public DoH
|
||||
servers (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex) so apps cannot
|
||||
bypass router DNS filtering." The caveat ("enable only after switching to
|
||||
UDP/DoT") moved into the ADVANCED tab description (section.tab 3rd arg).
|
||||
enable_ipv6's 2-sentence concat LEFT inline (short, the 2nd sentence is a
|
||||
genuine 1-line caveat; not bloating) — documented choice.
|
||||
- BACKTICK TRAP IN styles.ts: GlobalStyles is a template literal. Putting a
|
||||
backtick inside a CSS COMMENT (e.g. `#cbi-... > h3`) prematurely closes the
|
||||
template → ESLint "Parsing error: ',' expected". NEVER use backticks anywhere
|
||||
inside the styles.ts CSS string, even in comments. (Cost me one lint cycle.)
|
||||
- styles.ts: added `#cbi-netshift-settings .cbi-section-node-tabbed` (card
|
||||
border/radius/padding/min-width:0) + `#cbi-netshift-settings ul.cbi-tabmenu`
|
||||
(margin-bottom:var(--ns-gap)) — exact mirror of the task-025 section block,
|
||||
reusing task-024 --ns-* tokens (did NOT redefine tokens). The existing
|
||||
`#cbi-netshift-settings > h3 { display:none }` rule stays valid (added new
|
||||
rules after it). main.js delta = exactly these 2 CSS rules; build IDEMPOTENT
|
||||
(md5 a7300a2… across 3 builds), banner + `return baseclass.extend` intact,
|
||||
no new export symbol (only-loss vs HEAD is task-024's `styles` leak removal,
|
||||
not mine).
|
||||
- i18n: msgid delta = 9 added (tab titles "DNS"/"Network"/"Lists & Updates" —
|
||||
"Dashboard"+"Advanced" already existed; 4 tab descriptions; 1 reworded
|
||||
block_doh) / 4 removed (old block_doh fragments). Filled 9 ru msgstr in SOURCE
|
||||
locales/netshift.ru.po then `node distribute-locales.js`. fe↔luci ru.po AND
|
||||
pot byte-identical (diff -q); all LF; valid UTF-8 w/ Cyrillic; 0 empty
|
||||
non-header msgstr. Ran scripts via `node {extract-calls,generate-pot,
|
||||
generate-po ru,distribute-locales}.js` (generate-po reported 335/339 but 9
|
||||
were genuinely new — its count metric differs).
|
||||
- yarn classic 1.22.22; ran gate via node_modules/.bin (prettier/eslint/vitest/
|
||||
tsup). yarn.lock unchanged, no .yarn/.yarnrc.yml. NB: working tree already
|
||||
carried UNCOMMITTED task-024 + task-025 changes (showToast, dashboard/diag/
|
||||
manager styles+renders, section.js, netshift.js, #cbi-netshift-section CSS) —
|
||||
so `git diff -- src` is large but only my settings block + the 4 catalogs +
|
||||
main.js belong to task-026. format reported all-unchanged → no new churn.
|
||||
|
||||
## task-030 — NetShift update check ON-DEMAND (retires C1's systemInfo-refresh)
|
||||
|
||||
- REVERSES task-018's C1 decision. task-029 (backend, APPROVED) ADDED a real
|
||||
`component_action netshift check_update` action returning the STANDARD check
|
||||
JSON `{success,current_version,latest_version,status}` (v-normalized
|
||||
server-side, SAME shape as the sing-box cores) AND removed the latest-fetch
|
||||
from `get_system_info` (now returns `netshift_latest_version:"unknown"`). So
|
||||
the NetShift card is now a TRUE peer of the cores: on-demand check writes
|
||||
`managerChecks.netshift`, mount does NO network check.
|
||||
- SHELL METHOD: added `netshiftCheckUpdate()` to `methods/shell/index.ts` —
|
||||
copy of `singBoxCheckUpdate` but args `['component_action','netshift',
|
||||
'check_update']`, parsed by the EXISTING `parseComponentCheckUpdate`, returns
|
||||
`NetShift.ComponentCheckUpdateResult`. SYNC path (fast call), timeout 600000.
|
||||
It's a PROPERTY on `NetShiftShellMethods` (not a top-level export) → NO new
|
||||
symbol in the baseclass.extend export block (verified byte-identical to HEAD).
|
||||
- runNetshiftCheck (manager/initController.ts): now MIRRORS runSingBoxCheck
|
||||
exactly — call `netshiftCheckUpdate()`, `if(!parsed.success)` error toast +
|
||||
return, `status=parsed.status??null`, `setCheckResult('netshift',status,
|
||||
parsed.latest_version||'')`, `showToast(getCheckToastMessage(status),
|
||||
'success')`, catch→error toast, finally→reset loading. STOPPED calling
|
||||
`fetchSystemInfo()`+`resetCheckResult` as the "check".
|
||||
- cards.ts: `netshiftStatus(systemInfo, check)` now RETURNS `check.status`
|
||||
(the on-demand result; null until checked → neutral). KEPT the dev guard
|
||||
(`normalizeCompiledVersion(...)==='dev' → null`). REMOVED the
|
||||
`installed===latest` string compare AND the systemInfo.netshift_latest_version
|
||||
dependency. `netshiftCard` takes the check too; "Install %s" `latest` now
|
||||
comes from `check.latest_version`. `getComponentCards` passes `checks.netshift`
|
||||
to `netshiftCard`. The `check_netshift` kind NOW carries
|
||||
`backendAction:'check_update'` (still a DISTINCT kind so the dispatcher routes
|
||||
it to runNetshiftCheck, never to the sing-box check method).
|
||||
- DIAGNOSTIC: NO code change needed. `getNetshiftVersionRow.ts` already treats
|
||||
`netshift_latest_version === 'unknown'` (and `'loading'`) as
|
||||
`!hasActualVersion` → returns the plain neutral row (no Outdated/Latest tag).
|
||||
Since task-029 makes the backend return "unknown", the row auto-degrades to
|
||||
neutral. Mount's `fetchSystemInfo()` is now network-free (backend change), so
|
||||
diagnostic entry triggers no GitHub call. Existing
|
||||
getNetshiftVersionRow.test.ts (passes real versions) stays green unchanged.
|
||||
- TESTS: rewrote the 5 NetShift cases in manager/tests/cards.test.js to derive
|
||||
from `managerChecks.netshift` instead of systemInfo: null-status→neutral+
|
||||
check_update; check 'outdated'→self_update + Install <check.latest_version>;
|
||||
'latest'→Latest badge; dev-build stays neutral even with a check 'outdated';
|
||||
systemInfo latest mismatch is IGNORED. 472 tests pass (cards 19).
|
||||
- LOCALES: removing the `runNetshiftCheck` body ORPHANED `_('Latest version is
|
||||
unknown')` (no longer referenced anywhere). Ran `node {extract-calls,
|
||||
generate-pot,generate-po ru,distribute-locales}.js`. msgid delta = PURELY the
|
||||
1 removed msgid (calls.json/pot/ru.po) + `#:` line-ref reshuffle + POT header
|
||||
date. fe↔luci pairs byte-identical (diff -q). No new strings added (all toasts
|
||||
reused existing msgids). generate-po reported 340/338 (2 stale retained).
|
||||
- main.js: +36/-26 runtime diff = exactly (new method block + netshiftStatus/
|
||||
Card signature change + runNetshiftCheck rewrite). IDEMPOTENT (md5
|
||||
9ce13d2… across 2 builds), banner + `return baseclass.extend({` intact,
|
||||
export block byte-identical to HEAD. yarn classic 1.22.22; ran via
|
||||
node_modules/.bin; yarn.lock unchanged, no .yarn/.yarnrc.yml.
|
||||
- FLAG (no browser in env): the neutral→checked card transition + toast were
|
||||
verified by reasoning + the pure cards.test.js, NOT screenshotted.
|
||||
|
||||
## task-032 — subscription_format_preference dropdown (Subscription tab)
|
||||
|
||||
- Added a `form.ListValue` `subscription_format_preference` in section.js
|
||||
(HAND-WRITTEN, NOT bundled) right AFTER `subscription_url` (~144-157),
|
||||
modelled EXACTLY on `subscription_update_interval`: `.value('auto',_('Auto'))`
|
||||
/ `.value('xray',_('Xray JSON (Happ)'))` / `.value('singbox',_('Sing-box'))`,
|
||||
`o.default='auto'`, same `depends({connection_type:'proxy',proxy_config_type:
|
||||
'subscription'})`. NO explicit `rmempty` — like the interval field, LuCI
|
||||
ListValue defaults `rmempty=true`, so selecting the default ('auto') does NOT
|
||||
write a spurious UCI value (matches backend task-031 which treats empty/
|
||||
unknown as auto). Single-literal `_()` description (no concat).
|
||||
- types.ts: added optional union `subscription_format_preference?: 'auto' |
|
||||
'xray' | 'singbox';` to `ConfigProxySubscriptionSection` (after
|
||||
subscription_url). Pure type-only → erased at build.
|
||||
- BACKEND CONTRACT (task-031, in working tree): UCI option name EXACTLY
|
||||
`subscription_format_preference`, values auto/xray/singbox; netshift bin reads
|
||||
it (`uci -q get …subscription_format_preference`, empty→auto). Confirmed via
|
||||
grep before editing.
|
||||
- main.js: NO diff (section.js hand-written + type-only types.ts), like
|
||||
task-023. Build still run to confirm; `git diff --stat main.js` empty.
|
||||
- locales: `node {extract-calls,generate-pot,generate-po ru,distribute-
|
||||
locales}.js`. msgid delta PURELY ADDITIVE — 4 added (Auto / Subscription
|
||||
format / Xray JSON (Happ) / the description), 0 removed; "Sing-box" REUSED an
|
||||
existing msgid (so generate-po reported 339/342, only 3 truly-new beyond the
|
||||
reused one). Filled 4 ru msgstr in SOURCE locales/netshift.ru.po (Auto→Авто,
|
||||
Subscription format→Формат подписки, Xray JSON (Happ)→Xray JSON (Happ),
|
||||
description translated) then distribute → po/ru + po/templates byte-identical
|
||||
to source (diff -q). Only header msgstr empty. 5 catalog files touched.
|
||||
- yarn classic 1.22.22; ran gate via node_modules/.bin (prettier --write src /
|
||||
eslint src --ext .ts,.tsx --max-warnings=0 / vitest 472 pass / tsup). format
|
||||
diff on src = ONLY my 1 types.ts line (no churn). yarn.lock unchanged, no
|
||||
.yarn/.yarnrc.yml. FLAG (no browser): dropdown rendering/auto-hide not
|
||||
screenshotted — verified structurally.
|
||||
|
||||
## task-040 — "Clear subscription cache" button in Diagnostics (async)
|
||||
|
||||
- BACKEND CONTRACT (task-039, APPROVED): `component_action subscription
|
||||
clear_cache` deletes all subscription caches + redownloads (restarts service
|
||||
on change), driven via the EXISTING async job machinery
|
||||
`component_action_async subscription clear_cache` → `{success,job_id,message}`,
|
||||
poll `component_action_status <job>`. ACL already allows `/usr/bin/netshift`
|
||||
exec — NO ACL change. Action strings are EXACTLY component='subscription',
|
||||
action='clear_cache'.
|
||||
- SHELL METHOD: added `clearSubscriptionCache()` to `methods/shell/index.ts` as
|
||||
a COPY of `netshiftSelfUpdate`'s start-then-poll shape BUT with the STRICT
|
||||
(non-lenient) poll callback used by `singBoxComponentAction` install path
|
||||
(return `null` on empty stdout — no binary swap here, so a parse/exec failure
|
||||
IS terminal). args `['component_action_async','subscription','clear_cache']`,
|
||||
REUSES the component-agnostic `pollSingBoxComponentAction` (NO new poll loop).
|
||||
Returns `SingBoxComponentActionResult {success,version?,message?}`. It's a
|
||||
PROPERTY on `NetShiftShellMethods` → NO new top-level export symbol (the
|
||||
baseclass.extend export block is byte-identical to HEAD). NO new
|
||||
`AvailableMethods` enum entry needed — the existing async actions pass
|
||||
`'component_action_async'`/`'component_action_status'` + the component/action
|
||||
as RAW string-literal args (not enum members), so I mirrored that exactly.
|
||||
- HANDLER: `handleClearSubscriptionCache` in diagnostic/initController.ts mirrors
|
||||
`handleRestart`'s service-mutation idiom + globalCheck's toast idiom: set
|
||||
`clearSubscriptionCache.loading=true` → `showToast(_('Clearing subscription
|
||||
cache and re-downloading… this may take a minute'),'info')` → await the async
|
||||
method → success→`showToast(...,'success')` else logger.error+error toast →
|
||||
catch→logger.error+error toast → finally→`await fetchServicesInfo()` +
|
||||
loading=false + `store.reset(['diagnosticsChecks'])`. NB: did NOT use
|
||||
handleRestart's `setTimeout(...,5000)` — the async method ALREADY polls to
|
||||
completion (service restart finished by the time it resolves), so refresh
|
||||
immediately in finally. Wired into `renderDiagnosticAvailableActionsWidget`
|
||||
(visible:true, disabled:atLeastOneServiceCommandLoading).
|
||||
- BUTTON: added `clearSubscriptionCache: ActionProps` to renderAvailableActions.ts
|
||||
+ an `insertIf(visible,[renderButton(...)])` block using `renderRotateCcwIcon24`
|
||||
(already imported for Restart — rotate/refresh fits "clear+redownload"; the
|
||||
icon set has NO trash icon). Label `_('Clear subscription cache')`. No custom
|
||||
classNames (neutral btn, like globalCheck/viewLogs/showSingBoxConfig).
|
||||
- STORE: added `clearSubscriptionCache: { loading: boolean }` to
|
||||
`diagnosticsActions` in store.service.ts type AND
|
||||
`clearSubscriptionCache: { loading: false }` to initialDiagnosticStore in
|
||||
diagnostic.store.ts (after showSingBoxConfig in both).
|
||||
- i18n: 4 NEW msgids (PURELY additive): 'Clear subscription cache', 'Clearing
|
||||
subscription cache and re-downloading… this may take a minute', 'Failed to
|
||||
clear subscription cache' (used in BOTH the shell method fallback + handler →
|
||||
same msgid), 'Subscription cache cleared and re-downloaded'. NB the ellipsis is
|
||||
a real `…` char (U+2026), not three dots — kept literal-consistent fe↔ru. Ran
|
||||
`node {extract-calls,generate-pot,generate-po ru,distribute-locales}.js` (NOT
|
||||
yarn). generate-po reported 343/346 (its count metric undercounts; there were
|
||||
4 truly-new empty msgstr + the header). Filled ru in SOURCE
|
||||
locales/netshift.ru.po (Очистить кеш подписок / Очистка кеша подписок и
|
||||
повторная загрузка… это может занять минуту / Не удалось очистить кеш подписок
|
||||
/ Кеш подписок очищен и загружен заново), re-ran distribute → po/ru +
|
||||
po/templates byte-identical to source (diff -q). Only header msgstr empty.
|
||||
- main.js: REAL +98/-1 runtime diff (new method block + handler + button +
|
||||
widget wiring). IDEMPOTENT (md5 aa89dfc… across 2 builds), banner +
|
||||
`return baseclass.extend({` intact, top-level export block byte-identical to
|
||||
HEAD (no barrel leak — clearSubscriptionCache is a NetShiftShellMethods
|
||||
property). Confirmed action args in main.js are exactly
|
||||
`["component_action_async","subscription","clear_cache"]` + poll via
|
||||
`component_action_status`.
|
||||
- NO new test: reused existing `pollSingBoxComponentAction` (already
|
||||
table-tested); the method+handler is wiring (DOM/store untestable in node
|
||||
env). vitest 472 pass unchanged.
|
||||
- yarn classic 1.22.22; ran gate via node_modules/.bin (prettier --check src
|
||||
clean / eslint src --ext .ts,.tsx --max-warnings=0 / vitest 472 / tsup).
|
||||
yarn.lock unchanged, no .yarn/.yarnrc.yml. Working tree also carried UNRELATED
|
||||
task-039 backend changes (netshift bin, updater.sh, tests/entrypoint.sh) +
|
||||
.opencode/agent edits — NOT mine. FLAG (no browser): button render + toast
|
||||
sequence verified by reasoning + the gate, NOT screenshotted.
|
||||
|
||||
## task-045 — universal subscription grouper (mode dropdown + prefix length)
|
||||
|
||||
- REPLACED the single `subscription_group_by_countries` form.Flag (section.js
|
||||
~190-201) with TWO taboptions in the SAME `subscription` tab (mandatory —
|
||||
tabbed section, a plain option() renders nothing):
|
||||
(1) `form.ListValue subscription_group_mode` — values off/country/prefix
|
||||
(`_("Off")`/`_("By country flag")`/`_("By name prefix")`), `o.default="off"`,
|
||||
`o.rmempty=false`, depends `{connection_type:"proxy",proxy_config_type:
|
||||
"subscription"}`; title `_("Subscription grouping")` + single-literal help.
|
||||
(2) `form.Value subscription_group_prefix_len` — title `_("Prefix length")`,
|
||||
`o.default="2"`, `o.datatype="and(uinteger,min(1))"`, `o.rmempty=false`,
|
||||
depends ADDS `subscription_group_mode:"prefix"` (3-key object) so it shows
|
||||
ONLY when mode=prefix. CBI cross-field depends within the same section/tab
|
||||
works fine; a fully-hidden field is OK.
|
||||
- CROSS-LAYER CONTRACT (task-044 backend, DONE): UCI options EXACTLY
|
||||
`subscription_group_mode` ∈ {off,country,prefix} default off, and
|
||||
`subscription_group_prefix_len` positive-int string default 2 (meaningful
|
||||
only when mode=prefix). Backend falls back to the LEGACY
|
||||
`subscription_group_by_countries` boolean ONLY when the new option is ABSENT
|
||||
→ the UI writes only the NEW options; NO JS migration written.
|
||||
- types.ts: swapped `subscription_group_by_countries?: '0'|'1'` →
|
||||
`subscription_group_mode?: 'off'|'country'|'prefix'` +
|
||||
`subscription_group_prefix_len?: string`. Grepped src first — NOTHING in TS
|
||||
reads the old key (only the type decl), so removing it is safe (backend reads
|
||||
the legacy UCI key directly, not via UI). Pure type-only → erased at build.
|
||||
- main.js: ZERO diff (section.js hand-written + not bundled; types.ts type-only).
|
||||
md5 unchanged across the build (aa89dfc5…). Confirmed via
|
||||
`git diff --exit-code main.js`. This is the EXPECTED/correct outcome — a diff
|
||||
there would mean an unexpected src change.
|
||||
- i18n: ran `node {extract-calls,generate-pot,generate-po ru,distribute-
|
||||
locales}.js` (yarn classic 1.22.22, but used node to avoid corepack). msgid
|
||||
delta = clean SWAP: removed 2 (`Group by countries` + its long description),
|
||||
added 7 (Off / By country flag / By name prefix / Subscription grouping /
|
||||
Prefix length / the grouping description / the prefix-length description).
|
||||
Filled 7 RU msgstr in SOURCE locales/netshift.ru.po then re-ran distribute →
|
||||
po/ru + po/templates byte-identical to source (diff -q both pairs). 0 empty
|
||||
non-header msgstr after. RU: Off→Выключено, By country flag→По флагу страны,
|
||||
By name prefix→По префиксу имени, Subscription grouping→Группировка подписки,
|
||||
Prefix length→Длина префикса.
|
||||
- yarn ci GREEN: format no-diff, eslint --max-warnings=0, vitest 472 pass, tsup
|
||||
build. yarn.lock unchanged, no .yarn/.yarnrc.yml. No new vitest (no new pure
|
||||
TS logic — datatype validation is LuCI client-side).
|
||||
- PRIVACY: no subscription-identifying data (hosts/IPs/URLs/keys/node names) in
|
||||
any code/comment/i18n/test/memory — generic "proxy name"/"country flag"
|
||||
wording only.
|
||||
- FLAG (no browser in env): the rendered Subscription tab (dropdown +
|
||||
conditional prefix-length field appearing only on mode=prefix, taboption
|
||||
auto-hide) needs a HUMAN VISUAL CHECK before merge — verified structurally
|
||||
only (taboption completeness, depends preserved).
|
||||
|
||||
## task-051 — text-list Selector/URLTest (paste links, one per line)
|
||||
|
||||
- CROSS-LAYER CONTRACT (backend done first): proxy_config_type values
|
||||
`selector_text` / `urltest_text`; scalar UCI options (textarea, one link per
|
||||
line) `selector_proxy_links_text` / `urltest_proxy_links_text`. Matched VERBATIM.
|
||||
- section.js (HAND-WRITTEN, NOT bundled → 0 main.js diff): (a) 2 new
|
||||
`o.value("selector_text",_("Selector (text list)"))` /
|
||||
`o.value("urltest_text",_("URLTest (text list)"))` after the `urltest` value.
|
||||
(b) 2 `form.TextValue` textareas modelled on the `url`-type `proxy_string`
|
||||
one (`o.textarea=true; o.rows=5; o.wrap="soft"; o.rmempty=false`): placed
|
||||
`selector_proxy_links_text` in the **connection** tab next to the existing
|
||||
`selector_proxy_links` DynamicList, and `urltest_proxy_links_text` in the
|
||||
**subscription** tab next to `urltest_proxy_links` (mirror the tab each
|
||||
list-typed sibling already lives in — they differ!). Each `o.validate` calls
|
||||
`main.validateProxyUrlList`.
|
||||
- URLTEST-TWIN GATING: the 3 urltest tuning fields (urltest_check_interval,
|
||||
urltest_tolerance, urltest_testing_url) each had `depends urltest` + `depends
|
||||
subscription`; added a 3rd `o.depends({connection_type:"proxy",
|
||||
proxy_config_type:"urltest_text"})` to each (CBI ORs depends). DID NOT touch
|
||||
`enable_udp_over_tcp` (gated on `connection_type:"proxy"` only → already shows
|
||||
for urltest_text) nor the subscription-only grouping/filter fields. The
|
||||
`urltest_proxy_links` DynamicList itself stays urltest-only (its text variant
|
||||
is the NEW separate field) — grep `proxy_config_type:"urltest"` leaves exactly
|
||||
4 hits: the DynamicList + 3 tuning fields.
|
||||
- NEW VALIDATOR `validateProxyUrlList(value:string):ValidationResult` — splits on
|
||||
`\n`, `.trim()` each line (so CRLF `\r` is stripped), skips blank lines, runs
|
||||
the EXISTING `validateProxyUrl` per line, returns first failure as
|
||||
`{valid:false, message:`${_('Line')} ${i+1}: ${msg}`}` (1-based incl. blank
|
||||
lines in the count) or `{valid:true,message:''}`. Empty/blank-only →
|
||||
`_('At least one proxy link must be specified.')`. ValidationResult REQUIRES
|
||||
`message:string` so valid branch sets `message:''`. BARREL-EXPORTED via
|
||||
`validators/index.ts` (`export * from './validateProxyUrlList'`) → reaches
|
||||
`main.validateProxyUrlList`. This is an EXPORTED leaf (NOT dispatcher-only like
|
||||
validateHysteria2Url/validateVmessUrl) because section.js calls it directly.
|
||||
- main.js: EXPECTED +28-line diff (the bundled validator fn + 1 export-block
|
||||
entry). Export-symbol set delta vs HEAD = EXACTLY `+ validateProxyUrlList`
|
||||
(no leak). Build IDEMPOTENT (md5 e5273ea1… across 2 builds), banner +
|
||||
`return baseclass.extend({` intact. The regenerated main.js IS the deliverable.
|
||||
- TEST `validators/tests/validateProxyUrlList.test.js`: table-driven describe.each
|
||||
(valid blobs incl. CRLF/blank-line/whitespace; invalid incl. empty/unsupported/
|
||||
garbage) + line-number-context assertions. SS fixture is the KNOWN-VALID
|
||||
`ss://2022-blake3-aes-256-gcm:dmCly/…=@127.0.0.1:27214?type=tcp` form copied
|
||||
from validateShadowsocksUrl.test.js (do NOT invent base64 that may fail). VLESS
|
||||
fixture copied from validateVlessUrl.test.js. 13 tests; total 485 pass.
|
||||
- i18n: 7 NEW msgids (Selector (text list); URLTest (text list); Selector Proxy
|
||||
Links (one per line); URLTest Proxy Links (one per line); the shared scheme-doc
|
||||
desc "…links — one per line"; "Line"; "At least one proxy link must be
|
||||
specified."). RU filled in SOURCE locales/netshift.ru.po then distribute →
|
||||
po/ru + po/templates byte-identical (diff -q). msgid count 352→359 purely
|
||||
additive. Ran `node {extract-calls,generate-pot,generate-po ru,distribute}.js`
|
||||
(generate-pot needs git user.name set). 1 empty msgstr remains = header only.
|
||||
- PRIVACY: all link strings synthetic (`127.0.0.1` hosts + scheme-doc literals);
|
||||
no real proxy/subscription data anywhere.
|
||||
- GATES GREEN: prettier --write src (all unchanged → no format churn beyond my
|
||||
files), eslint --max-warnings=0, vitest 485 pass, tsup build. yarn classic
|
||||
1.22.22 → ran via node_modules/.bin; yarn.lock unchanged, no .yarn/.yarnrc.yml.
|
||||
- FLAG (no browser in env): the rendered Connection/Subscription tabs (2 new
|
||||
dropdown choices, the 2 textareas appearing only for their type, the urltest
|
||||
tuning fields now appearing for urltest_text) need a HUMAN VISUAL CHECK —
|
||||
verified structurally only (taboption completeness, depends grep).
|
||||
|
||||
@ -52,6 +52,38 @@ artifacts out of the container -> **ipk underscore->dash rename**
|
||||
- Add a test: `test_xyz()` (header/pass/fail/skip), add to `main()` `all)` list,
|
||||
add `case` alias, update usage line + docker-compose comment. Keep the two
|
||||
compose invocations (build.yml smoke vs openwrt-smoke-tests.yml) in sync.
|
||||
- Smoke baselines drift as tests get added: 81 passed (pre task-016) -> 84
|
||||
passed after adding `test_nft_ipv6` (3 v6 assertions). Re-confirm the baseline
|
||||
from the actual run, don't trust a stale number in a task spec.
|
||||
- `test_nft_ipv6` (alias `nftv6`, task-016): real-nft regression guard for the
|
||||
B-01 IPv6 tproxy blocker. Builds the v6 tproxy rule from constants
|
||||
(`SB_TPROXY_INBOUND_ADDRESS_V6`/`_PORT_V6`) in a throwaway `inet` table, lists
|
||||
it back, and asserts it normalizes to bracketed `[::1]:1603` (positive) and
|
||||
that no portless bare form (`tproxy ip6 to ::0`) appears (negative guard). The
|
||||
unbracketed bug (`::1:1603`) is normalized by nft to a portless bare addr
|
||||
(`[::1:1603]` / `[::0.1.22.3]` depending on nft version) — either way the
|
||||
`\[::1\]:1603` grep fails, so the guard fires. Capability-gated: an
|
||||
ip6-tproxy "not supported"/"operation not supported" kernel `skip`s; a
|
||||
successful-but-wrong load `fail`s. SELF-PROVEN: temp scratch with unbracketed
|
||||
rule -> 1 failed (guard caught it), reverted.
|
||||
- Smoke test capability gating pattern: capture `add_err="$(nft add ... 2>&1)"`
|
||||
inside the `if`; on success run asserts, on failure `case "$add_err"` for
|
||||
*not supported* substrings -> `skip`, else `fail`. Avoids false-fails on
|
||||
kernels lacking a feature while still catching real bugs.
|
||||
- jq `index()` truthiness nit: `index("x") and index("y")` works (jq treats 0 as
|
||||
truthy) but prefer `(index("x") != null) and (index("y") != null)` for intent
|
||||
+ 0-index robustness. Was at entrypoint.sh:688.
|
||||
- WSL2 kernel (6.6.x-microsoft-standard-WSL2) DOES support ip6 tproxy in the
|
||||
smoke container, so the v6 assertions run (not skip) locally.
|
||||
- nft v6 buggy-form normalization is VERSION-DEPENDENT: the PROOF doc saw
|
||||
`[::0.1.22.3]` (nftables v1.1.3), but the OpenWRT 24.10.6 smoke container
|
||||
re-prints unbracketed `::1:1603` as `[::1:1603]` (no `]:` port sep). A
|
||||
negative guard that greps a single literal (`\[::0`) is therefore a DEAD
|
||||
assertion on the smoke env. ROBUST pattern: flag any `tproxy ip6 to [...]`
|
||||
line that is NOT the correct `[::1]:1603` ->
|
||||
`grep 'tproxy ip6 to \[' | grep -qv '\[::1\]:1603'`. Catches both
|
||||
normalizations + future variants. Self-proved: unbracketed scratch -> BOTH
|
||||
positive (`bracketed`) and negative (`no-bare`) guards FAIL (2 failed).
|
||||
|
||||
## CI gates by path
|
||||
|
||||
@ -73,3 +105,12 @@ artifacts out of the container -> **ipk underscore->dash rename**
|
||||
unsupported; needs >=15 MB on `/overlay`; NO uninstall path (removal lives in
|
||||
package `prerm`). GitHub API rate-limit is a known fragility (wget path has no
|
||||
guard).
|
||||
- `pkg_install` opkg branch uses `opkg install --force-downgrade
|
||||
--force-reinstall "$pkg_file"` (task-042). Plain `opkg install` silently
|
||||
no-op'd (rc=0) when re-run on a router with an older build: the legacy
|
||||
v-prefixed version (`v0.8.6-r1`) sorts ABOVE the no-v release (`0.8.7-r1`) so
|
||||
opkg "won't downgrade", and equal versions report "up to date". Both force
|
||||
flags make opkg remove+reinstall (proven on OWRT 24.10.5 aarch64). apk branch
|
||||
unchanged — `apk add --allow-untrusted` overwrites by default. This is the
|
||||
install.sh twin of the task-041 `updates_pkg_install_file` updater.sh fix;
|
||||
keep both upgrade paths (README script + in-app self-update) aligned.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -68,18 +68,34 @@ best-effort). It uses the same `PKG_VERSION` expression and
|
||||
updated, `luci-base` installed, feed dirs created; the apk one also runs
|
||||
`./setup.sh`).
|
||||
|
||||
### KNOWN INCONSISTENCY — respect it, do not "fix" blindly
|
||||
### Version passing — symmetric, both RAW (no `v` prefix)
|
||||
|
||||
The two release Dockerfiles pass the version differently:
|
||||
Both release Dockerfiles now pass the version **raw**, with no `v` prefix:
|
||||
|
||||
- `Dockerfile-ipk`: `RUN export NETSHIFT_VERSION="v${NETSHIFT_VERSION}" && ...`
|
||||
— it **prepends `v`**.
|
||||
- `Dockerfile-ipk`: `ENV NETSHIFT_VERSION=${NETSHIFT_VERSION}` — **raw, no
|
||||
`v`**.
|
||||
- `Dockerfile-apk`: `ENV NETSHIFT_VERSION=${NETSHIFT_VERSION}` — **raw, no
|
||||
`v`**.
|
||||
|
||||
This asymmetry is intentional/load-bearing for the current artifact names. Do
|
||||
not normalize one to match the other without verifying the whole release flow
|
||||
(§4) and `install.sh` matching (§6).
|
||||
> Historical note (task-028): `Dockerfile-ipk` used to **prepend `v`**
|
||||
> (`RUN export NETSHIFT_VERSION="v${NETSHIFT_VERSION}" && ...`) while the apk
|
||||
> file passed it raw. That asymmetry stamped a leading `v` into the ipk
|
||||
> package/control version and the runtime `constants.sh` `NETSHIFT_VERSION`,
|
||||
> so on OWRT24/ipk the installed version (`v0.8.6`) never matched the no-`v`
|
||||
> GitHub tag (`0.8.6`) and the LuCI UI falsely reported "outdated". The `v`
|
||||
> prepend was removed (ipk normalized to the apk shape) after verifying the
|
||||
> whole release flow (§4) and `install.sh` matching (§6): the `_`→`-` rename,
|
||||
> the 3-package filter, the i18n `-${VERSION}` naming, and the release tag all
|
||||
> derive from the git tag, and `install.sh` matches assets by **name prefix**
|
||||
> (the `v` lived in the version segment, not the name prefix) — so dropping it
|
||||
> does not affect either. Keep both Dockerfiles passing the version raw.
|
||||
>
|
||||
> Residual fragility (out of scope, on record): the UI version-equality check
|
||||
> in `fe-app-netshift` does **not** normalize a leading `v`. If a future
|
||||
> release is tagged **with** a `v` (e.g. `v0.8.7`), `netshift_latest_version`
|
||||
> would carry `v` while the installed (no-`v`) version would not, re-triggering
|
||||
> the false-"outdated" mismatch. **Tag releases WITHOUT a `v`** to keep
|
||||
> ipk / apk / tag all consistent.
|
||||
|
||||
---
|
||||
|
||||
|
||||
BIN
docs/screenshot.png
Normal file
BIN
docs/screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 303 KiB |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -7,8 +7,8 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: NETSHIFT\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-06-05 09:28+0300\n"
|
||||
"PO-Revision-Date: 2026-06-05 09:28+0300\n"
|
||||
"POT-Creation-Date: 2026-06-13 14:14+0300\n"
|
||||
"PO-Revision-Date: 2026-06-13 14:14+0300\n"
|
||||
"Last-Translator: yandexru45\n"
|
||||
"Language-Team: none\n"
|
||||
"Language: ru\n"
|
||||
@ -29,33 +29,54 @@ msgstr "✘ Отключено"
|
||||
msgid "✘ Stopped"
|
||||
msgstr "✘ Остановлен"
|
||||
|
||||
msgid "Группировать по странам"
|
||||
msgstr ""
|
||||
|
||||
msgid "Группирует прокси подписки по флагу страны в начале тега в отдельные URLTest-группы"
|
||||
msgstr ""
|
||||
|
||||
msgid "Active Connections"
|
||||
msgstr "Активные соединения"
|
||||
|
||||
msgid "Add one or more subscription URLs to fetch proxy configurations from. All feeds are downloaded and merged."
|
||||
msgstr "Добавьте один или несколько URL подписок для получения конфигураций прокси. Все источники загружаются и объединяются."
|
||||
|
||||
msgid "Add your own domains: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip"
|
||||
msgstr "Добавьте свои домены: выберите Динамический список (по одному в строке) или Текстовый список (свободный ввод), либо Отключено, чтобы пропустить"
|
||||
|
||||
msgid "Add your own subnets or IPs: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip"
|
||||
msgstr "Добавьте свои подсети или IP: выберите Динамический список (по одному в строке) или Текстовый список (свободный ввод), либо Отключено, чтобы пропустить"
|
||||
|
||||
msgid "Additional marking rules found"
|
||||
msgstr "Найдены дополнительные правила маркировки"
|
||||
|
||||
msgid "Advanced"
|
||||
msgstr "Дополнительно"
|
||||
|
||||
msgid "Allow insecure TLS for subscription fetch"
|
||||
msgstr "Разрешить небезопасный TLS при загрузке подписки"
|
||||
|
||||
msgid "Allows access to YACD from the WAN. Make sure to open the appropriate port in your firewall."
|
||||
msgstr "Обеспечивает доступ к YACD из WAN. Убедитесь, что в брандмауэре открыт соответствующий порт."
|
||||
|
||||
msgid "Applicable for SOCKS and Shadowsocks proxy"
|
||||
msgstr "Применимо для SOCKS и Shadowsocks прокси"
|
||||
|
||||
msgid "At least one proxy link must be specified."
|
||||
msgstr "Необходимо указать хотя бы одну прокси-ссылку."
|
||||
|
||||
msgid "At least one valid domain must be specified. Comments-only content is not allowed."
|
||||
msgstr "Необходимо указать хотя бы один действительный домен. Содержимое только из комментариев не допускается."
|
||||
|
||||
msgid "At least one valid subnet or IP must be specified. Comments-only content is not allowed."
|
||||
msgstr "Необходимо указать хотя бы одну действительную подсеть или IP. Только комментарии недопустимы."
|
||||
|
||||
msgid "Auto"
|
||||
msgstr "Авто"
|
||||
|
||||
msgid "Available actions"
|
||||
msgstr "Доступные действия"
|
||||
|
||||
msgid "Block direct connections to known public DoH servers (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex) so apps cannot bypass router DNS filtering."
|
||||
msgstr "Блокировать прямые подключения к известным публичным DoH-серверам (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex), чтобы приложения не могли обойти DNS-фильтрацию роутера."
|
||||
|
||||
msgid "Block DoH Servers"
|
||||
msgstr "Блокировать DoH-серверы"
|
||||
|
||||
msgid "Bootsrap DNS"
|
||||
msgstr "Bootstrap DNS"
|
||||
|
||||
@ -68,6 +89,12 @@ msgstr "Браузер не использует FakeIP"
|
||||
msgid "Browser is using FakeIP correctly"
|
||||
msgstr "Браузер использует FakeIP"
|
||||
|
||||
msgid "By country flag"
|
||||
msgstr "По флагу страны"
|
||||
|
||||
msgid "By name prefix"
|
||||
msgstr "По префиксу имени"
|
||||
|
||||
msgid "Cache File Path"
|
||||
msgstr "Путь к файлу кэша"
|
||||
|
||||
@ -77,6 +104,9 @@ msgstr "Путь к файлу кэша не может быть пустым"
|
||||
msgid "Cannot receive checks result"
|
||||
msgstr "Не удалось получить результаты проверки"
|
||||
|
||||
msgid "Check update"
|
||||
msgstr "Проверить обновление"
|
||||
|
||||
msgid "Checking, please wait"
|
||||
msgstr "Проверяем, пожалуйста подождите"
|
||||
|
||||
@ -92,24 +122,39 @@ msgstr "Проверки пройдены"
|
||||
msgid "CIDR must be between 0 and 32"
|
||||
msgstr "CIDR должен быть между 0 и 32"
|
||||
|
||||
msgid "Clear subscription cache"
|
||||
msgstr "Очистить кеш подписок"
|
||||
|
||||
msgid "Clearing subscription cache and re-downloading… this may take a minute"
|
||||
msgstr "Очистка кеша подписок и повторная загрузка… это может занять минуту"
|
||||
|
||||
msgid "Close"
|
||||
msgstr "Закрыть"
|
||||
|
||||
msgid "Community Lists"
|
||||
msgstr "Списки сообщества"
|
||||
|
||||
msgid "Component Manager"
|
||||
msgstr "Менеджер компонентов"
|
||||
|
||||
msgid "Config File Path"
|
||||
msgstr "Путь к файлу конфигурации"
|
||||
|
||||
msgid "Configuration for NetShift service"
|
||||
msgstr ""
|
||||
msgstr "Конфигурация службы NetShift"
|
||||
|
||||
msgid "Configuration Type"
|
||||
msgstr "Тип конфигурации"
|
||||
|
||||
msgid "Connection"
|
||||
msgstr "Подключение"
|
||||
|
||||
msgid "Connection Type"
|
||||
msgstr "Тип подключения"
|
||||
|
||||
msgid "Connection type, transport and DNS resolver for this section"
|
||||
msgstr "Тип подключения, транспорт и DNS-резолвер для этой секции"
|
||||
|
||||
msgid "Connection URL"
|
||||
msgstr "URL подключения"
|
||||
|
||||
@ -125,6 +170,12 @@ msgstr "Истекло время ожидания переключения яд
|
||||
msgid "Currently unavailable"
|
||||
msgstr "Временно недоступно"
|
||||
|
||||
msgid "Custom domains"
|
||||
msgstr "Свои домены"
|
||||
|
||||
msgid "Custom subnets"
|
||||
msgstr "Свои подсети"
|
||||
|
||||
msgid "Dashboard"
|
||||
msgstr "Дашборд"
|
||||
|
||||
@ -132,11 +183,14 @@ msgid "Dashboard currently unavailable"
|
||||
msgstr "Дашборд сейчас недоступен"
|
||||
|
||||
msgid "Delay in milliseconds before reloading NetShift after interface UP"
|
||||
msgstr ""
|
||||
msgstr "Задержка в миллисекундах перед перезагрузкой NetShift после поднятия интерфейса"
|
||||
|
||||
msgid "Delay value cannot be empty"
|
||||
msgstr "Значение задержки не может быть пустым"
|
||||
|
||||
msgid "Dev"
|
||||
msgstr "Dev"
|
||||
|
||||
msgid "DHCP has DNS server"
|
||||
msgstr "DHCP содержит DNS сервер"
|
||||
|
||||
@ -155,9 +209,18 @@ msgstr "Отключить QUIC протокол для улучшения со
|
||||
msgid "Disabled"
|
||||
msgstr "Отключено"
|
||||
|
||||
msgid "Disables TLS certificate verification when downloading the subscription."
|
||||
msgstr "Отключает проверку TLS-сертификата при загрузке подписки."
|
||||
|
||||
msgid "DNS"
|
||||
msgstr "DNS"
|
||||
|
||||
msgid "DNS on router"
|
||||
msgstr "DNS на роутере"
|
||||
|
||||
msgid "DNS outbound section"
|
||||
msgstr "Секция outbound для DNS"
|
||||
|
||||
msgid "DNS over HTTPS (DoH)"
|
||||
msgstr "DNS через HTTPS (DoH)"
|
||||
|
||||
@ -179,6 +242,9 @@ msgstr "Адрес DNS-сервера не может быть пустым"
|
||||
msgid "Do not panic, everything can be fixed, just..."
|
||||
msgstr "Не паникуйте, всё можно исправить, просто..."
|
||||
|
||||
msgid "Domain and subnet lists that decide which traffic uses this section"
|
||||
msgstr "Списки доменов и подсетей, определяющие, какой трафик идёт через эту секцию"
|
||||
|
||||
msgid "Domain Resolver"
|
||||
msgstr "Резолвер доменов"
|
||||
|
||||
@ -215,6 +281,12 @@ msgstr "Включить встроенный DNS-резолвер для дом
|
||||
msgid "Enable DNS resolve to get real IP when routing"
|
||||
msgstr "Разрешать домены в реальные IP-адреса перед маршрутизацией в outbound"
|
||||
|
||||
msgid "Enable IPv6 Support"
|
||||
msgstr "Включить поддержку IPv6"
|
||||
|
||||
msgid "Enable IPv6 TProxy routing, IPv6 DNS inbound, and IPv6 FakeIP support."
|
||||
msgstr "Включить маршрутизацию TProxy по IPv6, входящий DNS по IPv6 и поддержку FakeIP для IPv6."
|
||||
|
||||
msgid "Enable Mixed Proxy"
|
||||
msgstr "Включить смешанный прокси"
|
||||
|
||||
@ -242,23 +314,20 @@ msgstr "Введите доменные имена без протоколов,
|
||||
msgid "Enter subnets in CIDR notation (e.g. 103.21.244.0/22) or single IP addresses"
|
||||
msgstr "Введите подсети в нотации CIDR (например, 103.21.244.0/22) или отдельные IP-адреса"
|
||||
|
||||
msgid "Enter the subscription URL to fetch proxy configurations from your provider"
|
||||
msgstr ""
|
||||
|
||||
msgid "Every 1 minute"
|
||||
msgstr "Каждую минуту"
|
||||
|
||||
msgid "Every 12 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 12 часов"
|
||||
|
||||
msgid "Every 3 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 3 часа"
|
||||
|
||||
msgid "Every 3 minutes"
|
||||
msgstr "Каждые 3 минуты"
|
||||
|
||||
msgid "Every 30 minutes"
|
||||
msgstr ""
|
||||
msgstr "Каждые 30 минут"
|
||||
|
||||
msgid "Every 30 seconds"
|
||||
msgstr "Каждые 30 секунд"
|
||||
@ -267,13 +336,13 @@ msgid "Every 5 minutes"
|
||||
msgstr "Каждые 5 минут"
|
||||
|
||||
msgid "Every 6 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 6 часов"
|
||||
|
||||
msgid "Every day"
|
||||
msgstr ""
|
||||
msgstr "Каждый день"
|
||||
|
||||
msgid "Every hour"
|
||||
msgstr ""
|
||||
msgstr "Каждый час"
|
||||
|
||||
msgid "Exclude NTP"
|
||||
msgstr "Исключить NTP"
|
||||
@ -284,6 +353,9 @@ msgstr "Исключите трафик протокола NTP из туннел
|
||||
msgid "Exclude servers by keyword"
|
||||
msgstr "Исключать серверы по ключевому слову"
|
||||
|
||||
msgid "Failed to clear subscription cache"
|
||||
msgstr "Не удалось очистить кеш подписок"
|
||||
|
||||
msgid "Failed to copy!"
|
||||
msgstr "Не удалось скопировать!"
|
||||
|
||||
@ -302,8 +374,14 @@ msgstr "Получить глобальную проверку"
|
||||
msgid "Global check"
|
||||
msgstr "Глобальная проверка"
|
||||
|
||||
msgid "Global Proxy"
|
||||
msgstr "Глобальный прокси"
|
||||
|
||||
msgid "Group subscription proxies into URLTest groups. 'By country flag' uses the flag emoji at the start of each name; 'By name prefix' groups by the first N characters."
|
||||
msgstr "Группировать прокси из подписки в группы URLTest. «По флагу страны» использует эмодзи флага в начале каждого имени; «По префиксу имени» группирует по первым N символам."
|
||||
|
||||
msgid "How often to automatically update the subscription"
|
||||
msgstr ""
|
||||
msgstr "Как часто автоматически обновлять подписку"
|
||||
|
||||
msgid "HTTP error"
|
||||
msgstr "Ошибка HTTP"
|
||||
@ -311,11 +389,11 @@ msgstr "Ошибка HTTP"
|
||||
msgid "Include servers by keyword"
|
||||
msgstr "Включать серверы по ключевому слову"
|
||||
|
||||
msgid "Install extended"
|
||||
msgstr "Установить extended"
|
||||
msgid "Install %s"
|
||||
msgstr "Установить %s"
|
||||
|
||||
msgid "Install stable"
|
||||
msgstr "Установить stable"
|
||||
msgid "Installed version is newer than release"
|
||||
msgstr "Установленная версия новее релиза"
|
||||
|
||||
msgid "Interface Monitoring"
|
||||
msgstr "Мониторинг интерфейса"
|
||||
@ -326,14 +404,14 @@ msgstr "Задержка при мониторинге интерфейсов"
|
||||
msgid "Interface monitoring for Bad WAN"
|
||||
msgstr "Мониторинг интерфейса для Bad WAN"
|
||||
|
||||
msgid "Invalid DNS server format. Examples: 8.8.8.8 or dns.example.com or dns.example.com/nicedns for DoH"
|
||||
msgstr "Неверный формат DNS-сервера. Примеры: 8.8.8.8, dns.example.com или dns.example.com/nicedns для DoH"
|
||||
msgid "Invalid DNS server format. Examples: 8.8.8.8, [::1], dns.example.com, or dns.example.com/dns-query for DoH"
|
||||
msgstr "Неверный формат DNS-сервера. Примеры: 8.8.8.8, [::1], dns.example.com или dns.example.com/dns-query для DoH"
|
||||
|
||||
msgid "Invalid domain address"
|
||||
msgstr "Неверный домен"
|
||||
|
||||
msgid "Invalid format. Use X.X.X.X or X.X.X.X/Y"
|
||||
msgstr "Неверный формат. Используйте X.X.X.X или X.X.X.X/Y"
|
||||
msgid "Invalid format. Use X.X.X.X/Y or IPv6/Y"
|
||||
msgstr "Неверный формат. Используйте X.X.X.X/Y или IPv6/Y"
|
||||
|
||||
msgid "Invalid HY2 URL: insecure must be 0 or 1"
|
||||
msgstr "Неверный URL Hysteria2: параметр insecure должен быть 0 или 1"
|
||||
@ -377,6 +455,9 @@ msgstr "Неверный URL Hysteria2: неподдерживаемый тип
|
||||
msgid "Invalid IP address"
|
||||
msgstr "Неверный IP-адрес"
|
||||
|
||||
msgid "Invalid IPv6 address"
|
||||
msgstr "Неверный IPv6-адрес"
|
||||
|
||||
msgid "Invalid JSON format"
|
||||
msgstr "Неверный формат JSON"
|
||||
|
||||
@ -479,6 +560,9 @@ msgstr "Неверный URL VMess: должен начинаться с vmess:/
|
||||
msgid "IP address 0.0.0.0 is not allowed"
|
||||
msgstr "IP-адрес 0.0.0.0 не допускается"
|
||||
|
||||
msgid "IPv6 CIDR must be between 0 and 128"
|
||||
msgstr "IPv6 CIDR должен быть от 0 до 128"
|
||||
|
||||
msgid "Issues detected"
|
||||
msgstr "Обнаружены проблемы"
|
||||
|
||||
@ -488,9 +572,21 @@ msgstr "Оставлять только серверы подписки, имя
|
||||
msgid "Latest"
|
||||
msgstr "Последняя"
|
||||
|
||||
msgid "Latest version is installed"
|
||||
msgstr "Установлена последняя версия"
|
||||
|
||||
msgid "Line"
|
||||
msgstr "Строка"
|
||||
|
||||
msgid "List Update Frequency"
|
||||
msgstr "Частота обновления списков"
|
||||
|
||||
msgid "List update schedule, download routing, and routing exclusions"
|
||||
msgstr "Расписание обновления списков, маршрутизация загрузок и исключения из маршрутизации"
|
||||
|
||||
msgid "Lists & Updates"
|
||||
msgstr "Списки и обновления"
|
||||
|
||||
msgid "Local Domain Lists"
|
||||
msgstr "Локальные списки доменов"
|
||||
|
||||
@ -503,9 +599,15 @@ msgstr "Уровень логов"
|
||||
msgid "Main DNS"
|
||||
msgstr "Основной DNS"
|
||||
|
||||
msgid "Main DNS via outbound"
|
||||
msgstr "Основной DNS через outbound"
|
||||
|
||||
msgid "Memory Usage"
|
||||
msgstr "Использование памяти"
|
||||
|
||||
msgid "Mixed proxy and DNS resolution tuning"
|
||||
msgstr "Настройка смешанного прокси и разрешения DNS"
|
||||
|
||||
msgid "Mixed Proxy Port"
|
||||
msgstr "Порт смешанного прокси"
|
||||
|
||||
@ -516,13 +618,19 @@ msgid "Must be a number in the range of 50 - 1000"
|
||||
msgstr "Должно быть числом от 50 до 1000"
|
||||
|
||||
msgid "NetShift"
|
||||
msgstr ""
|
||||
msgstr "NetShift"
|
||||
|
||||
msgid "NetShift Settings"
|
||||
msgstr ""
|
||||
msgstr "Настройки NetShift"
|
||||
|
||||
msgid "NetShift updated, version:"
|
||||
msgstr "NetShift обновлён, версия:"
|
||||
|
||||
msgid "NetShift will not modify your DHCP configuration"
|
||||
msgstr ""
|
||||
msgstr "NetShift не будет изменять вашу конфигурацию DHCP"
|
||||
|
||||
msgid "Network"
|
||||
msgstr "Сеть"
|
||||
|
||||
msgid "Network Interface"
|
||||
msgstr "Сетевой интерфейс"
|
||||
@ -533,12 +641,24 @@ msgstr "Другие правила маркировки не найдены"
|
||||
msgid "Not implement yet"
|
||||
msgstr "Ещё не реализовано"
|
||||
|
||||
msgid "Not installed"
|
||||
msgstr "Не установлено"
|
||||
|
||||
msgid "Not responding"
|
||||
msgstr "Не отвечает"
|
||||
|
||||
msgid "Not running"
|
||||
msgstr "Не запущено"
|
||||
|
||||
msgid "Number of leading characters of each proxy name to group by."
|
||||
msgstr "Количество начальных символов имени каждого прокси для группировки."
|
||||
|
||||
msgid "Off"
|
||||
msgstr "Выключено"
|
||||
|
||||
msgid "Only one section can be global at a time."
|
||||
msgstr "Только одна секция может быть глобальной одновременно."
|
||||
|
||||
msgid "Operation timed out"
|
||||
msgstr "Время ожидания истекло"
|
||||
|
||||
@ -569,6 +689,12 @@ msgstr "Путь должен заканчиваться на cache.db"
|
||||
msgid "Pending"
|
||||
msgstr "Ожидает запуска"
|
||||
|
||||
msgid "Prefix length"
|
||||
msgstr "Длина префикса"
|
||||
|
||||
msgid "Protocol toggles, file paths and logging. Block DoH only after switching upstream DNS to UDP or DoT."
|
||||
msgstr "Переключатели протоколов, пути к файлам и журналирование. Включайте блокировку DoH только после переключения вышестоящего DNS на UDP или DoT."
|
||||
|
||||
msgid "Proxy Configuration URL"
|
||||
msgstr "URL конфигурации прокси"
|
||||
|
||||
@ -591,7 +717,13 @@ msgid "Resolve real IP for routing"
|
||||
msgstr "Разрешение реальных IP-адресов"
|
||||
|
||||
msgid "Restart NetShift"
|
||||
msgstr ""
|
||||
msgstr "Перезапустить NetShift"
|
||||
|
||||
msgid "Route all unmatched traffic through this section's outbound."
|
||||
msgstr "Направлять весь несовпавший трафик через outbound этой секции."
|
||||
|
||||
msgid "Route main DNS through proxy/VPN"
|
||||
msgstr "Основной DNS через прокси/VPN"
|
||||
|
||||
msgid "Router DNS is not routed through sing-box"
|
||||
msgstr "DNS роутера не проходит через sing-box"
|
||||
@ -599,6 +731,9 @@ msgstr "DNS роутера не проходит через sing-box"
|
||||
msgid "Router DNS is routed through sing-box"
|
||||
msgstr "DNS роутера проходит через sing-box"
|
||||
|
||||
msgid "Routing"
|
||||
msgstr "Маршрутизация"
|
||||
|
||||
msgid "Routing Excluded IPs"
|
||||
msgstr "Исключённые из маршрутизации IP-адреса"
|
||||
|
||||
@ -608,9 +743,6 @@ msgstr "Счётчики правил mangle"
|
||||
msgid "Rules mangle exist"
|
||||
msgstr "Правила mangle существуют"
|
||||
|
||||
msgid "Rules mangle output counters"
|
||||
msgstr "Счётчики правил mangle output"
|
||||
|
||||
msgid "Rules mangle output exist"
|
||||
msgstr "Правила mangle output существуют"
|
||||
|
||||
@ -662,12 +794,6 @@ msgstr "Выберите путь к файлу конфигурации sing-bo
|
||||
msgid "Select the DNS protocol type for the domain resolver"
|
||||
msgstr "Выберите тип протокола DNS для резолвера доменов"
|
||||
|
||||
msgid "Select the list type for adding custom domains"
|
||||
msgstr "Выберите тип списка для добавления пользовательских доменов"
|
||||
|
||||
msgid "Select the list type for adding custom subnets"
|
||||
msgstr "Выберите тип списка для добавления пользовательских подсетей"
|
||||
|
||||
msgid "Select the log level for sing-box"
|
||||
msgstr "Выберите уровень логов для sing-box"
|
||||
|
||||
@ -683,9 +809,21 @@ msgstr "Выберите WAN интерфейсы для мониторинга"
|
||||
msgid "Selector"
|
||||
msgstr "Selector"
|
||||
|
||||
msgid "Selector (text list)"
|
||||
msgstr "Selector (текстовый список)"
|
||||
|
||||
msgid "Selector Proxy Links"
|
||||
msgstr "Ссылки прокси для Selector"
|
||||
|
||||
msgid "Selector Proxy Links (one per line)"
|
||||
msgstr "Прокси-ссылки Selector (по одной в строке)"
|
||||
|
||||
msgid "Self-update failed"
|
||||
msgstr "Не удалось обновить"
|
||||
|
||||
msgid "Send upstream DNS queries through a proxy/VPN outbound instead of directly. Bootstrap DNS always stays direct."
|
||||
msgstr "Отправлять запросы к основному DNS через outbound прокси/VPN вместо прямого подключения. Bootstrap DNS всегда остаётся прямым."
|
||||
|
||||
msgid "Services info"
|
||||
msgstr "Информация о сервисах"
|
||||
|
||||
@ -719,6 +857,9 @@ msgstr "Сервис sing-box существует"
|
||||
msgid "Sing-box version is compatible (newer than 1.12.4)"
|
||||
msgstr "Версия Sing-box совместима (новее 1.12.4)"
|
||||
|
||||
msgid "Source and output interfaces, and Bad WAN interface monitoring"
|
||||
msgstr "Входящий и исходящий интерфейсы, а также мониторинг интерфейсов Bad WAN"
|
||||
|
||||
msgid "Source Network Interface"
|
||||
msgstr "Сетевой интерфейс источника"
|
||||
|
||||
@ -738,23 +879,41 @@ msgid "Specify the path to the list file located on the router filesystem"
|
||||
msgstr "Укажите путь к файлу списка, расположенному в файловой системе маршрутизатора."
|
||||
|
||||
msgid "Start NetShift"
|
||||
msgstr ""
|
||||
msgstr "Запустить NetShift"
|
||||
|
||||
msgid "Stop NetShift"
|
||||
msgstr ""
|
||||
msgstr "Остановить NetShift"
|
||||
|
||||
msgid "Subscription"
|
||||
msgstr ""
|
||||
msgstr "Подписка"
|
||||
|
||||
msgid "Subscription cache cleared and re-downloaded"
|
||||
msgstr "Кеш подписок очищен и загружен заново"
|
||||
|
||||
msgid "Subscription feeds, server filters and URLTest tuning"
|
||||
msgstr "Источники подписок, фильтры серверов и настройка URLTest"
|
||||
|
||||
msgid "Subscription format"
|
||||
msgstr "Формат подписки"
|
||||
|
||||
msgid "Subscription grouping"
|
||||
msgstr "Группировка подписки"
|
||||
|
||||
msgid "Subscription Update Interval"
|
||||
msgstr ""
|
||||
msgstr "Интервал обновления подписки"
|
||||
|
||||
msgid "Subscription URL"
|
||||
msgstr ""
|
||||
msgid "Subscription URLs"
|
||||
msgstr "URL подписок"
|
||||
|
||||
msgid "Successfully copied!"
|
||||
msgstr "Успешно скопировано!"
|
||||
|
||||
msgid "Switch to extended"
|
||||
msgstr "Переключить на extended"
|
||||
|
||||
msgid "Switch to stable"
|
||||
msgstr "Переключить на stable"
|
||||
|
||||
msgid "Switching sing-box core, this may take a few minutes…"
|
||||
msgstr "Переключение ядра sing-box, это может занять несколько минут…"
|
||||
|
||||
@ -785,6 +944,9 @@ msgstr "Максимально допустимая разница во врем
|
||||
msgid "The URL used to test server connectivity"
|
||||
msgstr "URL-адрес, используемый для проверки подключения к серверу"
|
||||
|
||||
msgid "This is a security trade-off: an attacker could intercept the fetch."
|
||||
msgstr "Это компромисс в безопасности: злоумышленник может перехватить загрузку."
|
||||
|
||||
msgid "Time in seconds for DNS record caching (default: 60)"
|
||||
msgstr "Время в секундах для кэширования DNS записей (по умолчанию: 60)"
|
||||
|
||||
@ -815,9 +977,24 @@ msgstr "неизвестно"
|
||||
msgid "Unknown error"
|
||||
msgstr "Неизвестная ошибка"
|
||||
|
||||
msgid "Update"
|
||||
msgstr "Обновить"
|
||||
|
||||
msgid "Update is available"
|
||||
msgstr "Доступно обновление"
|
||||
|
||||
msgid "Update NetShift"
|
||||
msgstr "Обновить NetShift"
|
||||
|
||||
msgid "Updating NetShift, this may take a few minutes; the page will reload…"
|
||||
msgstr "Обновление NetShift, это может занять несколько минут; страница перезагрузится…"
|
||||
|
||||
msgid "Uplink"
|
||||
msgstr "Исходящий"
|
||||
|
||||
msgid "Upstream and bootstrap DNS resolvers, and optional DNS-over-proxy"
|
||||
msgstr "Вышестоящий и начальный (bootstrap) DNS-резолверы и опциональный DNS через прокси"
|
||||
|
||||
msgid "URL must start with vless://, vmess://, ss://, trojan://, socks4/5://, or hysteria2://hy2://"
|
||||
msgstr "URL должен начинаться с vless://, vmess://, ss://, trojan://, socks4/5:// или hysteria2:// hy2://"
|
||||
|
||||
@ -827,20 +1004,32 @@ msgstr "URL должен использовать один из следующи
|
||||
msgid "URLTest"
|
||||
msgstr "URLTest"
|
||||
|
||||
msgid "URLTest (text list)"
|
||||
msgstr "URLTest (текстовый список)"
|
||||
|
||||
msgid "URLTest Check Interval"
|
||||
msgstr "Интервал проверки URLTest"
|
||||
|
||||
msgid "URLTest Proxy Links"
|
||||
msgstr "Ссылки прокси для URLTest"
|
||||
|
||||
msgid "URLTest Proxy Links (one per line)"
|
||||
msgstr "Прокси-ссылки URLTest (по одной в строке)"
|
||||
|
||||
msgid "URLTest Testing URL"
|
||||
msgstr "URLTest ссылка для проверки"
|
||||
|
||||
msgid "URLTest Tolerance"
|
||||
msgstr "URLTest допустимое отклонение"
|
||||
|
||||
msgid "User Domain List Type"
|
||||
msgstr "Тип пользовательского списка доменов"
|
||||
msgid "Use only for IP-host panels that serve an invalid or self-signed certificate."
|
||||
msgstr "Используйте только для панелей с IP-адресом, у которых недействительный или самоподписанный сертификат."
|
||||
|
||||
msgid "Use this only when the router has working IPv6 connectivity."
|
||||
msgstr "Используйте это только если на роутере есть рабочее подключение по IPv6."
|
||||
|
||||
msgid "Use with Exclusion sections to route specific domains directly."
|
||||
msgstr "Используйте вместе с секциями исключений для прямой маршрутизации определённых доменов."
|
||||
|
||||
msgid "User Domains"
|
||||
msgstr "Пользовательские домены"
|
||||
@ -848,9 +1037,6 @@ msgstr "Пользовательские домены"
|
||||
msgid "User Domains List"
|
||||
msgstr "Список пользовательских доменов"
|
||||
|
||||
msgid "User Subnet List Type"
|
||||
msgstr "Тип пользовательского списка подсетей"
|
||||
|
||||
msgid "User Subnets"
|
||||
msgstr "Пользовательские подсети"
|
||||
|
||||
@ -863,6 +1049,9 @@ msgstr "Валидно"
|
||||
msgid "Validation errors:"
|
||||
msgstr "Ошибки валидации:"
|
||||
|
||||
msgid "Version"
|
||||
msgstr "Версия"
|
||||
|
||||
msgid "View logs"
|
||||
msgstr "Посмотреть логи"
|
||||
|
||||
@ -872,14 +1061,32 @@ msgstr "Перейти в wiki"
|
||||
msgid "vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links"
|
||||
msgstr "ссылки vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2://"
|
||||
|
||||
msgid "vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links — one per line"
|
||||
msgstr "Ссылки vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// — по одной в строке"
|
||||
|
||||
msgid "Warning: %s cannot be used together with %s. Previous selections have been removed."
|
||||
msgstr "Предупреждение: %s нельзя использовать вместе с %s. Предыдущие варианты были удалены."
|
||||
|
||||
msgid "Warning: Russia inside can only be used with %s. %s already in Russia inside and have been removed from selection."
|
||||
msgstr "Предупреждение: Russia inside может быть использован только с %s. %s уже есть в Russia inside и будет удален из выбранных."
|
||||
|
||||
msgid "When enabled, traffic not matching any other section's lists will go through this proxy."
|
||||
msgstr "Когда включено, трафик, не совпадающий со списками других секций, будет идти через этот прокси."
|
||||
|
||||
msgid "Which proxy/VPN section carries the DNS. Leave unset to use the first configured outbound."
|
||||
msgstr "Какая секция прокси/VPN обслуживает DNS. Оставьте пустым, чтобы использовать первый настроенный outbound."
|
||||
|
||||
msgid "Which subscription format (client) to fetch first. Auto uses the default order. Choose Xray JSON (Happ) when your panel only exposes some nodes (e.g. xhttp) under a Happ-like client, or Sing-box to prefer the sing-box format."
|
||||
msgstr "Какой формат подписки (клиент) запрашивать первым. «Авто» использует порядок по умолчанию. Выберите «Xray JSON (Happ)», если ваша панель отдаёт некоторые узлы (например, xhttp) только под клиентом вроде Happ, или «Sing-box», чтобы предпочесть формат sing-box."
|
||||
|
||||
msgid "Xray JSON (Happ)"
|
||||
msgstr "Xray JSON (Happ)"
|
||||
|
||||
msgid "YACD Secret Key"
|
||||
msgstr "Секретный ключ YACD"
|
||||
|
||||
msgid "YACD web dashboard access and remote-access protection"
|
||||
msgstr "Доступ к веб-панели YACD и защита удалённого доступа"
|
||||
|
||||
msgid "You can select Output Network Interface, by default autodetect"
|
||||
msgstr "Вы можете выбрать выходной сетевой интерфейс, по умолчанию он определяется автоматически."
|
||||
|
||||
@ -83,6 +83,9 @@ export const DNS_SERVER_OPTIONS = {
|
||||
'unfiltered.adguard-dns.com':
|
||||
'unfiltered.adguard-dns.com (AdGuard Unfiltered)',
|
||||
'family.adguard-dns.com': 'family.adguard-dns.com (AdGuard Family)',
|
||||
'2001:4860:4860::8888': '2001:4860:4860::8888 (Google IPv6)',
|
||||
'2606:4700:4700::1111': '2606:4700:4700::1111 (Cloudflare IPv6)',
|
||||
'2620:fe::fe': '2620:fe::fe (Quad9 IPv6)',
|
||||
};
|
||||
export const BOOTSTRAP_DNS_SERVER_OPTIONS = {
|
||||
'77.88.8.8': '77.88.8.8 (Yandex DNS)',
|
||||
@ -93,6 +96,8 @@ export const BOOTSTRAP_DNS_SERVER_OPTIONS = {
|
||||
'8.8.4.4': '8.8.4.4 (Google DNS)',
|
||||
'9.9.9.9': '9.9.9.9 (Quad9 DNS)',
|
||||
'9.9.9.11': '9.9.9.11 (Quad9 DNS)',
|
||||
'2001:4860:4860::8888': '2001:4860:4860::8888 (Google DNS IPv6)',
|
||||
'2606:4700:4700::1111': '2606:4700:4700::1111 (Cloudflare DNS IPv6)',
|
||||
};
|
||||
|
||||
export const DIAGNOSTICS_UPDATE_INTERVAL = 10000; // 10 seconds
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
export function showToast(
|
||||
message: string,
|
||||
type: 'success' | 'error',
|
||||
type: 'success' | 'error' | 'warning' | 'info',
|
||||
duration: number = 3000,
|
||||
) {
|
||||
let container = document.querySelector('.toast-container');
|
||||
|
||||
@ -3,10 +3,12 @@ import { ClashAPI, NetShift } from '../../types';
|
||||
import { executeShellCommand } from '../../../helpers';
|
||||
import {
|
||||
ComponentActionStartResponse,
|
||||
ComponentActionStatus,
|
||||
SingBoxComponentActionResult,
|
||||
parseComponentActionStatus,
|
||||
pollSingBoxComponentAction,
|
||||
} from './pollSingBoxComponentAction';
|
||||
import { parseComponentCheckUpdate } from './parseComponentCheckUpdate';
|
||||
|
||||
export const NetShiftShellMethods = {
|
||||
checkDNSAvailable: async () =>
|
||||
@ -173,4 +175,158 @@ export const NetShiftShellMethods = {
|
||||
return parseComponentActionStatus(statusResponse.stdout);
|
||||
});
|
||||
},
|
||||
// Sing-box update checks (sync) — STABLE task-017 contract:
|
||||
// component_action sing_box check_update (extended)
|
||||
// component_action sing_box check_update_stable (stock)
|
||||
// → {success, current_version, latest_version, status}.
|
||||
singBoxCheckUpdate: async (
|
||||
action: 'check_update' | 'check_update_stable',
|
||||
): Promise<NetShift.ComponentCheckUpdateResult> => {
|
||||
const response = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action', 'sing_box', action],
|
||||
timeout: 600000,
|
||||
});
|
||||
|
||||
if (response.stdout) {
|
||||
return parseComponentCheckUpdate(response.stdout);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: response.stderr || '',
|
||||
};
|
||||
},
|
||||
// NetShift update check (sync) — task-029/030 contract:
|
||||
// component_action netshift check_update
|
||||
// → {success, current_version, latest_version, status}. Same shape as the
|
||||
// sing-box cores (parsed by parseComponentCheckUpdate). The status is already
|
||||
// v-normalized server-side, so the caller TRUSTS result.status (no string
|
||||
// compare in TS). Stays on the SYNC component_action path (fast call).
|
||||
netshiftCheckUpdate:
|
||||
async (): Promise<NetShift.ComponentCheckUpdateResult> => {
|
||||
const response = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action', 'netshift', 'check_update'],
|
||||
timeout: 600000,
|
||||
});
|
||||
|
||||
if (response.stdout) {
|
||||
return parseComponentCheckUpdate(response.stdout);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: response.stderr || '',
|
||||
};
|
||||
},
|
||||
// Clear subscription cache (async) — task-039/040 contract:
|
||||
// component_action_async subscription clear_cache + component_action_status
|
||||
// <job>. Deletes all subscription caches then re-downloads, which restarts
|
||||
// the service and can exceed the rpcd ~30s wall — so it MUST run through the
|
||||
// SAME async start+poll mechanism as the sing-box core switch (reusing the
|
||||
// component-agnostic `pollSingBoxComponentAction`). The component/action
|
||||
// strings are EXACTLY 'subscription'/'clear_cache' (match task-039's router).
|
||||
clearSubscriptionCache: async (): Promise<SingBoxComponentActionResult> => {
|
||||
const startResponse = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action_async', 'subscription', 'clear_cache'],
|
||||
});
|
||||
|
||||
let start: ComponentActionStartResponse | null = null;
|
||||
|
||||
if (startResponse.stdout) {
|
||||
try {
|
||||
start = JSON.parse(
|
||||
startResponse.stdout,
|
||||
) as ComponentActionStartResponse;
|
||||
} catch (_e) {
|
||||
start = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!start || start.success !== true || !start.job_id) {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
start?.message ||
|
||||
startResponse.stderr ||
|
||||
_('Failed to clear subscription cache'),
|
||||
};
|
||||
}
|
||||
|
||||
const jobId = start.job_id;
|
||||
|
||||
return pollSingBoxComponentAction(async () => {
|
||||
const statusResponse = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action_status', jobId],
|
||||
});
|
||||
|
||||
if (!statusResponse.stdout) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parseComponentActionStatus(statusResponse.stdout);
|
||||
});
|
||||
},
|
||||
// NetShift self-update (async) — STABLE task-017 contract:
|
||||
// component_action_async netshift self_update + component_action_status <job>.
|
||||
// Reuses the component-agnostic poll. Because the package install swaps
|
||||
// /usr/bin/netshift mid-job, status polls can transiently fail (rpcd / binary
|
||||
// swap); once the job has STARTED we treat such failures leniently — keep
|
||||
// polling (return a synthetic running status) instead of aborting hard, so a
|
||||
// successful self-update is not misreported as a failure. The UI reloads the
|
||||
// page on success.
|
||||
netshiftSelfUpdate: async (): Promise<SingBoxComponentActionResult> => {
|
||||
const startResponse = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action_async', 'netshift', 'self_update'],
|
||||
});
|
||||
|
||||
let start: ComponentActionStartResponse | null = null;
|
||||
|
||||
if (startResponse.stdout) {
|
||||
try {
|
||||
start = JSON.parse(
|
||||
startResponse.stdout,
|
||||
) as ComponentActionStartResponse;
|
||||
} catch (_e) {
|
||||
start = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!start || start.success !== true || !start.job_id) {
|
||||
return {
|
||||
success: false,
|
||||
message:
|
||||
start?.message || startResponse.stderr || _('Self-update failed'),
|
||||
};
|
||||
}
|
||||
|
||||
const jobId = start.job_id;
|
||||
|
||||
return pollSingBoxComponentAction(async () => {
|
||||
// Lenient mid-job polling: any exec/parse error AFTER a successful start
|
||||
// is reported as "still running" so the binary swap doesn't end the loop
|
||||
// prematurely. The MAX_POLLS backstop still bounds the loop.
|
||||
try {
|
||||
const statusResponse = await executeShellCommand({
|
||||
command: '/usr/bin/netshift',
|
||||
args: ['component_action_status', jobId],
|
||||
});
|
||||
|
||||
if (!statusResponse.stdout) {
|
||||
return { running: true } as ComponentActionStatus;
|
||||
}
|
||||
|
||||
return (
|
||||
parseComponentActionStatus(statusResponse.stdout) ??
|
||||
({ running: true } as ComponentActionStatus)
|
||||
);
|
||||
} catch (_e) {
|
||||
return { running: true } as ComponentActionStatus;
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
@ -0,0 +1,58 @@
|
||||
import { NetShift } from '../../types';
|
||||
|
||||
const VALID_STATUSES: NetShift.ComponentUpdateStatus[] = [
|
||||
'latest',
|
||||
'outdated',
|
||||
'dev',
|
||||
'not_installed',
|
||||
];
|
||||
|
||||
function normalizeStatus(
|
||||
status: unknown,
|
||||
): NetShift.ComponentUpdateStatus | undefined {
|
||||
if (
|
||||
typeof status === 'string' &&
|
||||
(VALID_STATUSES as string[]).includes(status)
|
||||
) {
|
||||
return status as NetShift.ComponentUpdateStatus;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the STABLE JSON echoed by the sync update-check actions
|
||||
* (`component_action sing_box check_update` /
|
||||
* `component_action sing_box check_update_stable`):
|
||||
* `{success, current_version, latest_version, status}`.
|
||||
*
|
||||
* Pure (types-only import) so it is unit-testable without dragging in the
|
||||
* helpers barrel (which pulls TabService → MutationObserver and crashes the
|
||||
* node test env at collect time).
|
||||
*/
|
||||
export function parseComponentCheckUpdate(
|
||||
stdout: string,
|
||||
): NetShift.ComponentCheckUpdateResult {
|
||||
try {
|
||||
const parsed = JSON.parse(stdout) as Record<string, unknown>;
|
||||
|
||||
return {
|
||||
success: Boolean(parsed.success),
|
||||
current_version:
|
||||
typeof parsed.current_version === 'string'
|
||||
? parsed.current_version
|
||||
: undefined,
|
||||
latest_version:
|
||||
typeof parsed.latest_version === 'string'
|
||||
? parsed.latest_version
|
||||
: undefined,
|
||||
status: normalizeStatus(parsed.status),
|
||||
message: typeof parsed.message === 'string' ? parsed.message : undefined,
|
||||
};
|
||||
} catch (_e) {
|
||||
return {
|
||||
success: false,
|
||||
message: stdout,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseComponentCheckUpdate } from '../parseComponentCheckUpdate';
|
||||
|
||||
describe('parseComponentCheckUpdate', () => {
|
||||
it('parses the STABLE check-update JSON', () => {
|
||||
const result = parseComponentCheckUpdate(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
current_version: '1.12.0',
|
||||
latest_version: '1.12.9',
|
||||
status: 'outdated',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
success: true,
|
||||
current_version: '1.12.0',
|
||||
latest_version: '1.12.9',
|
||||
status: 'outdated',
|
||||
message: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(['latest', 'outdated', 'dev', 'not_installed'])(
|
||||
'accepts the valid status %s',
|
||||
(status) => {
|
||||
const result = parseComponentCheckUpdate(
|
||||
JSON.stringify({ success: true, status }),
|
||||
);
|
||||
|
||||
expect(result.status).toBe(status);
|
||||
},
|
||||
);
|
||||
|
||||
it('drops an unknown status to undefined', () => {
|
||||
const result = parseComponentCheckUpdate(
|
||||
JSON.stringify({ success: true, status: 'weird' }),
|
||||
);
|
||||
|
||||
expect(result.status).toBeUndefined();
|
||||
});
|
||||
|
||||
it('returns success:false with the raw stdout on invalid JSON', () => {
|
||||
const result = parseComponentCheckUpdate('not json');
|
||||
|
||||
expect(result).toEqual({ success: false, message: 'not json' });
|
||||
});
|
||||
|
||||
it('coerces a missing success to false', () => {
|
||||
const result = parseComponentCheckUpdate(JSON.stringify({}));
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
@ -1,5 +1,11 @@
|
||||
import { NetShift } from '../types';
|
||||
import { initialDiagnosticStore } from '../tabs/diagnostic/diagnostic.store';
|
||||
import { initialManagerStore } from '../tabs/manager/manager.store';
|
||||
import type { ManagerComponentKey } from '../tabs/manager/cards';
|
||||
|
||||
// Single source of truth for the component key union lives in `tabs/manager/cards`;
|
||||
// re-export it here so store consumers keep their existing import path.
|
||||
export type { ManagerComponentKey };
|
||||
|
||||
function jsonStableStringify<T, V>(obj: T): string {
|
||||
return JSON.stringify(obj, (_, value) => {
|
||||
@ -180,7 +186,7 @@ export interface StoreType {
|
||||
globalCheck: { loading: boolean };
|
||||
viewLogs: { loading: boolean };
|
||||
showSingBoxConfig: { loading: boolean };
|
||||
singBoxInstall: { loading: boolean };
|
||||
clearSubscriptionCache: { loading: boolean };
|
||||
};
|
||||
diagnosticsSystemInfo: {
|
||||
loading: boolean;
|
||||
@ -192,6 +198,21 @@ export interface StoreType {
|
||||
device_model: string;
|
||||
sing_box_extended: 0 | 1;
|
||||
};
|
||||
managerActions: {
|
||||
netshiftCheck: { loading: boolean };
|
||||
netshiftUpdate: { loading: boolean };
|
||||
singBoxStockCheck: { loading: boolean };
|
||||
singBoxStockAction: { loading: boolean };
|
||||
singBoxExtendedCheck: { loading: boolean };
|
||||
singBoxExtendedAction: { loading: boolean };
|
||||
};
|
||||
managerChecks: Record<
|
||||
ManagerComponentKey,
|
||||
{
|
||||
status: NetShift.ComponentUpdateStatus | null;
|
||||
latest_version: string;
|
||||
}
|
||||
>;
|
||||
}
|
||||
|
||||
const initialStore: StoreType = {
|
||||
@ -226,6 +247,7 @@ const initialStore: StoreType = {
|
||||
data: [],
|
||||
},
|
||||
...initialDiagnosticStore,
|
||||
...initialManagerStore,
|
||||
};
|
||||
|
||||
export const store = new StoreService<StoreType>(initialStore);
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { renderButton } from '../../../../partials';
|
||||
import { NetShift } from '../../../types';
|
||||
|
||||
interface IRenderSectionsProps {
|
||||
@ -13,7 +14,7 @@ function renderFailedState() {
|
||||
return E(
|
||||
'div',
|
||||
{
|
||||
class: 'pdk_dashboard-page__outbound-section centered',
|
||||
class: 'card pdk_dashboard-page__outbound-section centered',
|
||||
style: 'height: 127px',
|
||||
},
|
||||
E('span', {}, [E('span', {}, _('Dashboard currently unavailable'))]),
|
||||
@ -23,7 +24,7 @@ function renderFailedState() {
|
||||
function renderLoadingState() {
|
||||
return E('div', {
|
||||
id: 'dashboard-sections-grid-skeleton',
|
||||
class: 'pdk_dashboard-page__outbound-section skeleton',
|
||||
class: 'card pdk_dashboard-page__outbound-section skeleton',
|
||||
style: 'height: 127px',
|
||||
});
|
||||
}
|
||||
@ -64,7 +65,7 @@ export function renderDefaultState({
|
||||
return E(
|
||||
'div',
|
||||
{
|
||||
class: `pdk_dashboard-page__outbound-grid__item ${outbound.selected ? 'pdk_dashboard-page__outbound-grid__item--active' : ''} ${section.withTagSelect ? 'pdk_dashboard-page__outbound-grid__item--selectable' : ''}`,
|
||||
class: `card pdk_dashboard-page__outbound-grid__item ${outbound.selected ? 'pdk_dashboard-page__outbound-grid__item--active' : ''} ${section.withTagSelect ? 'pdk_dashboard-page__outbound-grid__item--selectable' : ''}`,
|
||||
click: () =>
|
||||
section.withTagSelect &&
|
||||
onChooseOutbound(section.code, outbound.code),
|
||||
@ -87,7 +88,7 @@ export function renderDefaultState({
|
||||
);
|
||||
}
|
||||
|
||||
return E('div', { class: 'pdk_dashboard-page__outbound-section' }, [
|
||||
return E('div', { class: 'card pdk_dashboard-page__outbound-section' }, [
|
||||
// Title with test latency
|
||||
E('div', { class: 'pdk_dashboard-page__outbound-section__title-section' }, [
|
||||
E(
|
||||
@ -99,14 +100,11 @@ export function renderDefaultState({
|
||||
),
|
||||
latencyFetching
|
||||
? E('div', { class: 'skeleton', style: 'width: 99px; height: 28px' })
|
||||
: E(
|
||||
'button',
|
||||
{
|
||||
class: 'btn dashboard-sections-grid-item-test-latency',
|
||||
click: () => testLatency(),
|
||||
},
|
||||
_('Test latency'),
|
||||
),
|
||||
: renderButton({
|
||||
text: _('Test latency'),
|
||||
onClick: () => testLatency(),
|
||||
classNames: ['dashboard-sections-grid-item-test-latency'],
|
||||
}),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
|
||||
@ -17,7 +17,7 @@ function renderFailedState() {
|
||||
{
|
||||
id: '',
|
||||
style: 'height: 78px',
|
||||
class: 'pdk_dashboard-page__widgets-section__item centered',
|
||||
class: 'card pdk_dashboard-page__widgets-section__item centered',
|
||||
},
|
||||
_('Currently unavailable'),
|
||||
);
|
||||
@ -29,14 +29,14 @@ function renderLoadingState() {
|
||||
{
|
||||
id: '',
|
||||
style: 'height: 78px',
|
||||
class: 'pdk_dashboard-page__widgets-section__item skeleton',
|
||||
class: 'card pdk_dashboard-page__widgets-section__item skeleton',
|
||||
},
|
||||
'',
|
||||
);
|
||||
}
|
||||
|
||||
function renderDefaultState({ title, items }: IRenderWidgetProps) {
|
||||
return E('div', { class: 'pdk_dashboard-page__widgets-section__item' }, [
|
||||
return E('div', { class: 'card pdk_dashboard-page__widgets-section__item' }, [
|
||||
E(
|
||||
'b',
|
||||
{ class: 'pdk_dashboard-page__widgets-section__item__title' },
|
||||
|
||||
@ -27,9 +27,6 @@ export const styles = `
|
||||
}
|
||||
|
||||
.pdk_dashboard-page__widgets-section__item {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.pdk_dashboard-page__widgets-section__item__title {}
|
||||
@ -50,9 +47,6 @@ export const styles = `
|
||||
|
||||
.pdk_dashboard-page__outbound-section {
|
||||
margin-top: 10px;
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.pdk_dashboard-page__outbound-section__title-section {
|
||||
@ -74,9 +68,6 @@ export const styles = `
|
||||
}
|
||||
|
||||
.pdk_dashboard-page__outbound-grid__item {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
transition: border 0.2s ease;
|
||||
}
|
||||
|
||||
|
||||
@ -72,6 +72,17 @@ export async function runDnsCheck() {
|
||||
key: _('Main DNS'),
|
||||
value: `${data.dns_server} [${data.dns_type}]`,
|
||||
},
|
||||
...insertIf<IDiagnosticsChecksItem>(
|
||||
typeof data.dns_via_outbound_tag === 'string' &&
|
||||
data.dns_via_outbound_tag.length > 0,
|
||||
[
|
||||
{
|
||||
state: 'success',
|
||||
key: _('Main DNS via outbound'),
|
||||
value: data.dns_via_outbound_tag ?? '',
|
||||
},
|
||||
],
|
||||
),
|
||||
{
|
||||
state: data.dns_on_router ? 'success' : 'error',
|
||||
key: _('DNS on router'),
|
||||
|
||||
@ -40,7 +40,6 @@ export async function runNftCheck() {
|
||||
Boolean(data.rules_mangle_exist) &&
|
||||
Boolean(data.rules_mangle_counters) &&
|
||||
Boolean(data.rules_mangle_output_exist) &&
|
||||
Boolean(data.rules_mangle_output_counters) &&
|
||||
Boolean(data.rules_proxy_exist) &&
|
||||
Boolean(data.rules_proxy_counters) &&
|
||||
!data.rules_other_mark_exist;
|
||||
@ -50,7 +49,6 @@ export async function runNftCheck() {
|
||||
Boolean(data.rules_mangle_exist) ||
|
||||
Boolean(data.rules_mangle_counters) ||
|
||||
Boolean(data.rules_mangle_output_exist) ||
|
||||
Boolean(data.rules_mangle_output_counters) ||
|
||||
Boolean(data.rules_proxy_exist) ||
|
||||
Boolean(data.rules_proxy_counters) ||
|
||||
!data.rules_other_mark_exist;
|
||||
@ -84,11 +82,6 @@ export async function runNftCheck() {
|
||||
key: _('Rules mangle output exist'),
|
||||
value: '',
|
||||
},
|
||||
{
|
||||
state: data.rules_mangle_output_counters ? 'success' : 'error',
|
||||
key: _('Rules mangle output counters'),
|
||||
value: '',
|
||||
},
|
||||
{
|
||||
state: data.rules_proxy_exist ? 'success' : 'error',
|
||||
key: _('Rules proxy exist'),
|
||||
|
||||
@ -46,7 +46,7 @@ export const initialDiagnosticStore: Pick<
|
||||
showSingBoxConfig: {
|
||||
loading: false,
|
||||
},
|
||||
singBoxInstall: {
|
||||
clearSubscriptionCache: {
|
||||
loading: false,
|
||||
},
|
||||
},
|
||||
|
||||
@ -316,47 +316,45 @@ async function handleShowSingBoxConfig() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleInstallSingBox() {
|
||||
async function handleClearSubscriptionCache() {
|
||||
const diagnosticsActions = store.get().diagnosticsActions;
|
||||
store.set({
|
||||
diagnosticsActions: {
|
||||
...diagnosticsActions,
|
||||
singBoxInstall: { loading: true },
|
||||
clearSubscriptionCache: { loading: true },
|
||||
},
|
||||
});
|
||||
|
||||
const isExtended = store.get().diagnosticsSystemInfo.sing_box_extended === 1;
|
||||
|
||||
showToast(
|
||||
_('Switching sing-box core, this may take a few minutes…'),
|
||||
'success',
|
||||
_('Clearing subscription cache and re-downloading… this may take a minute'),
|
||||
'info',
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await NetShiftShellMethods.singBoxComponentAction(
|
||||
isExtended ? 'install_stable' : 'install_extended',
|
||||
);
|
||||
const result = await NetShiftShellMethods.clearSubscriptionCache();
|
||||
|
||||
if (result.success) {
|
||||
showToast(
|
||||
_('Sing-box core changed, version: ') + (result.version || ''),
|
||||
'success',
|
||||
);
|
||||
showToast(_('Subscription cache cleared and re-downloaded'), 'success');
|
||||
} else {
|
||||
logger.error('[DIAGNOSTIC]', 'handleInstallSingBox - e', result);
|
||||
showToast(result.message || _('Failed to execute!'), 'error');
|
||||
logger.error(
|
||||
'[DIAGNOSTIC]',
|
||||
'handleClearSubscriptionCache - result',
|
||||
result,
|
||||
);
|
||||
showToast(_('Failed to clear subscription cache'), 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('[DIAGNOSTIC]', 'handleInstallSingBox - e', e);
|
||||
showToast(_('Failed to execute!'), 'error');
|
||||
logger.error('[DIAGNOSTIC]', 'handleClearSubscriptionCache - e', e);
|
||||
showToast(_('Failed to clear subscription cache'), 'error');
|
||||
} finally {
|
||||
await fetchServicesInfo();
|
||||
store.set({
|
||||
diagnosticsActions: {
|
||||
...diagnosticsActions,
|
||||
singBoxInstall: { loading: false },
|
||||
clearSubscriptionCache: { loading: false },
|
||||
},
|
||||
});
|
||||
await fetchSystemInfo();
|
||||
store.reset(['diagnosticsChecks']);
|
||||
}
|
||||
}
|
||||
|
||||
@ -448,15 +446,12 @@ function renderDiagnosticAvailableActionsWidget() {
|
||||
onClick: handleShowSingBoxConfig,
|
||||
disabled: atLeastOneServiceCommandLoading,
|
||||
},
|
||||
singBoxInstall: {
|
||||
loading: diagnosticsActions.singBoxInstall.loading,
|
||||
clearSubscriptionCache: {
|
||||
loading: diagnosticsActions.clearSubscriptionCache.loading,
|
||||
visible: true,
|
||||
onClick: handleInstallSingBox,
|
||||
disabled:
|
||||
atLeastOneServiceCommandLoading ||
|
||||
diagnosticsActions.singBoxInstall.loading,
|
||||
onClick: handleClearSubscriptionCache,
|
||||
disabled: atLeastOneServiceCommandLoading,
|
||||
},
|
||||
singBoxExtended: store.get().diagnosticsSystemInfo.sing_box_extended,
|
||||
});
|
||||
|
||||
return preserveScrollForPage(() => {
|
||||
|
||||
@ -27,8 +27,7 @@ interface IRenderAvailableActionsProps {
|
||||
globalCheck: ActionProps;
|
||||
viewLogs: ActionProps;
|
||||
showSingBoxConfig: ActionProps;
|
||||
singBoxInstall: ActionProps;
|
||||
singBoxExtended: 0 | 1;
|
||||
clearSubscriptionCache: ActionProps;
|
||||
}
|
||||
|
||||
export function renderAvailableActions({
|
||||
@ -40,10 +39,9 @@ export function renderAvailableActions({
|
||||
globalCheck,
|
||||
viewLogs,
|
||||
showSingBoxConfig,
|
||||
singBoxInstall,
|
||||
singBoxExtended,
|
||||
clearSubscriptionCache,
|
||||
}: IRenderAvailableActionsProps) {
|
||||
return E('div', { class: 'pdk_diagnostic-page__right-bar__actions' }, [
|
||||
return E('div', { class: 'card pdk_diagnostic-page__right-bar__actions' }, [
|
||||
E('b', {}, _('Available actions')),
|
||||
...insertIf(restart.visible, [
|
||||
renderButton({
|
||||
@ -122,13 +120,13 @@ export function renderAvailableActions({
|
||||
disabled: showSingBoxConfig.disabled,
|
||||
}),
|
||||
]),
|
||||
...insertIf(singBoxInstall.visible, [
|
||||
...insertIf(clearSubscriptionCache.visible, [
|
||||
renderButton({
|
||||
onClick: singBoxInstall.onClick,
|
||||
onClick: clearSubscriptionCache.onClick,
|
||||
icon: renderRotateCcwIcon24,
|
||||
text: singBoxExtended ? _('Install stable') : _('Install extended'),
|
||||
loading: singBoxInstall.loading,
|
||||
disabled: singBoxInstall.disabled,
|
||||
text: _('Clear subscription cache'),
|
||||
loading: clearSubscriptionCache.loading,
|
||||
disabled: clearSubscriptionCache.disabled,
|
||||
}),
|
||||
]),
|
||||
]);
|
||||
|
||||
@ -56,7 +56,7 @@ function renderLoadingState(props: IRenderCheckSectionProps) {
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic_alert pdk_diagnostic_alert--loading' },
|
||||
{ class: 'card pdk_diagnostic_alert pdk_diagnostic_alert--loading' },
|
||||
[
|
||||
iconWrap,
|
||||
E('div', { class: 'pdk_diagnostic_alert__content' }, [
|
||||
@ -79,7 +79,7 @@ function renderWarningState(props: IRenderCheckSectionProps) {
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic_alert pdk_diagnostic_alert--warning' },
|
||||
{ class: 'card pdk_diagnostic_alert pdk_diagnostic_alert--warning' },
|
||||
[
|
||||
iconWrap,
|
||||
E('div', { class: 'pdk_diagnostic_alert__content' }, [
|
||||
@ -102,7 +102,7 @@ function renderErrorState(props: IRenderCheckSectionProps) {
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic_alert pdk_diagnostic_alert--error' },
|
||||
{ class: 'card pdk_diagnostic_alert pdk_diagnostic_alert--error' },
|
||||
[
|
||||
iconWrap,
|
||||
E('div', { class: 'pdk_diagnostic_alert__content' }, [
|
||||
@ -125,7 +125,7 @@ function renderSuccessState(props: IRenderCheckSectionProps) {
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic_alert pdk_diagnostic_alert--success' },
|
||||
{ class: 'card pdk_diagnostic_alert pdk_diagnostic_alert--success' },
|
||||
[
|
||||
iconWrap,
|
||||
E('div', { class: 'pdk_diagnostic_alert__content' }, [
|
||||
@ -148,7 +148,7 @@ function renderSkippedState(props: IRenderCheckSectionProps) {
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic_alert pdk_diagnostic_alert--skipped' },
|
||||
{ class: 'card pdk_diagnostic_alert pdk_diagnostic_alert--skipped' },
|
||||
[
|
||||
iconWrap,
|
||||
E('div', { class: 'pdk_diagnostic_alert__content' }, [
|
||||
|
||||
@ -14,36 +14,40 @@ interface IRenderSystemInfoProps {
|
||||
}
|
||||
|
||||
export function renderSystemInfo({ items }: IRenderSystemInfoProps) {
|
||||
return E('div', { class: 'pdk_diagnostic-page__right-bar__system-info' }, [
|
||||
E(
|
||||
'b',
|
||||
{ class: 'pdk_diagnostic-page__right-bar__system-info__title' },
|
||||
_('System information'),
|
||||
),
|
||||
...items.map((item) => {
|
||||
const tagClass = [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag',
|
||||
...insertIf(item.tag?.kind === 'warning', [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag--warning',
|
||||
]),
|
||||
...insertIf(item.tag?.kind === 'success', [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag--success',
|
||||
]),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic-page__right-bar__system-info__row' },
|
||||
[
|
||||
E('b', {}, item.key),
|
||||
E('div', {}, [
|
||||
E('span', {}, item.value),
|
||||
E('span', { class: tagClass }, item?.tag?.label),
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'card pdk_diagnostic-page__right-bar__system-info' },
|
||||
[
|
||||
E(
|
||||
'b',
|
||||
{ class: 'pdk_diagnostic-page__right-bar__system-info__title' },
|
||||
_('System information'),
|
||||
),
|
||||
...items.map((item) => {
|
||||
const tagClass = [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag',
|
||||
...insertIf(item.tag?.kind === 'warning', [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag--warning',
|
||||
]),
|
||||
],
|
||||
);
|
||||
}),
|
||||
]);
|
||||
...insertIf(item.tag?.kind === 'success', [
|
||||
'pdk_diagnostic-page__right-bar__system-info__row__tag--success',
|
||||
]),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
|
||||
return E(
|
||||
'div',
|
||||
{ class: 'pdk_diagnostic-page__right-bar__system-info__row' },
|
||||
[
|
||||
E('b', {}, item.key),
|
||||
E('div', {}, [
|
||||
E('span', {}, item.value),
|
||||
E('span', { class: tagClass }, item?.tag?.label),
|
||||
]),
|
||||
],
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@ -9,6 +9,7 @@ export function renderWikiDisclaimer(kind: 'default' | 'error' | 'warning') {
|
||||
iconWrap.appendChild(renderBookOpenTextIcon24());
|
||||
|
||||
const className = [
|
||||
'card',
|
||||
'pdk_diagnostic-page__right-bar__wiki',
|
||||
...insertIf(kind === 'error', [
|
||||
'pdk_diagnostic-page__right-bar__wiki--error',
|
||||
|
||||
@ -29,10 +29,6 @@ export const styles = `
|
||||
}
|
||||
|
||||
.pdk_diagnostic-page__right-bar__wiki {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: auto;
|
||||
grid-row-gap: 10px;
|
||||
@ -54,21 +50,12 @@ export const styles = `
|
||||
.pdk_diagnostic-page__right-bar__wiki__texts {}
|
||||
|
||||
.pdk_diagnostic-page__right-bar__actions {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: auto;
|
||||
grid-row-gap: 10px;
|
||||
|
||||
}
|
||||
|
||||
.pdk_diagnostic-page__right-bar__system-info {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: auto;
|
||||
grid-row-gap: 10px;
|
||||
@ -120,14 +107,10 @@ export const styles = `
|
||||
}
|
||||
|
||||
.pdk_diagnostic_alert {
|
||||
border: 2px var(--background-color-low, lightgray) solid;
|
||||
border-radius: 4px;
|
||||
|
||||
display: grid;
|
||||
grid-template-columns: 24px 1fr;
|
||||
grid-column-gap: 10px;
|
||||
align-items: center;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.pdk_diagnostic_alert--loading {
|
||||
|
||||
@ -1,2 +1,3 @@
|
||||
export * from './dashboard';
|
||||
export * from './diagnostic';
|
||||
export * from './manager';
|
||||
|
||||
264
fe-app-netshift/src/netshift/tabs/manager/cards.ts
Normal file
264
fe-app-netshift/src/netshift/tabs/manager/cards.ts
Normal file
@ -0,0 +1,264 @@
|
||||
import { NetShift } from '../../types';
|
||||
import { normalizeCompiledVersion } from '../../../helpers/normalizeCompiledVersion';
|
||||
|
||||
export type ManagerComponentKey =
|
||||
| 'netshift'
|
||||
| 'sing_box_stock'
|
||||
| 'sing_box_extended';
|
||||
|
||||
// `check` = a sing-box update check (routed to the sing-box check method);
|
||||
// `check_netshift` = the NetShift card's on-demand check (task-030), which now
|
||||
// calls the dedicated `component_action netshift check_update` action and writes
|
||||
// `managerChecks.netshift` — exactly like the sing-box cores. Keeping it a
|
||||
// DISTINCT kind guarantees a NetShift check can never be routed to the sing-box
|
||||
// check method (the dispatcher routes it to runNetshiftCheck).
|
||||
export type ManagerActionKind =
|
||||
| 'check'
|
||||
| 'check_netshift'
|
||||
| 'update'
|
||||
| 'switch'
|
||||
| 'self_update';
|
||||
|
||||
export interface ManagerActionDescriptor {
|
||||
// The store-slice key driving this button's loading flag.
|
||||
loadingKey:
|
||||
| 'netshiftCheck'
|
||||
| 'netshiftUpdate'
|
||||
| 'singBoxStockCheck'
|
||||
| 'singBoxStockAction'
|
||||
| 'singBoxExtendedCheck'
|
||||
| 'singBoxExtendedAction';
|
||||
kind: ManagerActionKind;
|
||||
text: string;
|
||||
// For `update`/`switch`: the backend install action; for `self_update`:
|
||||
// 'self_update'; for `check`: the sing-box check action; for `check_netshift`:
|
||||
// the NetShift check action (routed to the dedicated NetShift check method).
|
||||
backendAction?:
|
||||
| 'check_update'
|
||||
| 'check_update_stable'
|
||||
| 'install_stable'
|
||||
| 'install_extended'
|
||||
| 'self_update';
|
||||
}
|
||||
|
||||
export interface ManagerCardTag {
|
||||
label: string;
|
||||
kind: 'neutral' | 'success' | 'warning';
|
||||
}
|
||||
|
||||
export interface ManagerCardDescriptor {
|
||||
key: ManagerComponentKey;
|
||||
title: string;
|
||||
version: string;
|
||||
installed: boolean;
|
||||
tag?: ManagerCardTag;
|
||||
actions: ManagerActionDescriptor[];
|
||||
}
|
||||
|
||||
export type ManagerSystemInfo = {
|
||||
netshift_version: string;
|
||||
netshift_latest_version: string;
|
||||
sing_box_version: string;
|
||||
sing_box_extended: 0 | 1;
|
||||
};
|
||||
|
||||
export type ManagerCheckState = {
|
||||
status: NetShift.ComponentUpdateStatus | null;
|
||||
latest_version: string;
|
||||
};
|
||||
|
||||
const NOT_INSTALLED = 'not installed';
|
||||
|
||||
export function isSingBoxInstalled(systemInfo: ManagerSystemInfo): boolean {
|
||||
const version = systemInfo.sing_box_version;
|
||||
|
||||
return Boolean(version) && version !== NOT_INSTALLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a check status to a status badge. Pure — same logic as podkop-plus
|
||||
* `getCheckTag`, extended with `not_installed`.
|
||||
*/
|
||||
export function getCheckTag(
|
||||
status: NetShift.ComponentUpdateStatus | null,
|
||||
): ManagerCardTag | undefined {
|
||||
if (!status) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (status === 'latest') {
|
||||
return { label: _('Latest'), kind: 'success' };
|
||||
}
|
||||
|
||||
if (status === 'outdated') {
|
||||
return { label: _('Outdated'), kind: 'warning' };
|
||||
}
|
||||
|
||||
if (status === 'not_installed') {
|
||||
return { label: _('Not installed'), kind: 'neutral' };
|
||||
}
|
||||
|
||||
return { label: _('Dev'), kind: 'neutral' };
|
||||
}
|
||||
|
||||
// NetShift status is derived from the on-demand check result (task-030):
|
||||
// `managerChecks.netshift.status` is null until the user presses "Check update"
|
||||
// → neutral card (no badge, no update button). The backend already computes the
|
||||
// v-normalized status, so we TRUST it (no installed-vs-latest string compare).
|
||||
// The `dev`-build guard is kept locally: a dev/placeholder build never shows an
|
||||
// update prompt regardless of any check result.
|
||||
function netshiftStatus(
|
||||
systemInfo: ManagerSystemInfo,
|
||||
check: ManagerCheckState,
|
||||
): NetShift.ComponentUpdateStatus | null {
|
||||
const installed = normalizeCompiledVersion(systemInfo.netshift_version);
|
||||
|
||||
if (installed === 'dev') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return check.status;
|
||||
}
|
||||
|
||||
function netshiftCard(
|
||||
systemInfo: ManagerSystemInfo,
|
||||
check: ManagerCheckState,
|
||||
): ManagerCardDescriptor {
|
||||
const status = netshiftStatus(systemInfo, check);
|
||||
const latest = check.latest_version;
|
||||
const actions: ManagerActionDescriptor[] = [];
|
||||
|
||||
if (status === 'outdated') {
|
||||
actions.push({
|
||||
loadingKey: 'netshiftUpdate',
|
||||
kind: 'self_update',
|
||||
text: latest
|
||||
? _('Install %s').replace('%s', latest)
|
||||
: _('Update NetShift'),
|
||||
backendAction: 'self_update',
|
||||
});
|
||||
} else {
|
||||
actions.push({
|
||||
loadingKey: 'netshiftCheck',
|
||||
kind: 'check_netshift',
|
||||
text: _('Check update'),
|
||||
backendAction: 'check_update',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
key: 'netshift',
|
||||
title: 'NetShift',
|
||||
version: normalizeCompiledVersion(systemInfo.netshift_version),
|
||||
installed: true,
|
||||
tag: getCheckTag(status),
|
||||
actions,
|
||||
};
|
||||
}
|
||||
|
||||
function singBoxStockCard(
|
||||
systemInfo: ManagerSystemInfo,
|
||||
check: ManagerCheckState,
|
||||
): ManagerCardDescriptor {
|
||||
const installed = isSingBoxInstalled(systemInfo);
|
||||
const isActive = installed && systemInfo.sing_box_extended === 0;
|
||||
const actions: ManagerActionDescriptor[] = [];
|
||||
|
||||
if (isActive) {
|
||||
if (check.status === 'outdated') {
|
||||
const latest = check.latest_version;
|
||||
|
||||
actions.push({
|
||||
loadingKey: 'singBoxStockAction',
|
||||
kind: 'update',
|
||||
text: latest ? _('Install %s').replace('%s', latest) : _('Update'),
|
||||
backendAction: 'install_stable',
|
||||
});
|
||||
} else {
|
||||
actions.push({
|
||||
loadingKey: 'singBoxStockCheck',
|
||||
kind: 'check',
|
||||
text: _('Check update'),
|
||||
backendAction: 'check_update_stable',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Either extended is active, or no sing-box at all → offer switch-to-stable.
|
||||
actions.push({
|
||||
loadingKey: 'singBoxStockAction',
|
||||
kind: 'switch',
|
||||
text: _('Switch to stable'),
|
||||
backendAction: 'install_stable',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
key: 'sing_box_stock',
|
||||
title: 'sing-box (stock)',
|
||||
version: isActive ? systemInfo.sing_box_version : _('Not installed'),
|
||||
installed: isActive,
|
||||
tag: isActive ? getCheckTag(check.status) : getCheckTag('not_installed'),
|
||||
actions,
|
||||
};
|
||||
}
|
||||
|
||||
function singBoxExtendedCard(
|
||||
systemInfo: ManagerSystemInfo,
|
||||
check: ManagerCheckState,
|
||||
): ManagerCardDescriptor {
|
||||
const installed = isSingBoxInstalled(systemInfo);
|
||||
const isActive = installed && systemInfo.sing_box_extended === 1;
|
||||
const actions: ManagerActionDescriptor[] = [];
|
||||
|
||||
if (isActive) {
|
||||
if (check.status === 'outdated') {
|
||||
const latest = check.latest_version;
|
||||
|
||||
actions.push({
|
||||
loadingKey: 'singBoxExtendedAction',
|
||||
kind: 'update',
|
||||
text: latest ? _('Install %s').replace('%s', latest) : _('Update'),
|
||||
backendAction: 'install_extended',
|
||||
});
|
||||
} else {
|
||||
actions.push({
|
||||
loadingKey: 'singBoxExtendedCheck',
|
||||
kind: 'check',
|
||||
text: _('Check update'),
|
||||
backendAction: 'check_update',
|
||||
});
|
||||
}
|
||||
} else {
|
||||
actions.push({
|
||||
loadingKey: 'singBoxExtendedAction',
|
||||
kind: 'switch',
|
||||
text: _('Switch to extended'),
|
||||
backendAction: 'install_extended',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
key: 'sing_box_extended',
|
||||
title: 'sing-box (extended)',
|
||||
version: isActive ? systemInfo.sing_box_version : _('Not installed'),
|
||||
installed: isActive,
|
||||
tag: isActive ? getCheckTag(check.status) : getCheckTag('not_installed'),
|
||||
actions,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the three Component Manager cards from systemInfo + per-component check
|
||||
* state. Pure (no DOM, no store) so it is unit-testable; the controller maps
|
||||
* descriptors to DOM + click handlers.
|
||||
*/
|
||||
export function getComponentCards(
|
||||
systemInfo: ManagerSystemInfo,
|
||||
checks: Record<ManagerComponentKey, ManagerCheckState>,
|
||||
): ManagerCardDescriptor[] {
|
||||
return [
|
||||
netshiftCard(systemInfo, checks.netshift),
|
||||
singBoxStockCard(systemInfo, checks.sing_box_stock),
|
||||
singBoxExtendedCard(systemInfo, checks.sing_box_extended),
|
||||
];
|
||||
}
|
||||
9
fe-app-netshift/src/netshift/tabs/manager/index.ts
Normal file
9
fe-app-netshift/src/netshift/tabs/manager/index.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import { render } from './render';
|
||||
import { initController } from './initController';
|
||||
import { styles } from './styles';
|
||||
|
||||
export const ManagerTab = {
|
||||
render,
|
||||
initController,
|
||||
styles,
|
||||
};
|
||||
425
fe-app-netshift/src/netshift/tabs/manager/initController.ts
Normal file
425
fe-app-netshift/src/netshift/tabs/manager/initController.ts
Normal file
@ -0,0 +1,425 @@
|
||||
import { onMount, preserveScrollForPage } from '../../../helpers';
|
||||
import { normalizeCompiledVersion } from '../../../helpers/normalizeCompiledVersion';
|
||||
import { showToast } from '../../../helpers/showToast';
|
||||
import { renderRotateCcwIcon24, renderSearchIcon24 } from '../../../icons';
|
||||
import { renderButton } from '../../../partials';
|
||||
import { NetShiftShellMethods } from '../../methods';
|
||||
import { logger, store, StoreType } from '../../services';
|
||||
import { NetShift } from '../../types';
|
||||
import {
|
||||
ManagerActionDescriptor,
|
||||
ManagerCardDescriptor,
|
||||
ManagerComponentKey,
|
||||
getComponentCards,
|
||||
} from './cards';
|
||||
|
||||
type ManagerActionKey = keyof StoreType['managerActions'];
|
||||
|
||||
let managerLifecycleRegistered = false;
|
||||
let managerControllerInitialized = false;
|
||||
let managerMounted = false;
|
||||
|
||||
async function fetchSystemInfo() {
|
||||
const systemInfo = await NetShiftShellMethods.getSystemInfo();
|
||||
|
||||
if (systemInfo.success) {
|
||||
store.set({
|
||||
diagnosticsSystemInfo: {
|
||||
loading: false,
|
||||
...systemInfo.data,
|
||||
sing_box_extended: systemInfo.data.sing_box_extended === 1 ? 1 : 0,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
store.set({
|
||||
diagnosticsSystemInfo: {
|
||||
loading: false,
|
||||
netshift_version: _('unknown'),
|
||||
netshift_latest_version: _('unknown'),
|
||||
luci_app_version: _('unknown'),
|
||||
sing_box_version: _('unknown'),
|
||||
openwrt_version: _('unknown'),
|
||||
device_model: _('unknown'),
|
||||
sing_box_extended: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function isAnyActionLoading() {
|
||||
return Object.values(store.get().managerActions).some((item) => item.loading);
|
||||
}
|
||||
|
||||
function isSystemInfoLoading() {
|
||||
return store.get().diagnosticsSystemInfo.loading;
|
||||
}
|
||||
|
||||
function setActionLoading(action: ManagerActionKey, loading: boolean) {
|
||||
const managerActions = store.get().managerActions;
|
||||
|
||||
store.set({
|
||||
managerActions: {
|
||||
...managerActions,
|
||||
[action]: { loading },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setCheckResult(
|
||||
component: ManagerComponentKey,
|
||||
status: NetShift.ComponentUpdateStatus | null,
|
||||
latestVersion: string,
|
||||
) {
|
||||
const managerChecks = store.get().managerChecks;
|
||||
|
||||
store.set({
|
||||
managerChecks: {
|
||||
...managerChecks,
|
||||
[component]: {
|
||||
status,
|
||||
latest_version: latestVersion,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function resetCheckResult(component: ManagerComponentKey) {
|
||||
setCheckResult(component, null, '');
|
||||
}
|
||||
|
||||
function getCheckToastMessage(status: NetShift.ComponentUpdateStatus | null) {
|
||||
if (status === 'outdated') {
|
||||
return _('Update is available');
|
||||
}
|
||||
|
||||
if (status === 'dev') {
|
||||
return _('Installed version is newer than release');
|
||||
}
|
||||
|
||||
if (status === 'not_installed') {
|
||||
return _('Not installed');
|
||||
}
|
||||
|
||||
return _('Latest version is installed');
|
||||
}
|
||||
|
||||
// Sing-box check: routes to the sing-box check method (stock or extended) and
|
||||
// stores the result into the matching managerChecks slice.
|
||||
async function runSingBoxCheck(
|
||||
component: ManagerComponentKey,
|
||||
button: ManagerActionDescriptor,
|
||||
) {
|
||||
setActionLoading(button.loadingKey, true);
|
||||
|
||||
try {
|
||||
const parsed = await NetShiftShellMethods.singBoxCheckUpdate(
|
||||
button.backendAction === 'check_update_stable'
|
||||
? 'check_update_stable'
|
||||
: 'check_update',
|
||||
);
|
||||
|
||||
if (!parsed.success) {
|
||||
showToast(parsed.message || _('Failed to execute!'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const status = parsed.status ?? null;
|
||||
|
||||
setCheckResult(component, status, parsed.latest_version || '');
|
||||
showToast(getCheckToastMessage(status), 'success');
|
||||
} catch (error) {
|
||||
logger.error('[MANAGER]', 'runSingBoxCheck failed', error);
|
||||
showToast(_('Failed to execute!'), 'error');
|
||||
} finally {
|
||||
setActionLoading(button.loadingKey, false);
|
||||
}
|
||||
}
|
||||
|
||||
// NetShift check (task-030): on-demand call to the dedicated
|
||||
// `component_action netshift check_update` action, which returns the same
|
||||
// {success, current_version, latest_version, status} contract as the sing-box
|
||||
// cores (status already v-normalized server-side). We TRUST result.status and
|
||||
// write it into managerChecks.netshift — mirroring runSingBoxCheck precisely.
|
||||
async function runNetshiftCheck(button: ManagerActionDescriptor) {
|
||||
setActionLoading(button.loadingKey, true);
|
||||
|
||||
try {
|
||||
const parsed = await NetShiftShellMethods.netshiftCheckUpdate();
|
||||
|
||||
if (!parsed.success) {
|
||||
showToast(parsed.message || _('Failed to execute!'), 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const status = parsed.status ?? null;
|
||||
|
||||
setCheckResult('netshift', status, parsed.latest_version || '');
|
||||
showToast(getCheckToastMessage(status), 'success');
|
||||
} catch (error) {
|
||||
logger.error('[MANAGER]', 'runNetshiftCheck failed', error);
|
||||
showToast(_('Failed to execute!'), 'error');
|
||||
} finally {
|
||||
setActionLoading(button.loadingKey, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSingBoxMutation(
|
||||
component: ManagerComponentKey,
|
||||
button: ManagerActionDescriptor,
|
||||
) {
|
||||
setActionLoading(button.loadingKey, true);
|
||||
showToast(_('Switching sing-box core, this may take a few minutes…'), 'info');
|
||||
|
||||
try {
|
||||
const result = await NetShiftShellMethods.singBoxComponentAction(
|
||||
button.backendAction === 'install_stable'
|
||||
? 'install_stable'
|
||||
: 'install_extended',
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
const changed = _('Sing-box core changed, version:');
|
||||
|
||||
showToast(`${changed} ${result.version || ''}`.trim(), 'success');
|
||||
resetCheckResult(component);
|
||||
await fetchSystemInfo();
|
||||
} else {
|
||||
logger.error('[MANAGER]', 'runSingBoxMutation failed', result);
|
||||
showToast(result.message || _('Failed to execute!'), 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('[MANAGER]', 'runSingBoxMutation failed', error);
|
||||
showToast(_('Failed to execute!'), 'error');
|
||||
} finally {
|
||||
setActionLoading(button.loadingKey, false);
|
||||
}
|
||||
}
|
||||
|
||||
function reloadPageAfterSelfUpdate() {
|
||||
window.setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1200);
|
||||
}
|
||||
|
||||
async function runNetshiftSelfUpdate(button: ManagerActionDescriptor) {
|
||||
setActionLoading(button.loadingKey, true);
|
||||
// Warning-style toast: self-update is long and ends in a page reload.
|
||||
showToast(
|
||||
_('Updating NetShift, this may take a few minutes; the page will reload…'),
|
||||
'warning',
|
||||
6000,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await NetShiftShellMethods.netshiftSelfUpdate();
|
||||
|
||||
if (result.success) {
|
||||
const updated = _('NetShift updated, version:');
|
||||
|
||||
showToast(`${updated} ${result.version || ''}`.trim(), 'success', 1200);
|
||||
reloadPageAfterSelfUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
logger.error('[MANAGER]', 'runNetshiftSelfUpdate failed', result);
|
||||
showToast(result.message || _('Failed to execute!'), 'error');
|
||||
setActionLoading(button.loadingKey, false);
|
||||
} catch (error) {
|
||||
logger.error('[MANAGER]', 'runNetshiftSelfUpdate failed', error);
|
||||
showToast(_('Failed to execute!'), 'error');
|
||||
setActionLoading(button.loadingKey, false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleManagerAction(
|
||||
card: ManagerCardDescriptor,
|
||||
button: ManagerActionDescriptor,
|
||||
) {
|
||||
if (isAnyActionLoading()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (button.kind === 'check_netshift') {
|
||||
void runNetshiftCheck(button);
|
||||
return;
|
||||
}
|
||||
|
||||
if (button.kind === 'check') {
|
||||
void runSingBoxCheck(card.key, button);
|
||||
return;
|
||||
}
|
||||
|
||||
if (button.kind === 'self_update') {
|
||||
void runNetshiftSelfUpdate(button);
|
||||
return;
|
||||
}
|
||||
|
||||
// `update` / `switch` — both drive the async sing-box install contract.
|
||||
void runSingBoxMutation(card.key, button);
|
||||
}
|
||||
|
||||
function renderComponentTag(card: ManagerCardDescriptor) {
|
||||
if (!card.tag) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return E(
|
||||
'span',
|
||||
{
|
||||
class: [
|
||||
'pdk_manager-page__component__tag',
|
||||
card.tag.kind === 'success'
|
||||
? 'pdk_manager-page__component__tag--success'
|
||||
: '',
|
||||
card.tag.kind === 'warning'
|
||||
? 'pdk_manager-page__component__tag--warning'
|
||||
: '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
},
|
||||
card.tag.label,
|
||||
);
|
||||
}
|
||||
|
||||
function renderComponentCard(card: ManagerCardDescriptor) {
|
||||
const managerActions = store.get().managerActions;
|
||||
const anyActionLoading = isAnyActionLoading();
|
||||
const systemInfoLoading = isSystemInfoLoading();
|
||||
const tag = renderComponentTag(card);
|
||||
const headerChildren: Node[] = [
|
||||
E('b', { class: 'pdk_manager-page__component__title' }, card.title),
|
||||
];
|
||||
|
||||
if (tag) {
|
||||
headerChildren.push(
|
||||
E('div', { class: 'pdk_manager-page__component__status' }, [tag]),
|
||||
);
|
||||
}
|
||||
|
||||
return E('div', { class: 'card pdk_manager-page__component' }, [
|
||||
E('div', { class: 'pdk_manager-page__component__header' }, headerChildren),
|
||||
E('div', { class: 'pdk_manager-page__component__version' }, [
|
||||
E(
|
||||
'span',
|
||||
{ class: 'pdk_manager-page__component__version__label' },
|
||||
_('Version'),
|
||||
),
|
||||
E(
|
||||
'span',
|
||||
{ class: 'pdk_manager-page__component__version__value' },
|
||||
card.version,
|
||||
),
|
||||
]),
|
||||
E(
|
||||
'div',
|
||||
{ class: 'pdk_manager-page__component__actions' },
|
||||
card.actions.map((action) => {
|
||||
const loading = managerActions[action.loadingKey].loading;
|
||||
|
||||
return renderButton({
|
||||
text: action.text,
|
||||
icon:
|
||||
action.kind === 'check' || action.kind === 'check_netshift'
|
||||
? renderSearchIcon24
|
||||
: renderRotateCcwIcon24,
|
||||
loading,
|
||||
disabled: systemInfoLoading || (anyActionLoading && !loading),
|
||||
onClick: () => handleManagerAction(card, action),
|
||||
});
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
function renderManagerComponents() {
|
||||
const container = document.getElementById('pdk_manager-components');
|
||||
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { diagnosticsSystemInfo, managerChecks } = store.get();
|
||||
const renderedComponents = getComponentCards(
|
||||
{
|
||||
netshift_version: normalizeCompiledVersion(
|
||||
diagnosticsSystemInfo.netshift_version,
|
||||
),
|
||||
netshift_latest_version: diagnosticsSystemInfo.netshift_latest_version,
|
||||
sing_box_version: diagnosticsSystemInfo.sing_box_version,
|
||||
sing_box_extended: diagnosticsSystemInfo.sing_box_extended,
|
||||
},
|
||||
managerChecks,
|
||||
).map(renderComponentCard);
|
||||
|
||||
return preserveScrollForPage(() => {
|
||||
container.replaceChildren(...renderedComponents);
|
||||
});
|
||||
}
|
||||
|
||||
function onStoreUpdate(
|
||||
_next: StoreType,
|
||||
_prev: StoreType,
|
||||
diff: Partial<StoreType>,
|
||||
) {
|
||||
if (diff.diagnosticsSystemInfo || diff.managerActions || diff.managerChecks) {
|
||||
renderManagerComponents();
|
||||
}
|
||||
}
|
||||
|
||||
function onPageMount() {
|
||||
onPageUnmount();
|
||||
|
||||
managerMounted = true;
|
||||
store.subscribe(onStoreUpdate);
|
||||
renderManagerComponents();
|
||||
void fetchSystemInfo();
|
||||
}
|
||||
|
||||
function onPageUnmount() {
|
||||
managerMounted = false;
|
||||
store.unsubscribe(onStoreUpdate);
|
||||
store.reset(['managerActions', 'managerChecks']);
|
||||
}
|
||||
|
||||
function registerLifecycleListeners() {
|
||||
if (managerLifecycleRegistered) {
|
||||
return;
|
||||
}
|
||||
|
||||
managerLifecycleRegistered = true;
|
||||
|
||||
store.subscribe((next, prev, diff) => {
|
||||
if (
|
||||
diff.tabService &&
|
||||
next.tabService.current !== prev.tabService.current
|
||||
) {
|
||||
const isManagerVisible = next.tabService.current === 'manager';
|
||||
|
||||
if (isManagerVisible) {
|
||||
return onPageMount();
|
||||
}
|
||||
|
||||
if (managerMounted) {
|
||||
return onPageUnmount();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function initController(): Promise<void> {
|
||||
if (managerControllerInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
managerControllerInitialized = true;
|
||||
|
||||
onMount('manager-status').then(() => {
|
||||
logger.debug('[MANAGER]', 'initController', 'onMount');
|
||||
registerLifecycleListeners();
|
||||
|
||||
if (store.get().tabService.current === 'manager') {
|
||||
onPageMount();
|
||||
}
|
||||
});
|
||||
}
|
||||
20
fe-app-netshift/src/netshift/tabs/manager/manager.store.ts
Normal file
20
fe-app-netshift/src/netshift/tabs/manager/manager.store.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { StoreType } from '../../services';
|
||||
|
||||
export const initialManagerStore: Pick<
|
||||
StoreType,
|
||||
'managerActions' | 'managerChecks'
|
||||
> = {
|
||||
managerActions: {
|
||||
netshiftCheck: { loading: false },
|
||||
netshiftUpdate: { loading: false },
|
||||
singBoxStockCheck: { loading: false },
|
||||
singBoxStockAction: { loading: false },
|
||||
singBoxExtendedCheck: { loading: false },
|
||||
singBoxExtendedAction: { loading: false },
|
||||
},
|
||||
managerChecks: {
|
||||
netshift: { status: null, latest_version: '' },
|
||||
sing_box_stock: { status: null, latest_version: '' },
|
||||
sing_box_extended: { status: null, latest_version: '' },
|
||||
},
|
||||
};
|
||||
8
fe-app-netshift/src/netshift/tabs/manager/render.ts
Normal file
8
fe-app-netshift/src/netshift/tabs/manager/render.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export function render() {
|
||||
return E('div', { id: 'manager-status', class: 'pdk_manager-page' }, [
|
||||
E('div', {
|
||||
id: 'pdk_manager-components',
|
||||
class: 'pdk_manager-page__components',
|
||||
}),
|
||||
]);
|
||||
}
|
||||
105
fe-app-netshift/src/netshift/tabs/manager/styles.ts
Normal file
105
fe-app-netshift/src/netshift/tabs/manager/styles.ts
Normal file
@ -0,0 +1,105 @@
|
||||
// language=CSS
|
||||
export const styles = `
|
||||
#cbi-netshift-manager-_mount_node > div {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#cbi-netshift-manager > h3 {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pdk_manager-page {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.pdk_manager-page__components {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(240px, 1fr));
|
||||
grid-gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.pdk_manager-page__components {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.pdk_manager-page__component {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
grid-row-gap: 10px;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__header {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, auto);
|
||||
align-items: start;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__title {
|
||||
color: var(--text-color-high);
|
||||
line-height: 1.25;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
max-width: 180px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__version {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-column-gap: 6px;
|
||||
align-items: baseline;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__version__label {
|
||||
color: var(--text-color-medium);
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__version__value {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__tag {
|
||||
flex: 0 0 auto;
|
||||
padding: 2px 5px;
|
||||
border: 1px var(--background-color-high, gray) solid;
|
||||
border-radius: 4px;
|
||||
color: var(--text-color-medium, gray);
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__tag--success {
|
||||
border-color: var(--success-color-medium, green);
|
||||
color: var(--success-color-medium, green);
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__tag--warning {
|
||||
border-color: var(--warn-color-medium, orange);
|
||||
color: var(--warn-color-medium, orange);
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.pdk_manager-page__component__actions > .pdk-partial-button {
|
||||
margin-left: 0;
|
||||
}
|
||||
`;
|
||||
215
fe-app-netshift/src/netshift/tabs/manager/tests/cards.test.js
Normal file
215
fe-app-netshift/src/netshift/tabs/manager/tests/cards.test.js
Normal file
@ -0,0 +1,215 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { getCheckTag, getComponentCards, isSingBoxInstalled } from '../cards';
|
||||
|
||||
const emptyChecks = {
|
||||
netshift: { status: null, latest_version: '' },
|
||||
sing_box_stock: { status: null, latest_version: '' },
|
||||
sing_box_extended: { status: null, latest_version: '' },
|
||||
};
|
||||
|
||||
function makeSystemInfo(patch = {}) {
|
||||
return {
|
||||
netshift_version: '1.0.0',
|
||||
netshift_latest_version: '1.0.0',
|
||||
sing_box_version: '1.12.0',
|
||||
sing_box_extended: 0,
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('getCheckTag', () => {
|
||||
it.each([
|
||||
['latest', { label: 'Latest', kind: 'success' }],
|
||||
['outdated', { label: 'Outdated', kind: 'warning' }],
|
||||
['dev', { label: 'Dev', kind: 'neutral' }],
|
||||
['not_installed', { label: 'Not installed', kind: 'neutral' }],
|
||||
])('maps status %s to the right badge', (status, expected) => {
|
||||
expect(getCheckTag(status)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('returns undefined for a null status', () => {
|
||||
expect(getCheckTag(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSingBoxInstalled', () => {
|
||||
it.each([
|
||||
['1.12.0', true],
|
||||
['not installed', false],
|
||||
['', false],
|
||||
])('treats %s as installed=%s', (version, expected) => {
|
||||
expect(
|
||||
isSingBoxInstalled(makeSystemInfo({ sing_box_version: version })),
|
||||
).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getComponentCards', () => {
|
||||
it('always builds exactly three cards in order', () => {
|
||||
const cards = getComponentCards(makeSystemInfo(), emptyChecks);
|
||||
|
||||
expect(cards.map((c) => c.key)).toEqual([
|
||||
'netshift',
|
||||
'sing_box_stock',
|
||||
'sing_box_extended',
|
||||
]);
|
||||
});
|
||||
|
||||
it('shows the stock card as installed/active when sing_box_extended=0', () => {
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({ sing_box_extended: 0, sing_box_version: '1.12.0' }),
|
||||
emptyChecks,
|
||||
);
|
||||
const [, stock, extended] = cards;
|
||||
|
||||
expect(stock.installed).toBe(true);
|
||||
expect(stock.version).toBe('1.12.0');
|
||||
// No check yet → no badge for the active card.
|
||||
expect(stock.tag).toBeUndefined();
|
||||
expect(stock.actions[0].kind).toBe('check');
|
||||
expect(stock.actions[0].backendAction).toBe('check_update_stable');
|
||||
|
||||
// Inactive extended card → "Not installed" + switch-to-extended.
|
||||
expect(extended.installed).toBe(false);
|
||||
expect(extended.version).toBe('Not installed');
|
||||
expect(extended.actions[0].kind).toBe('switch');
|
||||
expect(extended.actions[0].backendAction).toBe('install_extended');
|
||||
});
|
||||
|
||||
it('mirrors the layout when sing_box_extended=1', () => {
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({ sing_box_extended: 1, sing_box_version: '1.12.5' }),
|
||||
emptyChecks,
|
||||
);
|
||||
const [, stock, extended] = cards;
|
||||
|
||||
expect(extended.installed).toBe(true);
|
||||
expect(extended.actions[0].backendAction).toBe('check_update');
|
||||
|
||||
expect(stock.installed).toBe(false);
|
||||
expect(stock.actions[0].kind).toBe('switch');
|
||||
expect(stock.actions[0].backendAction).toBe('install_stable');
|
||||
});
|
||||
|
||||
it('offers switch-to on both cores when sing-box is absent', () => {
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({ sing_box_version: 'not installed' }),
|
||||
emptyChecks,
|
||||
);
|
||||
const [, stock, extended] = cards;
|
||||
|
||||
expect(stock.installed).toBe(false);
|
||||
expect(stock.actions[0].kind).toBe('switch');
|
||||
expect(extended.installed).toBe(false);
|
||||
expect(extended.actions[0].kind).toBe('switch');
|
||||
});
|
||||
|
||||
it('turns an outdated stock check into an Install %s update action', () => {
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({ sing_box_extended: 0, sing_box_version: '1.12.0' }),
|
||||
{
|
||||
...emptyChecks,
|
||||
sing_box_stock: { status: 'outdated', latest_version: '1.12.9' },
|
||||
},
|
||||
);
|
||||
const stock = cards[1];
|
||||
|
||||
expect(stock.tag).toEqual({ label: 'Outdated', kind: 'warning' });
|
||||
expect(stock.actions[0].kind).toBe('update');
|
||||
expect(stock.actions[0].backendAction).toBe('install_stable');
|
||||
expect(stock.actions[0].text).toBe('Install 1.12.9');
|
||||
});
|
||||
|
||||
it('is neutral until checked — null managerChecks.netshift status', () => {
|
||||
// task-030: mount does NO network check; managerChecks.netshift.status is
|
||||
// null → no badge, the "Check update" action (no outdated/update button).
|
||||
const cards = getComponentCards(makeSystemInfo(), emptyChecks);
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.tag).toBeUndefined();
|
||||
expect(netshift.actions[0].kind).toBe('check_netshift');
|
||||
expect(netshift.actions[0].backendAction).toBe('check_update');
|
||||
});
|
||||
|
||||
it('derives an outdated NetShift card from the on-demand check result', () => {
|
||||
// task-030: status comes from managerChecks.netshift (the check result), NOT
|
||||
// from a systemInfo installed-vs-latest string compare. The latest_version
|
||||
// for the "Install %s" text also comes from the check result.
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({
|
||||
netshift_version: '1.0.0',
|
||||
netshift_latest_version: '1.0.0',
|
||||
}),
|
||||
{
|
||||
...emptyChecks,
|
||||
netshift: { status: 'outdated', latest_version: '1.1.0' },
|
||||
},
|
||||
);
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.tag).toEqual({ label: 'Outdated', kind: 'warning' });
|
||||
expect(netshift.actions[0].kind).toBe('self_update');
|
||||
expect(netshift.actions[0].backendAction).toBe('self_update');
|
||||
expect(netshift.actions[0].text).toBe('Install 1.1.0');
|
||||
});
|
||||
|
||||
it('shows the Latest badge + Check update when the check says latest', () => {
|
||||
const cards = getComponentCards(makeSystemInfo(), {
|
||||
...emptyChecks,
|
||||
netshift: { status: 'latest', latest_version: '1.0.0' },
|
||||
});
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.tag).toEqual({ label: 'Latest', kind: 'success' });
|
||||
// The NetShift check is a DISTINCT kind so it can never be routed to the
|
||||
// sing-box check method.
|
||||
expect(netshift.actions[0].kind).toBe('check_netshift');
|
||||
});
|
||||
|
||||
it('NetShift check action carries its own (non-sing-box) backendAction', () => {
|
||||
// The NetShift "Check update" routes to runNetshiftCheck (distinct kind) and
|
||||
// calls `component_action netshift check_update` — NOT a sing-box check
|
||||
// action. Guard against accidentally reusing a sing-box check action.
|
||||
const cards = getComponentCards(makeSystemInfo(), emptyChecks);
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.actions[0].kind).toBe('check_netshift');
|
||||
expect(netshift.actions[0].backendAction).toBe('check_update');
|
||||
expect(['check_update_stable']).not.toContain(
|
||||
netshift.actions[0].backendAction,
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps a dev build neutral even if a check result says outdated', () => {
|
||||
// The dev-build guard: a placeholder/dev install never shows an update
|
||||
// prompt regardless of any check result.
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({ netshift_version: 'COMPILED_VERSION' }),
|
||||
{
|
||||
...emptyChecks,
|
||||
netshift: { status: 'outdated', latest_version: '9.9.9' },
|
||||
},
|
||||
);
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.version).toBe('dev');
|
||||
expect(netshift.tag).toBeUndefined();
|
||||
expect(netshift.actions[0].kind).toBe('check_netshift');
|
||||
});
|
||||
|
||||
it('ignores systemInfo netshift_latest_version for status (now on-demand)', () => {
|
||||
// task-030: a stale/unknown systemInfo latest must NOT drive the badge — only
|
||||
// the on-demand managerChecks.netshift result does.
|
||||
const cards = getComponentCards(
|
||||
makeSystemInfo({
|
||||
netshift_version: '1.0.0',
|
||||
netshift_latest_version: '9.9.9',
|
||||
}),
|
||||
emptyChecks,
|
||||
);
|
||||
const netshift = cards[0];
|
||||
|
||||
expect(netshift.tag).toBeUndefined();
|
||||
expect(netshift.actions[0].kind).toBe('check_netshift');
|
||||
});
|
||||
});
|
||||
@ -117,9 +117,11 @@ export namespace NetShift {
|
||||
export interface ConfigProxySubscriptionSection {
|
||||
connection_type: 'proxy';
|
||||
proxy_config_type: 'subscription';
|
||||
subscription_url: string;
|
||||
subscription_url: string[];
|
||||
subscription_format_preference?: 'auto' | 'xray' | 'singbox';
|
||||
subscription_update_interval?: string;
|
||||
subscription_group_by_countries?: '0' | '1';
|
||||
subscription_group_mode?: 'off' | 'country' | 'prefix';
|
||||
subscription_group_prefix_len?: string;
|
||||
subscription_filter_include_keywords?: string[];
|
||||
subscription_filter_exclude_keywords?: string[];
|
||||
}
|
||||
@ -175,6 +177,7 @@ export namespace NetShift {
|
||||
bootstrap_dns_server: string;
|
||||
bootstrap_dns_status: 0 | 1;
|
||||
dhcp_config_status: 0 | 1;
|
||||
dns_via_outbound_tag?: string;
|
||||
}
|
||||
|
||||
export interface NftRulesCheckResult {
|
||||
@ -182,7 +185,6 @@ export namespace NetShift {
|
||||
rules_mangle_exist: 0 | 1;
|
||||
rules_mangle_counters: 0 | 1;
|
||||
rules_mangle_output_exist: 0 | 1;
|
||||
rules_mangle_output_counters: 0 | 1;
|
||||
rules_proxy_exist: 0 | 1;
|
||||
rules_proxy_counters: 0 | 1;
|
||||
rules_other_mark_exist: 0 | 1;
|
||||
@ -229,4 +231,23 @@ export namespace NetShift {
|
||||
}
|
||||
|
||||
export type GetClashApiGroupLatency = Record<string, number>;
|
||||
|
||||
// Component Manager (task-018) — consumes the STABLE backend contract from
|
||||
// task-017. Status union returned by the sync update-check actions.
|
||||
export type ComponentUpdateStatus =
|
||||
| 'latest'
|
||||
| 'outdated'
|
||||
| 'dev'
|
||||
| 'not_installed';
|
||||
|
||||
// Shape echoed by the sync update-check actions:
|
||||
// component_action sing_box check_update (extended)
|
||||
// component_action sing_box check_update_stable (stock)
|
||||
export interface ComponentCheckUpdateResult {
|
||||
success: boolean;
|
||||
current_version?: string;
|
||||
latest_version?: string;
|
||||
status?: ComponentUpdateStatus;
|
||||
message?: string;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,10 +1,43 @@
|
||||
// language=CSS
|
||||
import { DashboardTab, DiagnosticTab } from './netshift';
|
||||
import { DashboardTab, DiagnosticTab, ManagerTab } from './netshift';
|
||||
import { PartialStyles } from './partials';
|
||||
|
||||
export const GlobalStyles = `
|
||||
/*
|
||||
* NetShift design tokens (Stage 1 foundation — task-024).
|
||||
* Each token layers over the LuCI theme var (with a hardcoded fallback) so
|
||||
* themes still win. Reused by the custom tabs and the form redesigns
|
||||
* (task-025/026). Keep these names stable.
|
||||
*/
|
||||
:root,
|
||||
.cbi-map {
|
||||
--ns-card-border: var(--background-color-low, lightgray);
|
||||
--ns-card-border-width: 2px;
|
||||
--ns-card-radius: 4px;
|
||||
--ns-gap: 10px;
|
||||
--ns-card-padding: var(--ns-gap);
|
||||
--ns-success: var(--success-color-medium, #28a745);
|
||||
--ns-warning: var(--warn-color-medium, #f0ad4e);
|
||||
--ns-error: var(--error-color-medium, #dc3545);
|
||||
--ns-info: var(--primary-color-high, #2196f3);
|
||||
}
|
||||
|
||||
/*
|
||||
* Shared card primitive. Mirrors the Manager component card look
|
||||
* (2px solid border, 4px radius, 10px padding, overflow-safe min-width:0).
|
||||
* Defined BEFORE the per-tab styles so colored-border modifiers
|
||||
* (e.g. .pdk_diagnostic_alert--warning) still win via source order.
|
||||
*/
|
||||
.card {
|
||||
border: var(--ns-card-border-width) solid var(--ns-card-border);
|
||||
border-radius: var(--ns-card-radius);
|
||||
padding: var(--ns-card-padding);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
${DashboardTab.styles}
|
||||
${DiagnosticTab.styles}
|
||||
${ManagerTab.styles}
|
||||
${PartialStyles}
|
||||
|
||||
|
||||
@ -23,6 +56,42 @@ ${PartialStyles}
|
||||
margin-bottom: -32px;
|
||||
}
|
||||
|
||||
/*
|
||||
* Sections (connection) form — native CBI option-group tabs styled as a
|
||||
* card (task-025). Reuses task-024's --ns-* tokens. The tab strip
|
||||
* (ul.cbi-tabmenu) sits on top; each tab pane (.cbi-section-node-tabbed)
|
||||
* reads as the card body. depends()-driven auto-hide of tabs is unaffected.
|
||||
*/
|
||||
#cbi-netshift-section .cbi-section-node-tabbed {
|
||||
border: var(--ns-card-border-width) solid var(--ns-card-border);
|
||||
border-radius: var(--ns-card-radius);
|
||||
padding: var(--ns-card-padding);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
#cbi-netshift-section ul.cbi-tabmenu {
|
||||
margin-bottom: var(--ns-gap);
|
||||
}
|
||||
|
||||
/*
|
||||
* Settings form — native CBI option-group tabs styled as a card (task-026).
|
||||
* Reuses task-024's --ns-* tokens and mirrors the #cbi-netshift-section
|
||||
* pattern above. The tab strip (ul.cbi-tabmenu) sits on top; each tab pane
|
||||
* (.cbi-section-node-tabbed) reads as the card body. depends()-driven
|
||||
* auto-hide of tabs is unaffected. The existing
|
||||
* #cbi-netshift-settings > h3 hide rule above stays valid.
|
||||
*/
|
||||
#cbi-netshift-settings .cbi-section-node-tabbed {
|
||||
border: var(--ns-card-border-width) solid var(--ns-card-border);
|
||||
border-radius: var(--ns-card-radius);
|
||||
padding: var(--ns-card-padding);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
#cbi-netshift-settings ul.cbi-tabmenu {
|
||||
margin-bottom: var(--ns-gap);
|
||||
}
|
||||
|
||||
/* Centered class helper */
|
||||
.centered {
|
||||
display: flex;
|
||||
@ -98,11 +167,19 @@ ${PartialStyles}
|
||||
}
|
||||
|
||||
.toast-success {
|
||||
background-color: #28a745;
|
||||
background-color: var(--ns-success, #28a745);
|
||||
}
|
||||
|
||||
.toast-error {
|
||||
background-color: #dc3545;
|
||||
background-color: var(--ns-error, #dc3545);
|
||||
}
|
||||
|
||||
.toast-warning {
|
||||
background-color: var(--ns-warning, #f0ad4e);
|
||||
}
|
||||
|
||||
.toast-info {
|
||||
background-color: var(--ns-info, #2196f3);
|
||||
}
|
||||
|
||||
.toast.visible {
|
||||
|
||||
@ -10,4 +10,5 @@ export * from './validateVlessUrl';
|
||||
export * from './validateOutboundJson';
|
||||
export * from './validateTrojanUrl';
|
||||
export * from './validateProxyUrl';
|
||||
export * from './validateProxyUrlList';
|
||||
export * from './validateSocksUrl';
|
||||
|
||||
@ -12,11 +12,23 @@ export const additionalValidDns = [
|
||||
['DoH IP with port 443', '1.1.1.1:443/dns-query'],
|
||||
['DoH domain', 'cloudflare-dns.com/dns-query'],
|
||||
['DoH domain with port 443', 'cloudflare-dns.com:443/dns-query'],
|
||||
['IPv6 address', '2001:db8::1'],
|
||||
['Bracketed IPv6', '[2001:db8::1]'],
|
||||
['Bracketed IPv6 with port', '[2001:db8::1]:853'],
|
||||
['IPv6 DoH path', '2001:db8::1/dns-query'],
|
||||
['Bracketed IPv6 DoH path with port', '[2001:db8::1]:443/dns-query'],
|
||||
];
|
||||
|
||||
export const additionalInvalidDns = [
|
||||
['IPv6 invalid hex', '2001:db8::zzzz'],
|
||||
['IPv6 group too long', '12345::1'],
|
||||
['IPv6 triple colon only', ':::'],
|
||||
['IPv6 multiple compressions', '1::2::3'],
|
||||
];
|
||||
|
||||
const validDns = [...validIPs, ...validDomains, ...additionalValidDns];
|
||||
|
||||
const invalidDns = [...invalidIPs, ...invalidDomains];
|
||||
const invalidDns = [...invalidIPs, ...invalidDomains, ...additionalInvalidDns];
|
||||
|
||||
describe('validateDns', () => {
|
||||
describe.each(validDns)('Valid dns: %s', (_desc, domain) => {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { validateIPV4 } from '../validateIp';
|
||||
import { validateIP, validateIPV4, validateIPV6 } from '../validateIp';
|
||||
|
||||
export const validIPs = [
|
||||
['Private LAN', '192.168.1.1'],
|
||||
@ -21,6 +21,29 @@ export const invalidIPs = [
|
||||
['Trailing dot', '1.2.3.'],
|
||||
];
|
||||
|
||||
export const validIPv6 = [
|
||||
['Loopback', '::1'],
|
||||
['Compressed', '2001:db8::1'],
|
||||
['Full form', '2001:0db8:85a3:0000:0000:8a2e:0370:7334'],
|
||||
['Bracketed', '[2001:db8::1]'],
|
||||
['Unspecified', '::'],
|
||||
['Compressed middle', '2001:db8:0:0:1::1'],
|
||||
['IPv4-mapped', '::ffff:192.168.1.1'],
|
||||
['IPv4-embedded', '2001:db8::192.168.1.1'],
|
||||
];
|
||||
|
||||
export const invalidIPv6 = [
|
||||
['Invalid hex', '2001:db8::zzzz'],
|
||||
['Group too long', '12345::1'],
|
||||
['Too many groups', '2001:db8:85a3:0:0:8a2e:370:7334:1234'],
|
||||
['Triple colon only', ':::'],
|
||||
['Colon run inside', '1:2:::3'],
|
||||
['Multiple compressions', '1::2::3'],
|
||||
['Incomplete (7 groups, no ::)', '1:2:3:4:5:6:7'],
|
||||
['Bad hex group', 'gggg::1'],
|
||||
['Too many groups (9)', '1:2:3:4:5:6:7:8:9'],
|
||||
];
|
||||
|
||||
describe('validateIPV4', () => {
|
||||
describe.each(validIPs)('Valid IP: %s', (_desc, ip) => {
|
||||
it(`returns {valid:true} for "${ip}"`, () => {
|
||||
@ -36,3 +59,41 @@ describe('validateIPV4', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateIPV6', () => {
|
||||
describe.each(validIPv6)('Valid IPv6: %s', (_desc, ip) => {
|
||||
it(`returns {valid:true} for "${ip}"`, () => {
|
||||
const res = validateIPV6(ip);
|
||||
expect(res.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([...invalidIPv6, ['IPv4 address', '192.168.1.1']])(
|
||||
'Invalid IPv6: %s',
|
||||
(_desc, ip) => {
|
||||
it(`returns {valid:false} for "${ip}"`, () => {
|
||||
const res = validateIPV6(ip);
|
||||
expect(res.valid).toBe(false);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('validateIP', () => {
|
||||
describe.each([...validIPs, ...validIPv6])('Valid IP: %s', (_desc, ip) => {
|
||||
it(`returns {valid:true} for "${ip}"`, () => {
|
||||
const res = validateIP(ip);
|
||||
expect(res.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe.each([...invalidIPs, ...invalidIPv6])(
|
||||
'Invalid IP: %s',
|
||||
(_desc, ip) => {
|
||||
it(`returns {valid:false} for "${ip}"`, () => {
|
||||
const res = validateIP(ip);
|
||||
expect(res.valid).toBe(false);
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@ -0,0 +1,55 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { validateProxyUrlList } from '../validateProxyUrlList';
|
||||
|
||||
// Synthetic placeholder links only — never real proxy/subscription data.
|
||||
const VLESS =
|
||||
'vless://94792286-7bbe-4f33-8b36-18d1bbf70723@127.0.0.1:34520?type=tcp&encryption=none&security=none#node-a';
|
||||
const SS =
|
||||
'ss://2022-blake3-aes-256-gcm:dmCly/Zh15Ww9+s+GFXiFTIkpw7c/qCISaBrai7WhhY=@127.0.0.1:27214?type=tcp#node-b';
|
||||
|
||||
const validBlobs = [
|
||||
['single vless line', VLESS],
|
||||
['single ss line', SS],
|
||||
['two links', `${VLESS}\n${SS}`],
|
||||
['blank lines ignored', `\n${VLESS}\n\n${SS}\n`],
|
||||
['leading/trailing whitespace trimmed', ` ${VLESS} \n\t${SS}\t`],
|
||||
['CRLF tolerated', `${VLESS}\r\n${SS}\r`],
|
||||
];
|
||||
|
||||
const invalidBlobs = [
|
||||
['empty string', ''],
|
||||
['whitespace/blank only', ' \n\t\n '],
|
||||
['unsupported scheme', 'tuic://127.0.0.1:443#node'],
|
||||
['second line invalid', `${VLESS}\ntuic://127.0.0.1:443`],
|
||||
['garbage line', 'not-a-link'],
|
||||
];
|
||||
|
||||
describe('validateProxyUrlList', () => {
|
||||
describe.each(validBlobs)('Valid blob: %s', (_desc, blob) => {
|
||||
it('returns valid=true', () => {
|
||||
const res = validateProxyUrlList(blob);
|
||||
expect(res.valid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe.each(invalidBlobs)('Invalid blob: %s', (_desc, blob) => {
|
||||
it('returns valid=false', () => {
|
||||
const res = validateProxyUrlList(blob);
|
||||
expect(res.valid).toBe(false);
|
||||
expect(typeof res.message).toBe('string');
|
||||
expect(res.message.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('reports the 1-based line number of the first failing line', () => {
|
||||
const res = validateProxyUrlList(`${VLESS}\n${SS}\ntuic://127.0.0.1:443`);
|
||||
expect(res.valid).toBe(false);
|
||||
expect(res.message).toContain('Line 3');
|
||||
});
|
||||
|
||||
it('counts blank lines toward the reported line number', () => {
|
||||
const res = validateProxyUrlList(`${VLESS}\n\ntuic://127.0.0.1:443`);
|
||||
expect(res.valid).toBe(false);
|
||||
expect(res.message).toContain('Line 3');
|
||||
});
|
||||
});
|
||||
@ -8,6 +8,10 @@ export const validSubnets = [
|
||||
['CIDR /32', '172.16.0.1/32'],
|
||||
['Loopback', '127.0.0.1'],
|
||||
['Broadcast with mask', '255.255.255.255/32'],
|
||||
['IPv6 loopback', '::1'],
|
||||
['IPv6 with CIDR /0', '::/0'],
|
||||
['IPv6 with CIDR /32', '2001:db8::/32'],
|
||||
['IPv6 with CIDR /128', '2001:db8::1/128'],
|
||||
];
|
||||
|
||||
export const invalidSubnets = [
|
||||
@ -22,6 +26,12 @@ export const invalidSubnets = [
|
||||
['Invalid CIDR (negative)', '192.168.1.1/-1'],
|
||||
['CIDR not number', '192.168.1.1/abc'],
|
||||
['Forbidden 0.0.0.0', '0.0.0.0'],
|
||||
['IPv6 invalid hex', '2001:db8::zzzz'],
|
||||
['IPv6 CIDR too high', '2001:db8::1/129'],
|
||||
['IPv6 CIDR negative', '2001:db8::1/-1'],
|
||||
['IPv6 CIDR not number', '2001:db8::1/abc'],
|
||||
['IPv6 triple colon with CIDR', ':::/64'],
|
||||
['IPv6 multiple compressions with CIDR', '1::2::3/64'],
|
||||
];
|
||||
|
||||
describe('validateSubnet', () => {
|
||||
|
||||
@ -8,6 +8,9 @@ const validUrls = [
|
||||
['With query', 'https://example.com/?q=test'],
|
||||
['With port', 'http://example.com:8080'],
|
||||
['With subdomain', 'https://sub.example.com'],
|
||||
['IPv4 host with port and path', 'https://91.199.111.52:2096/sub/abc'],
|
||||
['IPv4 host with path', 'http://10.0.0.1/x'],
|
||||
['Bracketed IPv6 host with port and path', 'https://[2001:db8::1]:2096/sub'],
|
||||
];
|
||||
|
||||
const invalidUrls = [
|
||||
@ -17,6 +20,9 @@ const invalidUrls = [
|
||||
['Unsupported protocol (ws)', 'ws://example.com'],
|
||||
['Empty string', ''],
|
||||
['Without tld', 'https://google'],
|
||||
['Bad IPv4 host', 'https://999.1.1.1/x'],
|
||||
['Bad protocol with IP host', 'ftp://1.2.3.4'],
|
||||
['No host', 'https://'],
|
||||
];
|
||||
|
||||
describe('validateUrl', () => {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { validateDomain } from './validateDomain';
|
||||
import { validateIPV4 } from './validateIp';
|
||||
import { validateIPV4, validateIPV6 } from './validateIp';
|
||||
import { ValidationResult } from './types';
|
||||
|
||||
export function validateDNS(value: string): ValidationResult {
|
||||
@ -7,13 +7,29 @@ export function validateDNS(value: string): ValidationResult {
|
||||
return { valid: false, message: _('DNS server address cannot be empty') };
|
||||
}
|
||||
|
||||
const cleanedValueWithoutPort = value.replace(/:(\d+)(?=\/|$)/, '');
|
||||
const cleanedIpWithoutPath = cleanedValueWithoutPort.split('/')[0];
|
||||
const valueBeforePath = value.split('/')[0];
|
||||
let cleanedValueWithoutPort = value;
|
||||
let cleanedIpWithoutPath = valueBeforePath;
|
||||
|
||||
if (valueBeforePath.startsWith('[')) {
|
||||
const closingBracketIndex = valueBeforePath.indexOf(']');
|
||||
|
||||
if (closingBracketIndex > 0) {
|
||||
cleanedIpWithoutPath = valueBeforePath.slice(1, closingBracketIndex);
|
||||
}
|
||||
} else if ((valueBeforePath.match(/:/g) || []).length < 2) {
|
||||
cleanedValueWithoutPort = value.replace(/:(\d+)(?=\/|$)/, '');
|
||||
cleanedIpWithoutPath = cleanedValueWithoutPort.split('/')[0];
|
||||
}
|
||||
|
||||
if (validateIPV4(cleanedIpWithoutPath).valid) {
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
if (validateIPV6(cleanedIpWithoutPath).valid) {
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
if (validateDomain(cleanedValueWithoutPort).valid) {
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
@ -21,7 +37,7 @@ export function validateDNS(value: string): ValidationResult {
|
||||
return {
|
||||
valid: false,
|
||||
message: _(
|
||||
'Invalid DNS server format. Examples: 8.8.8.8 or dns.example.com or dns.example.com/nicedns for DoH',
|
||||
'Invalid DNS server format. Examples: 8.8.8.8, [::1], dns.example.com, or dns.example.com/dns-query for DoH',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@ -10,3 +10,102 @@ export function validateIPV4(ip: string): ValidationResult {
|
||||
|
||||
return { valid: false, message: _('Invalid IP address') };
|
||||
}
|
||||
|
||||
const HEXTET_REGEX = /^[0-9a-fA-F]{1,4}$/;
|
||||
|
||||
function isHextet(group: string): boolean {
|
||||
return HEXTET_REGEX.test(group);
|
||||
}
|
||||
|
||||
function isEmbeddedIPv4(group: string): boolean {
|
||||
return validateIPV4(group).valid;
|
||||
}
|
||||
|
||||
// Validates one side (the part before or after "::") as a list of hextets.
|
||||
// The trailing group may be a dotted IPv4 (embedded/IPv4-mapped IPv6), which
|
||||
// counts as TWO 16-bit groups. Returns the 16-bit group count, or null on any
|
||||
// invalid group.
|
||||
function countGroups(side: string, allowEmbeddedIPv4: boolean): number | null {
|
||||
if (side === '') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const groups = side.split(':');
|
||||
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const group = groups[i];
|
||||
const isLast = i === groups.length - 1;
|
||||
|
||||
if (allowEmbeddedIPv4 && isLast && group.includes('.')) {
|
||||
if (!isEmbeddedIPv4(group)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isHextet(group)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// An embedded IPv4 tail occupies two 16-bit groups instead of one.
|
||||
const lastGroup = groups[groups.length - 1];
|
||||
const embeddedExtra =
|
||||
allowEmbeddedIPv4 && lastGroup.includes('.') && isEmbeddedIPv4(lastGroup)
|
||||
? 1
|
||||
: 0;
|
||||
|
||||
return groups.length + embeddedExtra;
|
||||
}
|
||||
|
||||
export function validateIPV6(ip: string): ValidationResult {
|
||||
const stripped = ip.replace(/^\[/, '').replace(/\]$/, '');
|
||||
const invalid: ValidationResult = {
|
||||
valid: false,
|
||||
message: _('Invalid IPv6 address'),
|
||||
};
|
||||
|
||||
// At most one "::" compression is allowed.
|
||||
const doubleColonCount = stripped.split('::').length - 1;
|
||||
if (doubleColonCount > 1) {
|
||||
return invalid;
|
||||
}
|
||||
|
||||
if (doubleColonCount === 1) {
|
||||
const [head, tail] = stripped.split('::');
|
||||
|
||||
const headGroups = countGroups(head, true);
|
||||
const tailGroups = countGroups(tail, true);
|
||||
|
||||
if (headGroups === null || tailGroups === null) {
|
||||
return invalid;
|
||||
}
|
||||
|
||||
// "::" must replace at least one group, so the explicit groups can total
|
||||
// at most 7 (it stands in for one or more zero groups).
|
||||
if (headGroups + tailGroups > 7) {
|
||||
return invalid;
|
||||
}
|
||||
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
// No "::" → must be exactly 8 groups, all explicit.
|
||||
const totalGroups = countGroups(stripped, true);
|
||||
if (totalGroups === 8) {
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
return invalid;
|
||||
}
|
||||
|
||||
export function validateIP(ip: string): ValidationResult {
|
||||
const ipv4 = validateIPV4(ip);
|
||||
|
||||
if (ipv4.valid) {
|
||||
return ipv4;
|
||||
}
|
||||
|
||||
return validateIPV6(ip);
|
||||
}
|
||||
|
||||
44
fe-app-netshift/src/validators/validateProxyUrlList.ts
Normal file
44
fe-app-netshift/src/validators/validateProxyUrlList.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { ValidationResult } from './types';
|
||||
import { validateProxyUrl } from './validateProxyUrl';
|
||||
|
||||
/**
|
||||
* Validate a textarea blob of proxy links (one per line).
|
||||
*
|
||||
* Splits on newlines, trims each line, ignores blank lines, then runs the
|
||||
* single-link `validateProxyUrl` on every remaining line. Returns the first
|
||||
* error encountered (annotated with the 1-based line number) or
|
||||
* `{ valid: true }` when every non-blank line is a valid proxy link.
|
||||
*/
|
||||
export function validateProxyUrlList(value: string): ValidationResult {
|
||||
const lines = value.split('\n');
|
||||
|
||||
let hasLink = false;
|
||||
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index].trim();
|
||||
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
hasLink = true;
|
||||
|
||||
const validation = validateProxyUrl(line);
|
||||
|
||||
if (!validation.valid) {
|
||||
return {
|
||||
valid: false,
|
||||
message: `${_('Line')} ${index + 1}: ${validation.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasLink) {
|
||||
return {
|
||||
valid: false,
|
||||
message: _('At least one proxy link must be specified.'),
|
||||
};
|
||||
}
|
||||
|
||||
return { valid: true, message: '' };
|
||||
}
|
||||
@ -1,39 +1,59 @@
|
||||
import { ValidationResult } from './types';
|
||||
import { validateIPV4 } from './validateIp';
|
||||
import { validateIPV4, validateIPV6 } from './validateIp';
|
||||
|
||||
export function validateSubnet(value: string): ValidationResult {
|
||||
// Must be in form X.X.X.X or X.X.X.X/Y
|
||||
const subnetRegex = /^(\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?$/;
|
||||
|
||||
if (!subnetRegex.test(value)) {
|
||||
return {
|
||||
valid: false,
|
||||
message: _('Invalid format. Use X.X.X.X or X.X.X.X/Y'),
|
||||
};
|
||||
}
|
||||
if (subnetRegex.test(value)) {
|
||||
const [ip, cidr] = value.split('/');
|
||||
|
||||
const [ip, cidr] = value.split('/');
|
||||
|
||||
if (ip === '0.0.0.0') {
|
||||
return { valid: false, message: _('IP address 0.0.0.0 is not allowed') };
|
||||
}
|
||||
|
||||
const ipCheck = validateIPV4(ip);
|
||||
if (!ipCheck.valid) {
|
||||
return ipCheck;
|
||||
}
|
||||
|
||||
// Validate CIDR if present
|
||||
if (cidr) {
|
||||
const cidrNum = parseInt(cidr, 10);
|
||||
|
||||
if (cidrNum < 0 || cidrNum > 32) {
|
||||
return {
|
||||
valid: false,
|
||||
message: _('CIDR must be between 0 and 32'),
|
||||
};
|
||||
if (ip === '0.0.0.0') {
|
||||
return { valid: false, message: _('IP address 0.0.0.0 is not allowed') };
|
||||
}
|
||||
|
||||
const ipCheck = validateIPV4(ip);
|
||||
if (!ipCheck.valid) {
|
||||
return ipCheck;
|
||||
}
|
||||
|
||||
if (cidr) {
|
||||
const cidrNum = parseInt(cidr, 10);
|
||||
|
||||
if (cidrNum < 0 || cidrNum > 32) {
|
||||
return {
|
||||
valid: false,
|
||||
message: _('CIDR must be between 0 and 32'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
return { valid: true, message: _('Valid') };
|
||||
const ipv6CidrRegex = /^([0-9a-fA-F:]+(?:\/[0-9]{1,3})?)$/;
|
||||
if (ipv6CidrRegex.test(value)) {
|
||||
const [ip, cidr] = value.split('/');
|
||||
const ipCheck = validateIPV6(ip);
|
||||
|
||||
if (!ipCheck.valid) {
|
||||
return ipCheck;
|
||||
}
|
||||
|
||||
if (cidr) {
|
||||
const cidrNum = parseInt(cidr, 10);
|
||||
if (cidrNum < 0 || cidrNum > 128) {
|
||||
return {
|
||||
valid: false,
|
||||
message: _('IPv6 CIDR must be between 0 and 128'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
return {
|
||||
valid: false,
|
||||
message: _('Invalid format. Use X.X.X.X/Y or IPv6/Y'),
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,4 +1,45 @@
|
||||
import { ValidationResult } from './types';
|
||||
import { validateDomain } from './validateDomain';
|
||||
import { validateIPV4, validateIPV6 } from './validateIp';
|
||||
|
||||
// Extracts the bare host from a URL, stripping the scheme, optional userinfo,
|
||||
// the port, and the path/query/fragment. A bracketed IPv6 literal (e.g.
|
||||
// "[2001:db8::1]") is unwrapped to "2001:db8::1".
|
||||
function extractHost(url: string): string {
|
||||
// Strip scheme://
|
||||
const schemeIndex = url.indexOf('://');
|
||||
let rest = schemeIndex === -1 ? url : url.slice(schemeIndex + 3);
|
||||
|
||||
// Strip path/query/fragment (everything from the first '/', '?' or '#').
|
||||
const pathIndex = rest.search(/[/?#]/);
|
||||
if (pathIndex !== -1) {
|
||||
rest = rest.slice(0, pathIndex);
|
||||
}
|
||||
|
||||
// Strip optional userinfo ("user:pass@").
|
||||
const atIndex = rest.lastIndexOf('@');
|
||||
if (atIndex !== -1) {
|
||||
rest = rest.slice(atIndex + 1);
|
||||
}
|
||||
|
||||
// Bracketed IPv6 literal: "[2001:db8::1]:2096" -> "2001:db8::1".
|
||||
if (rest.startsWith('[')) {
|
||||
const closeIndex = rest.indexOf(']');
|
||||
if (closeIndex !== -1) {
|
||||
return rest.slice(1, closeIndex);
|
||||
}
|
||||
// Unterminated bracket: drop the leading '[' and any ':port' suffix.
|
||||
return rest.slice(1).split(':')[0];
|
||||
}
|
||||
|
||||
// Bare host: strip a trailing ":port".
|
||||
const colonIndex = rest.lastIndexOf(':');
|
||||
if (colonIndex !== -1) {
|
||||
rest = rest.slice(0, colonIndex);
|
||||
}
|
||||
|
||||
return rest;
|
||||
}
|
||||
|
||||
export function validateUrl(
|
||||
url: string,
|
||||
@ -19,12 +60,18 @@ export function validateUrl(
|
||||
protocols.join(', '),
|
||||
};
|
||||
|
||||
const regex = new RegExp(
|
||||
`^(?:${protocols.map((p) => p.replace(':', '')).join('|')})://` +
|
||||
`(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,}(?::\\d+)?(?:/[^\\s]*)?$`,
|
||||
);
|
||||
const host = extractHost(url);
|
||||
|
||||
if (regex.test(url)) {
|
||||
if (!host) {
|
||||
return { valid: false, message: _('Invalid URL format') };
|
||||
}
|
||||
|
||||
const isValidHost =
|
||||
validateIPV4(host).valid ||
|
||||
validateIPV6(host).valid ||
|
||||
validateDomain(host).valid;
|
||||
|
||||
if (isValidHost) {
|
||||
return { valid: true, message: _('Valid') };
|
||||
}
|
||||
|
||||
|
||||
123
install.sh
123
install.sh
@ -1,7 +1,13 @@
|
||||
#!/bin/sh
|
||||
# shellcheck shell=dash
|
||||
|
||||
REPO="https://api.github.com/repos/yandexru45/netshift/releases/latest"
|
||||
REPO="https://uralgit.ru/api/v1/repos/ural/netshift/releases/latest"
|
||||
# uralgit.ru FRONTEND redirect path (NOT the rate-limited api.github.com).
|
||||
# /releases/latest 303s to /releases/tag/<tag>; /releases/download/<tag>/<asset>
|
||||
# direct download. Primary install path so CGNAT / shared-IP routers avoid the
|
||||
# 60/hour/IP API limit; REPO stays as the fallback.
|
||||
RELEASES_LATEST_REDIRECT="https://uralgit.ru/ural/netshift/releases/latest"
|
||||
RELEASES_DOWNLOAD_BASE="https://uralgit.ru/ural/netshift/releases/download"
|
||||
DOWNLOAD_DIR="/tmp/netshift"
|
||||
COUNT=3
|
||||
|
||||
@ -57,7 +63,7 @@ pkg_install() {
|
||||
# If you're installing a non-standard (self-built) package, use the --allow-untrusted option:
|
||||
apk add --allow-untrusted "$pkg_file"
|
||||
else
|
||||
opkg install "$pkg_file"
|
||||
opkg install --force-downgrade --force-reinstall "$pkg_file"
|
||||
fi
|
||||
}
|
||||
|
||||
@ -66,7 +72,7 @@ update_config() {
|
||||
printf "\033[48;5;196m\033[1m║ ! Обнаружена старая версия NetShift. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Если продолжите обновление, вам потребуется настроить NetShift заново.║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Старая конфигурация будет сохранена в /etc/config/netshift-070 ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Подробности: https://github.com/yandexru45/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Подробности: https://uralgit.ru/ural/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Точно хотите продолжить? ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m╚══════════════════════════════════════════════════════════════════════╝\033[0m\n"
|
||||
|
||||
@ -76,7 +82,7 @@ update_config() {
|
||||
printf "\033[48;5;196m\033[1m║ ! Detected old NetShift version. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ If you continue the update, you will need to RECONFIGURE NetShift. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Your old configuration will be saved to /etc/config/netshift-070 ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Details: https://github.com/yandexru45/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Details: https://uralgit.ru/ural/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Are you sure you want to continue? ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m╚══════════════════════════════════════════════════════════════════════╝\033[0m\n"
|
||||
|
||||
@ -88,7 +94,7 @@ update_config() {
|
||||
|
||||
yes|y|Y)
|
||||
mv /etc/config/netshift /etc/config/netshift-070
|
||||
wget -O /etc/config/netshift https://raw.githubusercontent.com/yandexru45/netshift/refs/heads/main/netshift/files/etc/config/netshift
|
||||
wget -O /etc/config/netshift https://uralgit.ru/ural/netshift/raw/branch/main/netshift/files/etc/config/netshift
|
||||
msg "NetShift config has been reset to default. Your old config saved in /etc/config/netshift-070"
|
||||
break
|
||||
;;
|
||||
@ -129,7 +135,7 @@ migrate_from_podkop() {
|
||||
printf "\033[48;5;196m\033[1m║ Ваша конфигурация будет перенесена автоматически. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Старая конфигурация сохранится в /etc/config/podkop.bak.pre-netshift║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Старый пакет podkop будет удалён, NetShift будет установлен. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Подробности: https://github.com/yandexru45/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Подробности: https://uralgit.ru/ural/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Точно хотите продолжить? ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m╚══════════════════════════════════════════════════════════════════════╝\033[0m\n"
|
||||
|
||||
@ -140,7 +146,7 @@ migrate_from_podkop() {
|
||||
printf "\033[48;5;196m\033[1m║ Your configuration will be carried over automatically. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Old config will be backed up to /etc/config/podkop.bak.pre-netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ The old podkop package will be removed, NetShift installed. ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Details: https://github.com/yandexru45/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Details: https://uralgit.ru/ural/netshift ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m║ Are you sure you want to continue? ║\033[0m\n"
|
||||
printf "\033[48;5;196m\033[1m╚══════════════════════════════════════════════════════════════════════╝\033[0m\n"
|
||||
|
||||
@ -241,6 +247,30 @@ migrate_from_podkop() {
|
||||
msg "Your old config is preserved at /etc/config/podkop.bak.pre-netshift"
|
||||
}
|
||||
|
||||
# Download one release asset URL into $DOWNLOAD_DIR with retry. POSIX sh.
|
||||
download_release_asset() {
|
||||
url="$1"
|
||||
filename="$2"
|
||||
filepath="$DOWNLOAD_DIR/$filename"
|
||||
|
||||
attempt=0
|
||||
while [ $attempt -lt $COUNT ]; do
|
||||
msg "Download $filename (count $((attempt + 1)))..."
|
||||
if wget -q -O "$filepath" "$url"; then
|
||||
if [ -s "$filepath" ]; then
|
||||
msg "$filename successfully downloaded"
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
msg "Download error for $filename. Retrying..."
|
||||
rm -f "$filepath"
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
msg "Failed to download $filename after $COUNT attempts"
|
||||
return 1
|
||||
}
|
||||
|
||||
main() {
|
||||
check_system
|
||||
sing_box
|
||||
@ -255,44 +285,63 @@ main() {
|
||||
msg "Installing NetShift..."
|
||||
fi
|
||||
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
check_response=$(curl -s "https://api.github.com/repos/yandexru45/netshift/releases/latest")
|
||||
|
||||
if echo "$check_response" | grep -q 'API rate limit '; then
|
||||
msg "You've reached the GitHub rate limit. Repeat in five minutes."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
local grep_url_pattern
|
||||
local ext release_tag redirect_url
|
||||
if [ "$PKG_IS_APK" -eq 1 ]; then
|
||||
grep_url_pattern='https://[^"[:space:]]*\.apk'
|
||||
ext="apk"
|
||||
else
|
||||
grep_url_pattern='https://[^"[:space:]]*\.ipk'
|
||||
ext="ipk"
|
||||
fi
|
||||
|
||||
wget -qO- "$REPO" | grep -o "$grep_url_pattern" | while read -r url; do
|
||||
filename=$(basename "$url")
|
||||
filepath="$DOWNLOAD_DIR/$filename"
|
||||
# PRIMARY: resolve the latest tag via the uralgit.ru frontend redirect (no
|
||||
# api.github.com hit → not subject to the 60/hour/IP rate limit), then build
|
||||
# the deterministic releases/download/<tag>/<asset> URLs and download them.
|
||||
release_tag=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
redirect_url=$(curl -sI -o /dev/null -w '%{redirect_url}' \
|
||||
--connect-timeout 5 -m 15 -A 'netshift-installer' \
|
||||
"$RELEASES_LATEST_REDIRECT" 2>/dev/null)
|
||||
case "$redirect_url" in
|
||||
*/releases/tag/*)
|
||||
release_tag="${redirect_url##*/releases/tag/}"
|
||||
case "$release_tag" in '' | */*) release_tag="" ;; esac
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
attempt=0
|
||||
while [ $attempt -lt $COUNT ]; do
|
||||
msg "Download $filename (count $((attempt+1)))..."
|
||||
if wget -q -O "$filepath" "$url"; then
|
||||
if [ -s "$filepath" ]; then
|
||||
msg "$filename successfully downloaded"
|
||||
break
|
||||
fi
|
||||
if [ -n "$release_tag" ]; then
|
||||
msg "Latest NetShift release: $release_tag (direct download, no GitHub API)"
|
||||
for pkg in netshift luci-app-netshift; do
|
||||
if [ "$ext" = "ipk" ]; then
|
||||
filename="${pkg}-${release_tag}-r1-all.${ext}"
|
||||
else
|
||||
filename="${pkg}-${release_tag}-r1.${ext}"
|
||||
fi
|
||||
msg "Download error for $filename. Retrying..."
|
||||
rm -f "$filepath"
|
||||
attempt=$((attempt+1))
|
||||
download_release_asset "$RELEASES_DOWNLOAD_BASE/$release_tag/$filename" "$filename"
|
||||
done
|
||||
|
||||
if [ $attempt -eq $COUNT ]; then
|
||||
msg "Failed to download $filename after $COUNT attempts"
|
||||
# RU i18n only if already installed (mirrors the install flow below).
|
||||
if pkg_is_installed luci-i18n-netshift-ru; then
|
||||
filename="luci-i18n-netshift-ru-${release_tag}.${ext}"
|
||||
download_release_asset "$RELEASES_DOWNLOAD_BASE/$release_tag/$filename" "$filename"
|
||||
fi
|
||||
done
|
||||
else
|
||||
# FALLBACK: scrape the api.github.com release JSON for .ipk/.apk URLs.
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
check_response=$(curl -s "$REPO")
|
||||
|
||||
if echo "$check_response" | grep -q 'API rate limit '; then
|
||||
msg "You've reached the GitHub rate limit. Repeat in five minutes."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
local grep_url_pattern
|
||||
grep_url_pattern="https://[^\"[:space:]]*\.${ext}"
|
||||
|
||||
wget -qO- "$REPO" | grep -o "$grep_url_pattern" | while read -r url; do
|
||||
filename=$(basename "$url")
|
||||
download_release_asset "$url" "$filename"
|
||||
done
|
||||
fi
|
||||
|
||||
# Check if any files were downloaded
|
||||
if ! ls "$DOWNLOAD_DIR"/*netshift* >/dev/null 2>&1; then
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
"require baseclass";
|
||||
"require form";
|
||||
"require ui";
|
||||
"require uci";
|
||||
"require fs";
|
||||
"require view.netshift.main as main";
|
||||
|
||||
function createManagerContent(section) {
|
||||
const o = section.option(form.DummyValue, "_mount_node");
|
||||
o.rawhtml = true;
|
||||
o.cfgvalue = () => {
|
||||
main.ManagerTab.initController();
|
||||
return main.ManagerTab.render();
|
||||
};
|
||||
}
|
||||
|
||||
const EntryPoint = {
|
||||
createManagerContent,
|
||||
};
|
||||
|
||||
return baseclass.extend(EntryPoint);
|
||||
@ -17,6 +17,9 @@
|
||||
// Diagnostic content
|
||||
"require view.netshift.diagnostic as diagnostic";
|
||||
|
||||
// Component Manager content
|
||||
"require view.netshift.manager as manager";
|
||||
|
||||
const EntryPoint = {
|
||||
async render() {
|
||||
main.injectGlobalStyles();
|
||||
@ -29,6 +32,21 @@ const EntryPoint = {
|
||||
// Enable tab views
|
||||
netshiftMap.tabbed = true;
|
||||
|
||||
// Dashboard tab (first / landing tab)
|
||||
const dashboardSection = netshiftMap.section(
|
||||
form.TypedSection,
|
||||
"dashboard",
|
||||
_("Dashboard"),
|
||||
);
|
||||
dashboardSection.anonymous = true;
|
||||
dashboardSection.addremove = false;
|
||||
dashboardSection.cfgsections = function () {
|
||||
return ["dashboard"];
|
||||
};
|
||||
|
||||
// Render dashboard content
|
||||
dashboard.createDashboardContent(dashboardSection);
|
||||
|
||||
// Sections tab
|
||||
const sectionsSection = netshiftMap.section(
|
||||
form.TypedSection,
|
||||
@ -58,6 +76,21 @@ const EntryPoint = {
|
||||
// Render settings content
|
||||
settings.createSettingsContent(settingsSection);
|
||||
|
||||
// Component Manager tab
|
||||
const managerSection = netshiftMap.section(
|
||||
form.TypedSection,
|
||||
"manager",
|
||||
_("Component Manager"),
|
||||
);
|
||||
managerSection.anonymous = true;
|
||||
managerSection.addremove = false;
|
||||
managerSection.cfgsections = function () {
|
||||
return ["manager"];
|
||||
};
|
||||
|
||||
// Render Component Manager content
|
||||
manager.createManagerContent(managerSection);
|
||||
|
||||
// Diagnostic tab
|
||||
const diagnosticSection = netshiftMap.section(
|
||||
form.TypedSection,
|
||||
@ -73,21 +106,6 @@ const EntryPoint = {
|
||||
// Render diagnostic content
|
||||
diagnostic.createDiagnosticContent(diagnosticSection);
|
||||
|
||||
// Dashboard tab
|
||||
const dashboardSection = netshiftMap.section(
|
||||
form.TypedSection,
|
||||
"dashboard",
|
||||
_("Dashboard"),
|
||||
);
|
||||
dashboardSection.anonymous = true;
|
||||
dashboardSection.addremove = false;
|
||||
dashboardSection.cfgsections = function () {
|
||||
return ["dashboard"];
|
||||
};
|
||||
|
||||
// Render dashboard content
|
||||
dashboard.createDashboardContent(dashboardSection);
|
||||
|
||||
// Inject core service
|
||||
main.coreService();
|
||||
|
||||
|
||||
@ -6,7 +6,34 @@
|
||||
"require view.netshift.main as main";
|
||||
|
||||
function createSectionContent(section) {
|
||||
let o = section.option(
|
||||
// Group the 36 connection options into 4 native CBI option-group tabs.
|
||||
// HARD RULE: once a section has tab(), every option MUST be added via
|
||||
// taboption() — any leftover section.option(...) renders nothing.
|
||||
// depends() works across tabs; a tab whose options are all depends-hidden
|
||||
// auto-hides from the strip (desired, e.g. Subscription for proxy/url).
|
||||
section.tab(
|
||||
"connection",
|
||||
_("Connection"),
|
||||
_("Connection type, transport and DNS resolver for this section"),
|
||||
);
|
||||
section.tab(
|
||||
"subscription",
|
||||
_("Subscription"),
|
||||
_("Subscription feeds, server filters and URLTest tuning"),
|
||||
);
|
||||
section.tab(
|
||||
"routing",
|
||||
_("Routing"),
|
||||
_("Domain and subnet lists that decide which traffic uses this section"),
|
||||
);
|
||||
section.tab(
|
||||
"advanced",
|
||||
_("Advanced"),
|
||||
_("Mixed proxy and DNS resolution tuning"),
|
||||
);
|
||||
|
||||
let o = section.taboption(
|
||||
"connection",
|
||||
form.ListValue,
|
||||
"connection_type",
|
||||
_("Connection Type"),
|
||||
@ -17,7 +44,8 @@ function createSectionContent(section) {
|
||||
o.value("block", "Block");
|
||||
o.value("exclusion", "Exclusion");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.ListValue,
|
||||
"proxy_config_type",
|
||||
_("Configuration Type"),
|
||||
@ -26,16 +54,21 @@ function createSectionContent(section) {
|
||||
o.value("url", _("Connection URL"));
|
||||
o.value("selector", _("Selector"));
|
||||
o.value("urltest", _("URLTest"));
|
||||
o.value("selector_text", _("Selector (text list)"));
|
||||
o.value("urltest_text", _("URLTest (text list)"));
|
||||
o.value("subscription", _("Subscription"));
|
||||
o.value("outbound", _("Outbound Config"));
|
||||
o.default = "url";
|
||||
o.depends("connection_type", "proxy");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.TextValue,
|
||||
"proxy_string",
|
||||
_("Proxy Configuration URL"),
|
||||
_("vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links")
|
||||
_(
|
||||
"vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "url" });
|
||||
o.rows = 5;
|
||||
@ -60,7 +93,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.TextValue,
|
||||
"outbound_json",
|
||||
_("Outbound Configuration"),
|
||||
@ -83,15 +117,18 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
form.Value,
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.DynamicList,
|
||||
"subscription_url",
|
||||
_("Subscription URL"),
|
||||
_("Enter the subscription URL to fetch proxy configurations from your provider"),
|
||||
_("Subscription URLs"),
|
||||
_(
|
||||
"Add one or more subscription URLs to fetch proxy configurations from. All feeds are downloaded and merged.",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
o.placeholder = "https://example.com/api/sub";
|
||||
o.rmempty = false;
|
||||
o.rmempty = true;
|
||||
o.validate = function (section_id, value) {
|
||||
if (!value || value.length === 0) {
|
||||
return true;
|
||||
@ -106,7 +143,38 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.ListValue,
|
||||
"subscription_format_preference",
|
||||
_("Subscription format"),
|
||||
_(
|
||||
"Which subscription format (client) to fetch first. Auto uses the default order. Choose Xray JSON (Happ) when your panel only exposes some nodes (e.g. xhttp) under a Happ-like client, or Sing-box to prefer the sing-box format.",
|
||||
),
|
||||
);
|
||||
o.value("auto", _("Auto"));
|
||||
o.value("xray", _("Xray JSON (Happ)"));
|
||||
o.value("singbox", _("Sing-box"));
|
||||
o.default = "auto";
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.Flag,
|
||||
"subscription_insecure",
|
||||
_("Allow insecure TLS for subscription fetch"),
|
||||
_("Disables TLS certificate verification when downloading the subscription.") +
|
||||
" " +
|
||||
_("Use only for IP-host panels that serve an invalid or self-signed certificate.") +
|
||||
" " +
|
||||
_("This is a security trade-off: an attacker could intercept the fetch."),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.ListValue,
|
||||
"subscription_update_interval",
|
||||
_("Subscription Update Interval"),
|
||||
@ -121,39 +189,70 @@ function createSectionContent(section) {
|
||||
o.default = "1h";
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o = section.option(
|
||||
form.Flag,
|
||||
"subscription_group_by_countries",
|
||||
_("Группировать по странам"),
|
||||
_("Группирует прокси подписки по флагу страны в начале тега в отдельные URLTest-группы"),
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.ListValue,
|
||||
"subscription_group_mode",
|
||||
_("Subscription grouping"),
|
||||
_(
|
||||
"Group subscription proxies into URLTest groups. 'By country flag' uses the flag emoji at the start of each name; 'By name prefix' groups by the first N characters.",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.value("off", _("Off"));
|
||||
o.value("country", _("By country flag"));
|
||||
o.value("prefix", _("By name prefix"));
|
||||
o.default = "off";
|
||||
o.rmempty = false;
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.Value,
|
||||
"subscription_group_prefix_len",
|
||||
_("Prefix length"),
|
||||
_("Number of leading characters of each proxy name to group by."),
|
||||
);
|
||||
o.default = "2";
|
||||
o.datatype = "and(uinteger,min(1))";
|
||||
o.rmempty = false;
|
||||
o.depends({
|
||||
connection_type: "proxy",
|
||||
proxy_config_type: "subscription",
|
||||
subscription_group_mode: "prefix",
|
||||
});
|
||||
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.DynamicList,
|
||||
"subscription_filter_include_keywords",
|
||||
_("Include servers by keyword"),
|
||||
_("Keep only subscription servers whose name contains at least one of these keywords (case-insensitive). Leave empty to keep all."),
|
||||
_(
|
||||
"Keep only subscription servers whose name contains at least one of these keywords (case-insensitive). Leave empty to keep all.",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
o.rmempty = true;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.DynamicList,
|
||||
"subscription_filter_exclude_keywords",
|
||||
_("Exclude servers by keyword"),
|
||||
_("Drop subscription servers whose name contains any of these keywords (case-insensitive)."),
|
||||
_(
|
||||
"Drop subscription servers whose name contains any of these keywords (case-insensitive).",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
o.rmempty = true;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.DynamicList,
|
||||
"selector_proxy_links",
|
||||
_("Selector Proxy Links"),
|
||||
_("vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links")
|
||||
_(
|
||||
"vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "selector" });
|
||||
o.rmempty = false;
|
||||
@ -172,11 +271,43 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.TextValue,
|
||||
"selector_proxy_links_text",
|
||||
_("Selector Proxy Links (one per line)"),
|
||||
_(
|
||||
"vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links — one per line",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "selector_text" });
|
||||
o.rows = 5;
|
||||
o.wrap = "soft";
|
||||
o.textarea = true;
|
||||
o.rmempty = false;
|
||||
o.validate = function (section_id, value) {
|
||||
// Optional
|
||||
if (!value || value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const validation = main.validateProxyUrlList(value);
|
||||
|
||||
if (validation.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.DynamicList,
|
||||
"urltest_proxy_links",
|
||||
_("URLTest Proxy Links"),
|
||||
_("vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links")
|
||||
_(
|
||||
"vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest" });
|
||||
o.rmempty = false;
|
||||
@ -195,11 +326,41 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.TextValue,
|
||||
"urltest_proxy_links_text",
|
||||
_("URLTest Proxy Links (one per line)"),
|
||||
_(
|
||||
"vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links — one per line",
|
||||
),
|
||||
);
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest_text" });
|
||||
o.rows = 5;
|
||||
o.wrap = "soft";
|
||||
o.textarea = true;
|
||||
o.rmempty = false;
|
||||
o.validate = function (section_id, value) {
|
||||
// Optional
|
||||
if (!value || value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const validation = main.validateProxyUrlList(value);
|
||||
|
||||
if (validation.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.ListValue,
|
||||
"urltest_check_interval",
|
||||
_("URLTest Check Interval"),
|
||||
_("The interval between connectivity tests")
|
||||
_("The interval between connectivity tests"),
|
||||
);
|
||||
o.value("30s", _("Every 30 seconds"));
|
||||
o.value("1m", _("Every 1 minute"));
|
||||
@ -207,17 +368,22 @@ function createSectionContent(section) {
|
||||
o.value("5m", _("Every 5 minutes"));
|
||||
o.default = "3m";
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest_text" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.Value,
|
||||
"urltest_tolerance",
|
||||
_("URLTest Tolerance"),
|
||||
_("The maximum difference in response times (ms) allowed when comparing servers")
|
||||
_(
|
||||
"The maximum difference in response times (ms) allowed when comparing servers",
|
||||
),
|
||||
);
|
||||
o.default = "50";
|
||||
o.rmempty = false;
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest_text" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
o.validate = function (section_id, value) {
|
||||
if (!value || value.length === 0) {
|
||||
@ -226,26 +392,43 @@ function createSectionContent(section) {
|
||||
|
||||
const parsed = parseFloat(value);
|
||||
|
||||
if (/^[0-9]+$/.test(value) && !isNaN(parsed) && isFinite(parsed) && parsed >= 50 && parsed <= 1000) {
|
||||
if (
|
||||
/^[0-9]+$/.test(value) &&
|
||||
!isNaN(parsed) &&
|
||||
isFinite(parsed) &&
|
||||
parsed >= 50 &&
|
||||
parsed <= 1000
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return _('Must be a number in the range of 50 - 1000');
|
||||
return _("Must be a number in the range of 50 - 1000");
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"subscription",
|
||||
form.Value,
|
||||
"urltest_testing_url",
|
||||
_("URLTest Testing URL"),
|
||||
_("The URL used to test server connectivity")
|
||||
_("The URL used to test server connectivity"),
|
||||
);
|
||||
o.value(
|
||||
"https://www.gstatic.com/generate_204",
|
||||
"https://www.gstatic.com/generate_204 (Google)",
|
||||
);
|
||||
o.value(
|
||||
"https://cp.cloudflare.com/generate_204",
|
||||
"https://cp.cloudflare.com/generate_204 (Cloudflare)",
|
||||
);
|
||||
o.value("https://www.gstatic.com/generate_204", "https://www.gstatic.com/generate_204 (Google)");
|
||||
o.value("https://cp.cloudflare.com/generate_204", "https://cp.cloudflare.com/generate_204 (Cloudflare)");
|
||||
o.value("https://captive.apple.com", "https://captive.apple.com (Apple)");
|
||||
o.value("https://connectivity-check.ubuntu.com", "https://connectivity-check.ubuntu.com (Ubuntu)")
|
||||
o.value(
|
||||
"https://connectivity-check.ubuntu.com",
|
||||
"https://connectivity-check.ubuntu.com (Ubuntu)",
|
||||
);
|
||||
o.default = "https://www.gstatic.com/generate_204";
|
||||
o.rmempty = false;
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "urltest_text" });
|
||||
o.depends({ connection_type: "proxy", proxy_config_type: "subscription" });
|
||||
|
||||
o.validate = function (section_id, value) {
|
||||
@ -262,7 +445,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.Flag,
|
||||
"enable_udp_over_tcp",
|
||||
_("UDP over TCP"),
|
||||
@ -272,7 +456,26 @@ function createSectionContent(section) {
|
||||
o.depends("connection_type", "proxy");
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.Flag,
|
||||
"global_proxy",
|
||||
_("Global Proxy"),
|
||||
_("Route all unmatched traffic through this section's outbound.") +
|
||||
" " +
|
||||
_(
|
||||
"When enabled, traffic not matching any other section's lists will go through this proxy.",
|
||||
) +
|
||||
" " +
|
||||
_("Use with Exclusion sections to route specific domains directly.") +
|
||||
" " +
|
||||
_("Only one section can be global at a time."),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
widgets.DeviceSelect,
|
||||
"interface",
|
||||
_("Network Interface"),
|
||||
@ -318,7 +521,8 @@ function createSectionContent(section) {
|
||||
return !isWireless;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.Flag,
|
||||
"domain_resolver_enabled",
|
||||
_("Domain Resolver"),
|
||||
@ -328,7 +532,8 @@ function createSectionContent(section) {
|
||||
o.rmempty = false;
|
||||
o.depends("connection_type", "vpn");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.ListValue,
|
||||
"domain_resolver_dns_type",
|
||||
_("DNS Protocol Type"),
|
||||
@ -341,7 +546,8 @@ function createSectionContent(section) {
|
||||
o.rmempty = false;
|
||||
o.depends("domain_resolver_enabled", "1");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"connection",
|
||||
form.Value,
|
||||
"domain_resolver_dns_server",
|
||||
_("DNS Server"),
|
||||
@ -363,12 +569,13 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"community_lists",
|
||||
_("Community Lists"),
|
||||
_("Select a predefined list for routing") +
|
||||
' <a href="https://github.com/itdoginfo/allow-domains" target="_blank">github.com/itdoginfo/allow-domains</a>',
|
||||
' <a href="https://github.com/itdoginfo/allow-domains" target="_blank">github.com/itdoginfo/allow-domains</a>',
|
||||
);
|
||||
o.placeholder = "Service list";
|
||||
Object.entries(main.DOMAIN_LIST_OPTIONS).forEach(([key, label]) => {
|
||||
@ -451,11 +658,18 @@ function createSectionContent(section) {
|
||||
}
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
// --- Custom domains group (mode selector + the matching input below) ---
|
||||
// Three UCI keys kept (user_domain_list_type, user_domains,
|
||||
// user_domains_text); depends() shows only the input for the chosen mode,
|
||||
// so the trio reads as one "list-or-text" control.
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.ListValue,
|
||||
"user_domain_list_type",
|
||||
_("User Domain List Type"),
|
||||
_("Select the list type for adding custom domains"),
|
||||
_("Custom domains"),
|
||||
_(
|
||||
"Add your own domains: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip",
|
||||
),
|
||||
);
|
||||
o.value("disabled", _("Disabled"));
|
||||
o.value("dynamic", _("Dynamic List"));
|
||||
@ -463,7 +677,8 @@ function createSectionContent(section) {
|
||||
o.default = "disabled";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"user_domains",
|
||||
_("User Domains"),
|
||||
@ -489,7 +704,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.TextValue,
|
||||
"user_domains_text",
|
||||
_("User Domains List"),
|
||||
@ -531,11 +747,17 @@ function createSectionContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
// --- Custom subnets group (mode selector + the matching input below) ---
|
||||
// Same pattern as the domains group; keeps user_subnet_list_type,
|
||||
// user_subnets and user_subnets_text as separate UCI keys.
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.ListValue,
|
||||
"user_subnet_list_type",
|
||||
_("User Subnet List Type"),
|
||||
_("Select the list type for adding custom subnets"),
|
||||
_("Custom subnets"),
|
||||
_(
|
||||
"Add your own subnets or IPs: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip",
|
||||
),
|
||||
);
|
||||
o.value("disabled", _("Disabled"));
|
||||
o.value("dynamic", _("Dynamic List"));
|
||||
@ -543,7 +765,8 @@ function createSectionContent(section) {
|
||||
o.default = "disabled";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"user_subnets",
|
||||
_("User Subnets"),
|
||||
@ -569,13 +792,14 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.TextValue,
|
||||
"user_subnets_text",
|
||||
_("User Subnets List"),
|
||||
_(
|
||||
"Enter subnets in CIDR notation or single IP addresses, separated by commas, spaces, or newlines. " +
|
||||
"You can add comments using //",
|
||||
"You can add comments using //",
|
||||
),
|
||||
);
|
||||
o.placeholder =
|
||||
@ -610,7 +834,8 @@ function createSectionContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"local_domain_lists",
|
||||
_("Local Domain Lists"),
|
||||
@ -633,7 +858,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"local_subnet_lists",
|
||||
_("Local Subnet Lists"),
|
||||
@ -656,7 +882,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"remote_domain_lists",
|
||||
_("Remote Domain Lists"),
|
||||
@ -679,7 +906,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"remote_subnet_lists",
|
||||
_("Remote Subnet Lists"),
|
||||
@ -702,7 +930,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"routing",
|
||||
form.DynamicList,
|
||||
"fully_routed_ips",
|
||||
_("Fully Routed IPs"),
|
||||
@ -729,7 +958,8 @@ function createSectionContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"mixed_proxy_enabled",
|
||||
_("Enable Mixed Proxy"),
|
||||
@ -742,13 +972,14 @@ function createSectionContent(section) {
|
||||
o.depends("connection_type", "proxy");
|
||||
o.depends("connection_type", "vpn");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Value,
|
||||
"mixed_proxy_port",
|
||||
_("Mixed Proxy Port"),
|
||||
_(
|
||||
"Specify the port number on which the mixed proxy will run for this section. " +
|
||||
"Make sure the selected port is not used by another service",
|
||||
"Make sure the selected port is not used by another service",
|
||||
),
|
||||
);
|
||||
o.default = "2080";
|
||||
@ -757,7 +988,8 @@ function createSectionContent(section) {
|
||||
o.rmempty = true;
|
||||
o.depends("mixed_proxy_enabled", "1");
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"resolve_real_ip_for_routing",
|
||||
_("Resolve real IP for routing"),
|
||||
|
||||
@ -6,7 +6,40 @@
|
||||
"require view.netshift.main as main";
|
||||
|
||||
function createSettingsContent(section) {
|
||||
let o = section.option(
|
||||
// Group the 27 settings options into 5 native CBI option-group tabs.
|
||||
// HARD RULE: once a section has tab(), every option MUST be added via
|
||||
// taboption() — any leftover section.option(...) renders nothing.
|
||||
// depends() works across tabs; a tab whose options are all depends-hidden
|
||||
// auto-hides from the strip.
|
||||
section.tab(
|
||||
"dns",
|
||||
_("DNS"),
|
||||
_("Upstream and bootstrap DNS resolvers, and optional DNS-over-proxy"),
|
||||
);
|
||||
section.tab(
|
||||
"network",
|
||||
_("Network"),
|
||||
_("Source and output interfaces, and Bad WAN interface monitoring"),
|
||||
);
|
||||
section.tab(
|
||||
"lists",
|
||||
_("Lists & Updates"),
|
||||
_("List update schedule, download routing, and routing exclusions"),
|
||||
);
|
||||
section.tab(
|
||||
"yacd",
|
||||
_("Dashboard"),
|
||||
_("YACD web dashboard access and remote-access protection"),
|
||||
);
|
||||
section.tab(
|
||||
"advanced",
|
||||
_("Advanced"),
|
||||
_("Protocol toggles, file paths and logging. Block DoH only after switching upstream DNS to UDP or DoT."),
|
||||
);
|
||||
|
||||
// --- DNS tab ---
|
||||
let o = section.taboption(
|
||||
"dns",
|
||||
form.ListValue,
|
||||
"dns_type",
|
||||
_("DNS Protocol Type"),
|
||||
@ -18,7 +51,8 @@ function createSettingsContent(section) {
|
||||
o.default = "udp";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"dns",
|
||||
form.Value,
|
||||
"dns_server",
|
||||
_("DNS Server"),
|
||||
@ -39,7 +73,8 @@ function createSettingsContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"dns",
|
||||
form.Value,
|
||||
"bootstrap_dns_server",
|
||||
_("Bootstrap DNS server"),
|
||||
@ -62,7 +97,55 @@ function createSettingsContent(section) {
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"dns",
|
||||
form.Flag,
|
||||
"dns_via_outbound",
|
||||
_("Route main DNS through proxy/VPN"),
|
||||
_(
|
||||
"Send upstream DNS queries through a proxy/VPN outbound instead of directly. Bootstrap DNS always stays direct.",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"dns",
|
||||
form.ListValue,
|
||||
"dns_outbound_section",
|
||||
_("DNS outbound section"),
|
||||
_(
|
||||
"Which proxy/VPN section carries the DNS. Leave unset to use the first configured outbound.",
|
||||
),
|
||||
);
|
||||
o.rmempty = true;
|
||||
o.depends("dns_via_outbound", "1");
|
||||
o.cfgvalue = function (section_id) {
|
||||
return uci.get("netshift", section_id, "dns_outbound_section");
|
||||
};
|
||||
o.load = function () {
|
||||
const sections = this.map?.data?.state?.values?.netshift ?? {};
|
||||
|
||||
this.keylist = [];
|
||||
this.vallist = [];
|
||||
|
||||
for (const secName in sections) {
|
||||
const sec = sections[secName];
|
||||
if (
|
||||
sec[".type"] === "section" &&
|
||||
sec["connection_type"] !== "block" &&
|
||||
sec["connection_type"] !== "exclusion"
|
||||
) {
|
||||
this.keylist.push(secName);
|
||||
this.vallist.push(secName);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
o = section.taboption(
|
||||
"dns",
|
||||
form.Value,
|
||||
"dns_rewrite_ttl",
|
||||
_("DNS Rewrite TTL"),
|
||||
@ -83,7 +166,9 @@ function createSettingsContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
// --- Network tab ---
|
||||
o = section.taboption(
|
||||
"network",
|
||||
widgets.DeviceSelect,
|
||||
"source_network_interfaces",
|
||||
_("Source Network Interface"),
|
||||
@ -120,7 +205,8 @@ function createSettingsContent(section) {
|
||||
return !isWireless;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"network",
|
||||
form.Flag,
|
||||
"enable_output_network_interface",
|
||||
_("Enable Output Network Interface"),
|
||||
@ -129,7 +215,8 @@ function createSettingsContent(section) {
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"network",
|
||||
widgets.DeviceSelect,
|
||||
"output_network_interface",
|
||||
_("Output Network Interface"),
|
||||
@ -148,9 +235,7 @@ function createSettingsContent(section) {
|
||||
}
|
||||
|
||||
// Reject lan*
|
||||
if (
|
||||
value.startsWith("lan")
|
||||
) {
|
||||
if (value.startsWith("lan")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -183,7 +268,8 @@ function createSettingsContent(section) {
|
||||
return !isWireless;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"network",
|
||||
form.Flag,
|
||||
"enable_badwan_interface_monitoring",
|
||||
_("Interface Monitoring"),
|
||||
@ -192,7 +278,8 @@ function createSettingsContent(section) {
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"network",
|
||||
widgets.NetworkSelect,
|
||||
"badwan_monitored_interfaces",
|
||||
_("Monitored Interfaces"),
|
||||
@ -215,7 +302,8 @@ function createSettingsContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"network",
|
||||
form.Value,
|
||||
"badwan_reload_delay",
|
||||
_("Interface Monitoring Delay"),
|
||||
@ -231,46 +319,9 @@ function createSettingsContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
form.Flag,
|
||||
"enable_yacd",
|
||||
_("Enable YACD"),
|
||||
`<a href="${main.getClashUIUrl()}" target="_blank">${main.getClashUIUrl()}</a>`,
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
form.Flag,
|
||||
"enable_yacd_wan_access",
|
||||
_("Enable YACD WAN Access"),
|
||||
_("Allows access to YACD from the WAN. Make sure to open the appropriate port in your firewall."),
|
||||
);
|
||||
o.depends("enable_yacd", "1");
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
form.Value,
|
||||
"yacd_secret_key",
|
||||
_("YACD Secret Key"),
|
||||
_("Secret key for authenticating remote access to YACD when WAN access is enabled."),
|
||||
);
|
||||
o.depends("enable_yacd_wan_access", "1");
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
form.Flag,
|
||||
"disable_quic",
|
||||
_("Disable QUIC"),
|
||||
_(
|
||||
"Disable the QUIC protocol to improve compatibility or fix issues with video streaming",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
// --- Lists & Updates tab ---
|
||||
o = section.taboption(
|
||||
"lists",
|
||||
form.ListValue,
|
||||
"update_interval",
|
||||
_("List Update Frequency"),
|
||||
@ -282,7 +333,8 @@ function createSettingsContent(section) {
|
||||
o.default = "1d";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"lists",
|
||||
form.Flag,
|
||||
"download_lists_via_proxy",
|
||||
_("Download Lists via Proxy/VPN"),
|
||||
@ -291,7 +343,8 @@ function createSettingsContent(section) {
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"lists",
|
||||
form.ListValue,
|
||||
"download_lists_via_proxy_section",
|
||||
_("Download Lists via specific proxy section"),
|
||||
@ -311,7 +364,11 @@ function createSettingsContent(section) {
|
||||
|
||||
for (const secName in sections) {
|
||||
const sec = sections[secName];
|
||||
if (sec[".type"] === "section" && sec['connection_type'] !== 'block' && sec['connection_type'] !== 'exclusion') {
|
||||
if (
|
||||
sec[".type"] === "section" &&
|
||||
sec["connection_type"] !== "block" &&
|
||||
sec["connection_type"] !== "exclusion"
|
||||
) {
|
||||
this.keylist.push(secName);
|
||||
this.vallist.push(secName);
|
||||
}
|
||||
@ -320,7 +377,81 @@ function createSettingsContent(section) {
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"lists",
|
||||
form.DynamicList,
|
||||
"routing_excluded_ips",
|
||||
_("Routing Excluded IPs"),
|
||||
_("Specify a local IP address to be excluded from routing"),
|
||||
);
|
||||
o.placeholder = "IP";
|
||||
o.rmempty = true;
|
||||
o.validate = function (section_id, value) {
|
||||
// Optional
|
||||
if (!value || value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const validation = main.validateIP(value);
|
||||
|
||||
if (validation.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return validation.message;
|
||||
};
|
||||
|
||||
// --- Dashboard / YACD tab ---
|
||||
o = section.taboption(
|
||||
"yacd",
|
||||
form.Flag,
|
||||
"enable_yacd",
|
||||
_("Enable YACD"),
|
||||
`<a href="${main.getClashUIUrl()}" target="_blank">${main.getClashUIUrl()}</a>`,
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"yacd",
|
||||
form.Flag,
|
||||
"enable_yacd_wan_access",
|
||||
_("Enable YACD WAN Access"),
|
||||
_(
|
||||
"Allows access to YACD from the WAN. Make sure to open the appropriate port in your firewall.",
|
||||
),
|
||||
);
|
||||
o.depends("enable_yacd", "1");
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"yacd",
|
||||
form.Value,
|
||||
"yacd_secret_key",
|
||||
_("YACD Secret Key"),
|
||||
_(
|
||||
"Secret key for authenticating remote access to YACD when WAN access is enabled.",
|
||||
),
|
||||
);
|
||||
o.depends("enable_yacd_wan_access", "1");
|
||||
o.rmempty = false;
|
||||
|
||||
// --- Advanced tab ---
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"disable_quic",
|
||||
_("Disable QUIC"),
|
||||
_(
|
||||
"Disable the QUIC protocol to improve compatibility or fix issues with video streaming",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"dont_touch_dhcp",
|
||||
_("Dont Touch My DHCP!"),
|
||||
@ -329,7 +460,44 @@ function createSettingsContent(section) {
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"exclude_ntp",
|
||||
_("Exclude NTP"),
|
||||
_(
|
||||
"Exclude NTP protocol traffic from the tunnel to prevent it from being routed through the proxy or VPN",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"block_doh",
|
||||
_("Block DoH Servers"),
|
||||
_(
|
||||
"Block direct connections to known public DoH servers (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex) so apps cannot bypass router DNS filtering.",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Flag,
|
||||
"enable_ipv6",
|
||||
_("Enable IPv6 Support"),
|
||||
_("Enable IPv6 TProxy routing, IPv6 DNS inbound, and IPv6 FakeIP support.") +
|
||||
" " +
|
||||
_("Use this only when the router has working IPv6 connectivity."),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.ListValue,
|
||||
"config_path",
|
||||
_("Config File Path"),
|
||||
@ -342,7 +510,8 @@ function createSettingsContent(section) {
|
||||
o.default = "/etc/sing-box/config.json";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.Value,
|
||||
"cache_path",
|
||||
_("Cache File Path"),
|
||||
@ -378,13 +547,12 @@ function createSettingsContent(section) {
|
||||
return true;
|
||||
};
|
||||
|
||||
o = section.option(
|
||||
o = section.taboption(
|
||||
"advanced",
|
||||
form.ListValue,
|
||||
"log_level",
|
||||
_("Log Level"),
|
||||
_(
|
||||
"Select the log level for sing-box",
|
||||
),
|
||||
_("Select the log level for sing-box"),
|
||||
);
|
||||
o.value("trace", "Trace");
|
||||
o.value("debug", "Debug");
|
||||
@ -395,40 +563,6 @@ function createSettingsContent(section) {
|
||||
o.value("panic", "Panic");
|
||||
o.default = "warn";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
form.Flag,
|
||||
"exclude_ntp",
|
||||
_("Exclude NTP"),
|
||||
_(
|
||||
"Exclude NTP protocol traffic from the tunnel to prevent it from being routed through the proxy or VPN",
|
||||
),
|
||||
);
|
||||
o.default = "0";
|
||||
o.rmempty = false;
|
||||
|
||||
o = section.option(
|
||||
form.DynamicList,
|
||||
"routing_excluded_ips",
|
||||
_("Routing Excluded IPs"),
|
||||
_("Specify a local IP address to be excluded from routing"),
|
||||
);
|
||||
o.placeholder = "IP";
|
||||
o.rmempty = true;
|
||||
o.validate = function (section_id, value) {
|
||||
// Optional
|
||||
if (!value || value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const validation = main.validateIPV4(value);
|
||||
|
||||
if (validation.valid) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return validation.message;
|
||||
};
|
||||
}
|
||||
|
||||
const EntryPoint = {
|
||||
|
||||
@ -7,8 +7,8 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: NETSHIFT\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-06-05 09:28+0300\n"
|
||||
"PO-Revision-Date: 2026-06-05 09:28+0300\n"
|
||||
"POT-Creation-Date: 2026-06-13 14:14+0300\n"
|
||||
"PO-Revision-Date: 2026-06-13 14:14+0300\n"
|
||||
"Last-Translator: yandexru45\n"
|
||||
"Language-Team: none\n"
|
||||
"Language: ru\n"
|
||||
@ -29,33 +29,54 @@ msgstr "✘ Отключено"
|
||||
msgid "✘ Stopped"
|
||||
msgstr "✘ Остановлен"
|
||||
|
||||
msgid "Группировать по странам"
|
||||
msgstr ""
|
||||
|
||||
msgid "Группирует прокси подписки по флагу страны в начале тега в отдельные URLTest-группы"
|
||||
msgstr ""
|
||||
|
||||
msgid "Active Connections"
|
||||
msgstr "Активные соединения"
|
||||
|
||||
msgid "Add one or more subscription URLs to fetch proxy configurations from. All feeds are downloaded and merged."
|
||||
msgstr "Добавьте один или несколько URL подписок для получения конфигураций прокси. Все источники загружаются и объединяются."
|
||||
|
||||
msgid "Add your own domains: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip"
|
||||
msgstr "Добавьте свои домены: выберите Динамический список (по одному в строке) или Текстовый список (свободный ввод), либо Отключено, чтобы пропустить"
|
||||
|
||||
msgid "Add your own subnets or IPs: choose Dynamic List (one per row) or Text List (free-form), or Disabled to skip"
|
||||
msgstr "Добавьте свои подсети или IP: выберите Динамический список (по одному в строке) или Текстовый список (свободный ввод), либо Отключено, чтобы пропустить"
|
||||
|
||||
msgid "Additional marking rules found"
|
||||
msgstr "Найдены дополнительные правила маркировки"
|
||||
|
||||
msgid "Advanced"
|
||||
msgstr "Дополнительно"
|
||||
|
||||
msgid "Allow insecure TLS for subscription fetch"
|
||||
msgstr "Разрешить небезопасный TLS при загрузке подписки"
|
||||
|
||||
msgid "Allows access to YACD from the WAN. Make sure to open the appropriate port in your firewall."
|
||||
msgstr "Обеспечивает доступ к YACD из WAN. Убедитесь, что в брандмауэре открыт соответствующий порт."
|
||||
|
||||
msgid "Applicable for SOCKS and Shadowsocks proxy"
|
||||
msgstr "Применимо для SOCKS и Shadowsocks прокси"
|
||||
|
||||
msgid "At least one proxy link must be specified."
|
||||
msgstr "Необходимо указать хотя бы одну прокси-ссылку."
|
||||
|
||||
msgid "At least one valid domain must be specified. Comments-only content is not allowed."
|
||||
msgstr "Необходимо указать хотя бы один действительный домен. Содержимое только из комментариев не допускается."
|
||||
|
||||
msgid "At least one valid subnet or IP must be specified. Comments-only content is not allowed."
|
||||
msgstr "Необходимо указать хотя бы одну действительную подсеть или IP. Только комментарии недопустимы."
|
||||
|
||||
msgid "Auto"
|
||||
msgstr "Авто"
|
||||
|
||||
msgid "Available actions"
|
||||
msgstr "Доступные действия"
|
||||
|
||||
msgid "Block direct connections to known public DoH servers (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex) so apps cannot bypass router DNS filtering."
|
||||
msgstr "Блокировать прямые подключения к известным публичным DoH-серверам (Cloudflare, Google, Quad9, OpenDNS, AdGuard, Yandex), чтобы приложения не могли обойти DNS-фильтрацию роутера."
|
||||
|
||||
msgid "Block DoH Servers"
|
||||
msgstr "Блокировать DoH-серверы"
|
||||
|
||||
msgid "Bootsrap DNS"
|
||||
msgstr "Bootstrap DNS"
|
||||
|
||||
@ -68,6 +89,12 @@ msgstr "Браузер не использует FakeIP"
|
||||
msgid "Browser is using FakeIP correctly"
|
||||
msgstr "Браузер использует FakeIP"
|
||||
|
||||
msgid "By country flag"
|
||||
msgstr "По флагу страны"
|
||||
|
||||
msgid "By name prefix"
|
||||
msgstr "По префиксу имени"
|
||||
|
||||
msgid "Cache File Path"
|
||||
msgstr "Путь к файлу кэша"
|
||||
|
||||
@ -77,6 +104,9 @@ msgstr "Путь к файлу кэша не может быть пустым"
|
||||
msgid "Cannot receive checks result"
|
||||
msgstr "Не удалось получить результаты проверки"
|
||||
|
||||
msgid "Check update"
|
||||
msgstr "Проверить обновление"
|
||||
|
||||
msgid "Checking, please wait"
|
||||
msgstr "Проверяем, пожалуйста подождите"
|
||||
|
||||
@ -92,24 +122,39 @@ msgstr "Проверки пройдены"
|
||||
msgid "CIDR must be between 0 and 32"
|
||||
msgstr "CIDR должен быть между 0 и 32"
|
||||
|
||||
msgid "Clear subscription cache"
|
||||
msgstr "Очистить кеш подписок"
|
||||
|
||||
msgid "Clearing subscription cache and re-downloading… this may take a minute"
|
||||
msgstr "Очистка кеша подписок и повторная загрузка… это может занять минуту"
|
||||
|
||||
msgid "Close"
|
||||
msgstr "Закрыть"
|
||||
|
||||
msgid "Community Lists"
|
||||
msgstr "Списки сообщества"
|
||||
|
||||
msgid "Component Manager"
|
||||
msgstr "Менеджер компонентов"
|
||||
|
||||
msgid "Config File Path"
|
||||
msgstr "Путь к файлу конфигурации"
|
||||
|
||||
msgid "Configuration for NetShift service"
|
||||
msgstr ""
|
||||
msgstr "Конфигурация службы NetShift"
|
||||
|
||||
msgid "Configuration Type"
|
||||
msgstr "Тип конфигурации"
|
||||
|
||||
msgid "Connection"
|
||||
msgstr "Подключение"
|
||||
|
||||
msgid "Connection Type"
|
||||
msgstr "Тип подключения"
|
||||
|
||||
msgid "Connection type, transport and DNS resolver for this section"
|
||||
msgstr "Тип подключения, транспорт и DNS-резолвер для этой секции"
|
||||
|
||||
msgid "Connection URL"
|
||||
msgstr "URL подключения"
|
||||
|
||||
@ -125,6 +170,12 @@ msgstr "Истекло время ожидания переключения яд
|
||||
msgid "Currently unavailable"
|
||||
msgstr "Временно недоступно"
|
||||
|
||||
msgid "Custom domains"
|
||||
msgstr "Свои домены"
|
||||
|
||||
msgid "Custom subnets"
|
||||
msgstr "Свои подсети"
|
||||
|
||||
msgid "Dashboard"
|
||||
msgstr "Дашборд"
|
||||
|
||||
@ -132,11 +183,14 @@ msgid "Dashboard currently unavailable"
|
||||
msgstr "Дашборд сейчас недоступен"
|
||||
|
||||
msgid "Delay in milliseconds before reloading NetShift after interface UP"
|
||||
msgstr ""
|
||||
msgstr "Задержка в миллисекундах перед перезагрузкой NetShift после поднятия интерфейса"
|
||||
|
||||
msgid "Delay value cannot be empty"
|
||||
msgstr "Значение задержки не может быть пустым"
|
||||
|
||||
msgid "Dev"
|
||||
msgstr "Dev"
|
||||
|
||||
msgid "DHCP has DNS server"
|
||||
msgstr "DHCP содержит DNS сервер"
|
||||
|
||||
@ -155,9 +209,18 @@ msgstr "Отключить QUIC протокол для улучшения со
|
||||
msgid "Disabled"
|
||||
msgstr "Отключено"
|
||||
|
||||
msgid "Disables TLS certificate verification when downloading the subscription."
|
||||
msgstr "Отключает проверку TLS-сертификата при загрузке подписки."
|
||||
|
||||
msgid "DNS"
|
||||
msgstr "DNS"
|
||||
|
||||
msgid "DNS on router"
|
||||
msgstr "DNS на роутере"
|
||||
|
||||
msgid "DNS outbound section"
|
||||
msgstr "Секция outbound для DNS"
|
||||
|
||||
msgid "DNS over HTTPS (DoH)"
|
||||
msgstr "DNS через HTTPS (DoH)"
|
||||
|
||||
@ -179,6 +242,9 @@ msgstr "Адрес DNS-сервера не может быть пустым"
|
||||
msgid "Do not panic, everything can be fixed, just..."
|
||||
msgstr "Не паникуйте, всё можно исправить, просто..."
|
||||
|
||||
msgid "Domain and subnet lists that decide which traffic uses this section"
|
||||
msgstr "Списки доменов и подсетей, определяющие, какой трафик идёт через эту секцию"
|
||||
|
||||
msgid "Domain Resolver"
|
||||
msgstr "Резолвер доменов"
|
||||
|
||||
@ -215,6 +281,12 @@ msgstr "Включить встроенный DNS-резолвер для дом
|
||||
msgid "Enable DNS resolve to get real IP when routing"
|
||||
msgstr "Разрешать домены в реальные IP-адреса перед маршрутизацией в outbound"
|
||||
|
||||
msgid "Enable IPv6 Support"
|
||||
msgstr "Включить поддержку IPv6"
|
||||
|
||||
msgid "Enable IPv6 TProxy routing, IPv6 DNS inbound, and IPv6 FakeIP support."
|
||||
msgstr "Включить маршрутизацию TProxy по IPv6, входящий DNS по IPv6 и поддержку FakeIP для IPv6."
|
||||
|
||||
msgid "Enable Mixed Proxy"
|
||||
msgstr "Включить смешанный прокси"
|
||||
|
||||
@ -242,23 +314,20 @@ msgstr "Введите доменные имена без протоколов,
|
||||
msgid "Enter subnets in CIDR notation (e.g. 103.21.244.0/22) or single IP addresses"
|
||||
msgstr "Введите подсети в нотации CIDR (например, 103.21.244.0/22) или отдельные IP-адреса"
|
||||
|
||||
msgid "Enter the subscription URL to fetch proxy configurations from your provider"
|
||||
msgstr ""
|
||||
|
||||
msgid "Every 1 minute"
|
||||
msgstr "Каждую минуту"
|
||||
|
||||
msgid "Every 12 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 12 часов"
|
||||
|
||||
msgid "Every 3 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 3 часа"
|
||||
|
||||
msgid "Every 3 minutes"
|
||||
msgstr "Каждые 3 минуты"
|
||||
|
||||
msgid "Every 30 minutes"
|
||||
msgstr ""
|
||||
msgstr "Каждые 30 минут"
|
||||
|
||||
msgid "Every 30 seconds"
|
||||
msgstr "Каждые 30 секунд"
|
||||
@ -267,13 +336,13 @@ msgid "Every 5 minutes"
|
||||
msgstr "Каждые 5 минут"
|
||||
|
||||
msgid "Every 6 hours"
|
||||
msgstr ""
|
||||
msgstr "Каждые 6 часов"
|
||||
|
||||
msgid "Every day"
|
||||
msgstr ""
|
||||
msgstr "Каждый день"
|
||||
|
||||
msgid "Every hour"
|
||||
msgstr ""
|
||||
msgstr "Каждый час"
|
||||
|
||||
msgid "Exclude NTP"
|
||||
msgstr "Исключить NTP"
|
||||
@ -284,6 +353,9 @@ msgstr "Исключите трафик протокола NTP из туннел
|
||||
msgid "Exclude servers by keyword"
|
||||
msgstr "Исключать серверы по ключевому слову"
|
||||
|
||||
msgid "Failed to clear subscription cache"
|
||||
msgstr "Не удалось очистить кеш подписок"
|
||||
|
||||
msgid "Failed to copy!"
|
||||
msgstr "Не удалось скопировать!"
|
||||
|
||||
@ -302,8 +374,14 @@ msgstr "Получить глобальную проверку"
|
||||
msgid "Global check"
|
||||
msgstr "Глобальная проверка"
|
||||
|
||||
msgid "Global Proxy"
|
||||
msgstr "Глобальный прокси"
|
||||
|
||||
msgid "Group subscription proxies into URLTest groups. 'By country flag' uses the flag emoji at the start of each name; 'By name prefix' groups by the first N characters."
|
||||
msgstr "Группировать прокси из подписки в группы URLTest. «По флагу страны» использует эмодзи флага в начале каждого имени; «По префиксу имени» группирует по первым N символам."
|
||||
|
||||
msgid "How often to automatically update the subscription"
|
||||
msgstr ""
|
||||
msgstr "Как часто автоматически обновлять подписку"
|
||||
|
||||
msgid "HTTP error"
|
||||
msgstr "Ошибка HTTP"
|
||||
@ -311,11 +389,11 @@ msgstr "Ошибка HTTP"
|
||||
msgid "Include servers by keyword"
|
||||
msgstr "Включать серверы по ключевому слову"
|
||||
|
||||
msgid "Install extended"
|
||||
msgstr "Установить extended"
|
||||
msgid "Install %s"
|
||||
msgstr "Установить %s"
|
||||
|
||||
msgid "Install stable"
|
||||
msgstr "Установить stable"
|
||||
msgid "Installed version is newer than release"
|
||||
msgstr "Установленная версия новее релиза"
|
||||
|
||||
msgid "Interface Monitoring"
|
||||
msgstr "Мониторинг интерфейса"
|
||||
@ -326,14 +404,14 @@ msgstr "Задержка при мониторинге интерфейсов"
|
||||
msgid "Interface monitoring for Bad WAN"
|
||||
msgstr "Мониторинг интерфейса для Bad WAN"
|
||||
|
||||
msgid "Invalid DNS server format. Examples: 8.8.8.8 or dns.example.com or dns.example.com/nicedns for DoH"
|
||||
msgstr "Неверный формат DNS-сервера. Примеры: 8.8.8.8, dns.example.com или dns.example.com/nicedns для DoH"
|
||||
msgid "Invalid DNS server format. Examples: 8.8.8.8, [::1], dns.example.com, or dns.example.com/dns-query for DoH"
|
||||
msgstr "Неверный формат DNS-сервера. Примеры: 8.8.8.8, [::1], dns.example.com или dns.example.com/dns-query для DoH"
|
||||
|
||||
msgid "Invalid domain address"
|
||||
msgstr "Неверный домен"
|
||||
|
||||
msgid "Invalid format. Use X.X.X.X or X.X.X.X/Y"
|
||||
msgstr "Неверный формат. Используйте X.X.X.X или X.X.X.X/Y"
|
||||
msgid "Invalid format. Use X.X.X.X/Y or IPv6/Y"
|
||||
msgstr "Неверный формат. Используйте X.X.X.X/Y или IPv6/Y"
|
||||
|
||||
msgid "Invalid HY2 URL: insecure must be 0 or 1"
|
||||
msgstr "Неверный URL Hysteria2: параметр insecure должен быть 0 или 1"
|
||||
@ -377,6 +455,9 @@ msgstr "Неверный URL Hysteria2: неподдерживаемый тип
|
||||
msgid "Invalid IP address"
|
||||
msgstr "Неверный IP-адрес"
|
||||
|
||||
msgid "Invalid IPv6 address"
|
||||
msgstr "Неверный IPv6-адрес"
|
||||
|
||||
msgid "Invalid JSON format"
|
||||
msgstr "Неверный формат JSON"
|
||||
|
||||
@ -479,6 +560,9 @@ msgstr "Неверный URL VMess: должен начинаться с vmess:/
|
||||
msgid "IP address 0.0.0.0 is not allowed"
|
||||
msgstr "IP-адрес 0.0.0.0 не допускается"
|
||||
|
||||
msgid "IPv6 CIDR must be between 0 and 128"
|
||||
msgstr "IPv6 CIDR должен быть от 0 до 128"
|
||||
|
||||
msgid "Issues detected"
|
||||
msgstr "Обнаружены проблемы"
|
||||
|
||||
@ -488,9 +572,21 @@ msgstr "Оставлять только серверы подписки, имя
|
||||
msgid "Latest"
|
||||
msgstr "Последняя"
|
||||
|
||||
msgid "Latest version is installed"
|
||||
msgstr "Установлена последняя версия"
|
||||
|
||||
msgid "Line"
|
||||
msgstr "Строка"
|
||||
|
||||
msgid "List Update Frequency"
|
||||
msgstr "Частота обновления списков"
|
||||
|
||||
msgid "List update schedule, download routing, and routing exclusions"
|
||||
msgstr "Расписание обновления списков, маршрутизация загрузок и исключения из маршрутизации"
|
||||
|
||||
msgid "Lists & Updates"
|
||||
msgstr "Списки и обновления"
|
||||
|
||||
msgid "Local Domain Lists"
|
||||
msgstr "Локальные списки доменов"
|
||||
|
||||
@ -503,9 +599,15 @@ msgstr "Уровень логов"
|
||||
msgid "Main DNS"
|
||||
msgstr "Основной DNS"
|
||||
|
||||
msgid "Main DNS via outbound"
|
||||
msgstr "Основной DNS через outbound"
|
||||
|
||||
msgid "Memory Usage"
|
||||
msgstr "Использование памяти"
|
||||
|
||||
msgid "Mixed proxy and DNS resolution tuning"
|
||||
msgstr "Настройка смешанного прокси и разрешения DNS"
|
||||
|
||||
msgid "Mixed Proxy Port"
|
||||
msgstr "Порт смешанного прокси"
|
||||
|
||||
@ -516,13 +618,19 @@ msgid "Must be a number in the range of 50 - 1000"
|
||||
msgstr "Должно быть числом от 50 до 1000"
|
||||
|
||||
msgid "NetShift"
|
||||
msgstr ""
|
||||
msgstr "NetShift"
|
||||
|
||||
msgid "NetShift Settings"
|
||||
msgstr ""
|
||||
msgstr "Настройки NetShift"
|
||||
|
||||
msgid "NetShift updated, version:"
|
||||
msgstr "NetShift обновлён, версия:"
|
||||
|
||||
msgid "NetShift will not modify your DHCP configuration"
|
||||
msgstr ""
|
||||
msgstr "NetShift не будет изменять вашу конфигурацию DHCP"
|
||||
|
||||
msgid "Network"
|
||||
msgstr "Сеть"
|
||||
|
||||
msgid "Network Interface"
|
||||
msgstr "Сетевой интерфейс"
|
||||
@ -533,12 +641,24 @@ msgstr "Другие правила маркировки не найдены"
|
||||
msgid "Not implement yet"
|
||||
msgstr "Ещё не реализовано"
|
||||
|
||||
msgid "Not installed"
|
||||
msgstr "Не установлено"
|
||||
|
||||
msgid "Not responding"
|
||||
msgstr "Не отвечает"
|
||||
|
||||
msgid "Not running"
|
||||
msgstr "Не запущено"
|
||||
|
||||
msgid "Number of leading characters of each proxy name to group by."
|
||||
msgstr "Количество начальных символов имени каждого прокси для группировки."
|
||||
|
||||
msgid "Off"
|
||||
msgstr "Выключено"
|
||||
|
||||
msgid "Only one section can be global at a time."
|
||||
msgstr "Только одна секция может быть глобальной одновременно."
|
||||
|
||||
msgid "Operation timed out"
|
||||
msgstr "Время ожидания истекло"
|
||||
|
||||
@ -569,6 +689,12 @@ msgstr "Путь должен заканчиваться на cache.db"
|
||||
msgid "Pending"
|
||||
msgstr "Ожидает запуска"
|
||||
|
||||
msgid "Prefix length"
|
||||
msgstr "Длина префикса"
|
||||
|
||||
msgid "Protocol toggles, file paths and logging. Block DoH only after switching upstream DNS to UDP or DoT."
|
||||
msgstr "Переключатели протоколов, пути к файлам и журналирование. Включайте блокировку DoH только после переключения вышестоящего DNS на UDP или DoT."
|
||||
|
||||
msgid "Proxy Configuration URL"
|
||||
msgstr "URL конфигурации прокси"
|
||||
|
||||
@ -591,7 +717,13 @@ msgid "Resolve real IP for routing"
|
||||
msgstr "Разрешение реальных IP-адресов"
|
||||
|
||||
msgid "Restart NetShift"
|
||||
msgstr ""
|
||||
msgstr "Перезапустить NetShift"
|
||||
|
||||
msgid "Route all unmatched traffic through this section's outbound."
|
||||
msgstr "Направлять весь несовпавший трафик через outbound этой секции."
|
||||
|
||||
msgid "Route main DNS through proxy/VPN"
|
||||
msgstr "Основной DNS через прокси/VPN"
|
||||
|
||||
msgid "Router DNS is not routed through sing-box"
|
||||
msgstr "DNS роутера не проходит через sing-box"
|
||||
@ -599,6 +731,9 @@ msgstr "DNS роутера не проходит через sing-box"
|
||||
msgid "Router DNS is routed through sing-box"
|
||||
msgstr "DNS роутера проходит через sing-box"
|
||||
|
||||
msgid "Routing"
|
||||
msgstr "Маршрутизация"
|
||||
|
||||
msgid "Routing Excluded IPs"
|
||||
msgstr "Исключённые из маршрутизации IP-адреса"
|
||||
|
||||
@ -608,9 +743,6 @@ msgstr "Счётчики правил mangle"
|
||||
msgid "Rules mangle exist"
|
||||
msgstr "Правила mangle существуют"
|
||||
|
||||
msgid "Rules mangle output counters"
|
||||
msgstr "Счётчики правил mangle output"
|
||||
|
||||
msgid "Rules mangle output exist"
|
||||
msgstr "Правила mangle output существуют"
|
||||
|
||||
@ -662,12 +794,6 @@ msgstr "Выберите путь к файлу конфигурации sing-bo
|
||||
msgid "Select the DNS protocol type for the domain resolver"
|
||||
msgstr "Выберите тип протокола DNS для резолвера доменов"
|
||||
|
||||
msgid "Select the list type for adding custom domains"
|
||||
msgstr "Выберите тип списка для добавления пользовательских доменов"
|
||||
|
||||
msgid "Select the list type for adding custom subnets"
|
||||
msgstr "Выберите тип списка для добавления пользовательских подсетей"
|
||||
|
||||
msgid "Select the log level for sing-box"
|
||||
msgstr "Выберите уровень логов для sing-box"
|
||||
|
||||
@ -683,9 +809,21 @@ msgstr "Выберите WAN интерфейсы для мониторинга"
|
||||
msgid "Selector"
|
||||
msgstr "Selector"
|
||||
|
||||
msgid "Selector (text list)"
|
||||
msgstr "Selector (текстовый список)"
|
||||
|
||||
msgid "Selector Proxy Links"
|
||||
msgstr "Ссылки прокси для Selector"
|
||||
|
||||
msgid "Selector Proxy Links (one per line)"
|
||||
msgstr "Прокси-ссылки Selector (по одной в строке)"
|
||||
|
||||
msgid "Self-update failed"
|
||||
msgstr "Не удалось обновить"
|
||||
|
||||
msgid "Send upstream DNS queries through a proxy/VPN outbound instead of directly. Bootstrap DNS always stays direct."
|
||||
msgstr "Отправлять запросы к основному DNS через outbound прокси/VPN вместо прямого подключения. Bootstrap DNS всегда остаётся прямым."
|
||||
|
||||
msgid "Services info"
|
||||
msgstr "Информация о сервисах"
|
||||
|
||||
@ -719,6 +857,9 @@ msgstr "Сервис sing-box существует"
|
||||
msgid "Sing-box version is compatible (newer than 1.12.4)"
|
||||
msgstr "Версия Sing-box совместима (новее 1.12.4)"
|
||||
|
||||
msgid "Source and output interfaces, and Bad WAN interface monitoring"
|
||||
msgstr "Входящий и исходящий интерфейсы, а также мониторинг интерфейсов Bad WAN"
|
||||
|
||||
msgid "Source Network Interface"
|
||||
msgstr "Сетевой интерфейс источника"
|
||||
|
||||
@ -738,23 +879,41 @@ msgid "Specify the path to the list file located on the router filesystem"
|
||||
msgstr "Укажите путь к файлу списка, расположенному в файловой системе маршрутизатора."
|
||||
|
||||
msgid "Start NetShift"
|
||||
msgstr ""
|
||||
msgstr "Запустить NetShift"
|
||||
|
||||
msgid "Stop NetShift"
|
||||
msgstr ""
|
||||
msgstr "Остановить NetShift"
|
||||
|
||||
msgid "Subscription"
|
||||
msgstr ""
|
||||
msgstr "Подписка"
|
||||
|
||||
msgid "Subscription cache cleared and re-downloaded"
|
||||
msgstr "Кеш подписок очищен и загружен заново"
|
||||
|
||||
msgid "Subscription feeds, server filters and URLTest tuning"
|
||||
msgstr "Источники подписок, фильтры серверов и настройка URLTest"
|
||||
|
||||
msgid "Subscription format"
|
||||
msgstr "Формат подписки"
|
||||
|
||||
msgid "Subscription grouping"
|
||||
msgstr "Группировка подписки"
|
||||
|
||||
msgid "Subscription Update Interval"
|
||||
msgstr ""
|
||||
msgstr "Интервал обновления подписки"
|
||||
|
||||
msgid "Subscription URL"
|
||||
msgstr ""
|
||||
msgid "Subscription URLs"
|
||||
msgstr "URL подписок"
|
||||
|
||||
msgid "Successfully copied!"
|
||||
msgstr "Успешно скопировано!"
|
||||
|
||||
msgid "Switch to extended"
|
||||
msgstr "Переключить на extended"
|
||||
|
||||
msgid "Switch to stable"
|
||||
msgstr "Переключить на stable"
|
||||
|
||||
msgid "Switching sing-box core, this may take a few minutes…"
|
||||
msgstr "Переключение ядра sing-box, это может занять несколько минут…"
|
||||
|
||||
@ -785,6 +944,9 @@ msgstr "Максимально допустимая разница во врем
|
||||
msgid "The URL used to test server connectivity"
|
||||
msgstr "URL-адрес, используемый для проверки подключения к серверу"
|
||||
|
||||
msgid "This is a security trade-off: an attacker could intercept the fetch."
|
||||
msgstr "Это компромисс в безопасности: злоумышленник может перехватить загрузку."
|
||||
|
||||
msgid "Time in seconds for DNS record caching (default: 60)"
|
||||
msgstr "Время в секундах для кэширования DNS записей (по умолчанию: 60)"
|
||||
|
||||
@ -815,9 +977,24 @@ msgstr "неизвестно"
|
||||
msgid "Unknown error"
|
||||
msgstr "Неизвестная ошибка"
|
||||
|
||||
msgid "Update"
|
||||
msgstr "Обновить"
|
||||
|
||||
msgid "Update is available"
|
||||
msgstr "Доступно обновление"
|
||||
|
||||
msgid "Update NetShift"
|
||||
msgstr "Обновить NetShift"
|
||||
|
||||
msgid "Updating NetShift, this may take a few minutes; the page will reload…"
|
||||
msgstr "Обновление NetShift, это может занять несколько минут; страница перезагрузится…"
|
||||
|
||||
msgid "Uplink"
|
||||
msgstr "Исходящий"
|
||||
|
||||
msgid "Upstream and bootstrap DNS resolvers, and optional DNS-over-proxy"
|
||||
msgstr "Вышестоящий и начальный (bootstrap) DNS-резолверы и опциональный DNS через прокси"
|
||||
|
||||
msgid "URL must start with vless://, vmess://, ss://, trojan://, socks4/5://, or hysteria2://hy2://"
|
||||
msgstr "URL должен начинаться с vless://, vmess://, ss://, trojan://, socks4/5:// или hysteria2:// hy2://"
|
||||
|
||||
@ -827,20 +1004,32 @@ msgstr "URL должен использовать один из следующи
|
||||
msgid "URLTest"
|
||||
msgstr "URLTest"
|
||||
|
||||
msgid "URLTest (text list)"
|
||||
msgstr "URLTest (текстовый список)"
|
||||
|
||||
msgid "URLTest Check Interval"
|
||||
msgstr "Интервал проверки URLTest"
|
||||
|
||||
msgid "URLTest Proxy Links"
|
||||
msgstr "Ссылки прокси для URLTest"
|
||||
|
||||
msgid "URLTest Proxy Links (one per line)"
|
||||
msgstr "Прокси-ссылки URLTest (по одной в строке)"
|
||||
|
||||
msgid "URLTest Testing URL"
|
||||
msgstr "URLTest ссылка для проверки"
|
||||
|
||||
msgid "URLTest Tolerance"
|
||||
msgstr "URLTest допустимое отклонение"
|
||||
|
||||
msgid "User Domain List Type"
|
||||
msgstr "Тип пользовательского списка доменов"
|
||||
msgid "Use only for IP-host panels that serve an invalid or self-signed certificate."
|
||||
msgstr "Используйте только для панелей с IP-адресом, у которых недействительный или самоподписанный сертификат."
|
||||
|
||||
msgid "Use this only when the router has working IPv6 connectivity."
|
||||
msgstr "Используйте это только если на роутере есть рабочее подключение по IPv6."
|
||||
|
||||
msgid "Use with Exclusion sections to route specific domains directly."
|
||||
msgstr "Используйте вместе с секциями исключений для прямой маршрутизации определённых доменов."
|
||||
|
||||
msgid "User Domains"
|
||||
msgstr "Пользовательские домены"
|
||||
@ -848,9 +1037,6 @@ msgstr "Пользовательские домены"
|
||||
msgid "User Domains List"
|
||||
msgstr "Список пользовательских доменов"
|
||||
|
||||
msgid "User Subnet List Type"
|
||||
msgstr "Тип пользовательского списка подсетей"
|
||||
|
||||
msgid "User Subnets"
|
||||
msgstr "Пользовательские подсети"
|
||||
|
||||
@ -863,6 +1049,9 @@ msgstr "Валидно"
|
||||
msgid "Validation errors:"
|
||||
msgstr "Ошибки валидации:"
|
||||
|
||||
msgid "Version"
|
||||
msgstr "Версия"
|
||||
|
||||
msgid "View logs"
|
||||
msgstr "Посмотреть логи"
|
||||
|
||||
@ -872,14 +1061,32 @@ msgstr "Перейти в wiki"
|
||||
msgid "vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links"
|
||||
msgstr "ссылки vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2://"
|
||||
|
||||
msgid "vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// links — one per line"
|
||||
msgstr "Ссылки vless://, vmess://, ss://, trojan://, socks4/5://, hy2/hysteria2:// — по одной в строке"
|
||||
|
||||
msgid "Warning: %s cannot be used together with %s. Previous selections have been removed."
|
||||
msgstr "Предупреждение: %s нельзя использовать вместе с %s. Предыдущие варианты были удалены."
|
||||
|
||||
msgid "Warning: Russia inside can only be used with %s. %s already in Russia inside and have been removed from selection."
|
||||
msgstr "Предупреждение: Russia inside может быть использован только с %s. %s уже есть в Russia inside и будет удален из выбранных."
|
||||
|
||||
msgid "When enabled, traffic not matching any other section's lists will go through this proxy."
|
||||
msgstr "Когда включено, трафик, не совпадающий со списками других секций, будет идти через этот прокси."
|
||||
|
||||
msgid "Which proxy/VPN section carries the DNS. Leave unset to use the first configured outbound."
|
||||
msgstr "Какая секция прокси/VPN обслуживает DNS. Оставьте пустым, чтобы использовать первый настроенный outbound."
|
||||
|
||||
msgid "Which subscription format (client) to fetch first. Auto uses the default order. Choose Xray JSON (Happ) when your panel only exposes some nodes (e.g. xhttp) under a Happ-like client, or Sing-box to prefer the sing-box format."
|
||||
msgstr "Какой формат подписки (клиент) запрашивать первым. «Авто» использует порядок по умолчанию. Выберите «Xray JSON (Happ)», если ваша панель отдаёт некоторые узлы (например, xhttp) только под клиентом вроде Happ, или «Sing-box», чтобы предпочесть формат sing-box."
|
||||
|
||||
msgid "Xray JSON (Happ)"
|
||||
msgstr "Xray JSON (Happ)"
|
||||
|
||||
msgid "YACD Secret Key"
|
||||
msgstr "Секретный ключ YACD"
|
||||
|
||||
msgid "YACD web dashboard access and remote-access protection"
|
||||
msgstr "Доступ к веб-панели YACD и защита удалённого доступа"
|
||||
|
||||
msgid "You can select Output Network Interface, by default autodetect"
|
||||
msgstr "Вы можете выбрать выходной сетевой интерфейс, по умолчанию он определяется автоматически."
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=netshift
|
||||
|
||||
PKG_VERSION := $(if $(NETSHIFT_VERSION),$(NETSHIFT_VERSION),0.$(shell date +%d%m%Y))
|
||||
PKG_VERSION := $(if $(NETSHIFT_VERSION),$(NETSHIFT_VERSION),0.9.6)
|
||||
|
||||
PKG_RELEASE:=1
|
||||
|
||||
|
||||
@ -13,12 +13,16 @@ config settings 'settings'
|
||||
option disable_quic '0'
|
||||
option update_interval '1d'
|
||||
option download_lists_via_proxy '0'
|
||||
#option dns_via_outbound '0'
|
||||
#option dns_outbound_section 'main'
|
||||
option dont_touch_dhcp '0'
|
||||
option config_path '/etc/sing-box/config.json'
|
||||
option cache_path '/tmp/sing-box/cache.db'
|
||||
option log_level 'warn'
|
||||
option exclude_ntp '0'
|
||||
option shutdown_correctly '0'
|
||||
option block_doh '0'
|
||||
option enable_ipv6 '0'
|
||||
#list routing_excluded_ips '192.168.1.3'
|
||||
|
||||
config section 'main'
|
||||
@ -26,6 +30,7 @@ config section 'main'
|
||||
option proxy_config_type 'url'
|
||||
option proxy_string ''
|
||||
option enable_udp_over_tcp '0'
|
||||
option global_proxy '0'
|
||||
list community_lists 'russia_inside'
|
||||
#option user_domain_list_type 'dynamic'
|
||||
#list user_domains '2ip.ru'
|
||||
@ -42,8 +47,35 @@ config section 'main'
|
||||
#config section 'subscription_example'
|
||||
# option connection_type 'proxy'
|
||||
# option proxy_config_type 'subscription'
|
||||
# # subscription_url may be a single option (legacy, still supported) or a
|
||||
# # UCI list of one or more feed URLs. With multiple URLs every feed is
|
||||
# # downloaded/validated independently and all nodes are MERGED into one
|
||||
# # selector/urltest group (same-named nodes auto-deduped). A dead feed
|
||||
# # never breaks the others; the section is blocked only if ALL feeds fail.
|
||||
# option subscription_url 'https://example.com/api/sub'
|
||||
# #list subscription_url 'https://example.com/api/sub'
|
||||
# #list subscription_url 'https://another-panel.example/api/sub'
|
||||
# # Allow insecure TLS for the subscription fetch (default 0). Set to 1 to
|
||||
# # add wget --no-check-certificate for IP-host panels whose HTTPS cert is
|
||||
# # invalid/self-signed/missing-SAN. Disables certificate verification.
|
||||
# #option subscription_insecure '0'
|
||||
# # Force a specific client User-Agent for the fetch. When set, ONLY this
|
||||
# # UA is used (no probing). Leave unset to auto-probe well-known clients.
|
||||
# #option subscription_user_agent 'Happ'
|
||||
# # Preferred body FORMAT to probe first (auto|xray|singbox, default auto).
|
||||
# # Panels often serve a different config per User-Agent. 'xray' tries the
|
||||
# # Xray-JSON UAs (Happ/v2rayN) FIRST to recover xhttp nodes a panel only
|
||||
# # exposes in its Xray JSON; 'singbox' keeps the singbox/<ver> UA first;
|
||||
# # 'auto' preserves the default order. Ignored when subscription_user_agent
|
||||
# # is set (an explicit UA always wins).
|
||||
# #option subscription_format_preference 'auto'
|
||||
# option subscription_update_interval '1h'
|
||||
# # Node grouping: off | country | prefix. 'country' clusters by leading
|
||||
# # flag emoji; 'prefix' clusters by the first N codepoints of each node
|
||||
# # name (N = subscription_group_prefix_len). subscription_group_mode
|
||||
# # outranks the legacy subscription_group_by_countries boolean below.
|
||||
# #option subscription_group_mode 'off'
|
||||
# #option subscription_group_prefix_len '2'
|
||||
# #option subscription_group_by_countries '0'
|
||||
# #option urltest_check_interval '3m'
|
||||
# #option urltest_tolerance '50'
|
||||
@ -54,5 +86,28 @@ config section 'main'
|
||||
# #list subscription_filter_include_keywords 'grpc'
|
||||
# # Keyword blacklist: drop any node whose display name contains any of
|
||||
# # these (OR). Empty/absent = no exclusion.
|
||||
# #list subscription_filter_exclude_keywords 'expired'
|
||||
# list community_lists 'russia_inside'
|
||||
# #list subscription_filter_exclude_keywords 'expired'
|
||||
# list community_lists 'russia_inside'
|
||||
|
||||
# Text-list Selector / URLTest: paste proxy links into a single multi-line
|
||||
# textarea option (one link per line) instead of one DynamicList item each. The
|
||||
# supported links (vless/vmess/ss/trojan/hysteria2/socks) are built into a
|
||||
# Selector ('selector_text') or a URLTest + selector ('urltest_text'); blank
|
||||
# lines and unsupported schemes are skipped. The value is a scalar newline-
|
||||
# delimited blob — NOT a UCI list.
|
||||
#config section 'selector_text_example'
|
||||
# option connection_type 'proxy'
|
||||
# option proxy_config_type 'selector_text'
|
||||
# # one link per line in a single multi-line option value
|
||||
# option selector_proxy_links_text 'vless://example-node-1
|
||||
#vless://example-node-2'
|
||||
|
||||
#config section 'urltest_text_example'
|
||||
# option connection_type 'proxy'
|
||||
# option proxy_config_type 'urltest_text'
|
||||
# # one link per line in a single multi-line option value
|
||||
# option urltest_proxy_links_text 'vless://example-node-1
|
||||
#vless://example-node-2'
|
||||
# #option urltest_check_interval '3m'
|
||||
# #option urltest_tolerance '50'
|
||||
# #option urltest_testing_url 'https://www.gstatic.com/generate_204'
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -14,6 +14,12 @@ TMP_RULESET_FOLDER="$TMP_SING_BOX_FOLDER/rulesets"
|
||||
TMP_SUBSCRIPTION_FOLDER="$TMP_SING_BOX_FOLDER/subscriptions"
|
||||
SUBSCRIPTION_CACHE_FOLDER="$NETSHIFT_STATE_DIR/subscriptions"
|
||||
TMP_SUBSCRIPTION_DOWNLOAD_FOLDER="$TMP_SING_BOX_FOLDER/subscription-downloads"
|
||||
# A section may list MULTIPLE subscription_url feeds. At config generation the
|
||||
# usable per-URL caches are concatenated into one merged subscription JSON in
|
||||
# this folder, then passed ONCE through the facade (keyword filter + global
|
||||
# tag-dedup + sing-box check bisection). Per-feed cache files are keyed
|
||||
# "${section}.<md5(url)>.<ext>" under SUBSCRIPTION_CACHE_FOLDER.
|
||||
TMP_SUBSCRIPTION_MERGE_FOLDER="$TMP_SING_BOX_FOLDER/subscription-merge"
|
||||
# Subscription User-Agent fallback. Many panels return a DIFFERENT body format
|
||||
# depending on the client User-Agent (sing-box JSON vs base64 URI list vs Clash
|
||||
# vs Xray JSON, or an HTML/403 stub for unknown clients). When no User-Agent is
|
||||
@ -22,15 +28,39 @@ TMP_SUBSCRIPTION_DOWNLOAD_FOLDER="$TMP_SING_BOX_FOLDER/subscription-downloads"
|
||||
# "singbox/<version>" candidate is prepended at runtime (it depends on the
|
||||
# installed sing-box). Order matters: most-likely-to-work first.
|
||||
SUBSCRIPTION_USER_AGENT_CANDIDATES="v2rayN Happ Hiddify Clash.Meta ClashMetaForAndroid"
|
||||
# Versioned client UAs that well-known panels answer with an Xray JSON body
|
||||
# (which carries xhttp/transport nodes the default sing-box JSON may omit). Used
|
||||
# by build_subscription_user_agent_candidates when a section's
|
||||
# subscription_format_preference is "xray": these UAs are probed FIRST so an
|
||||
# Xray-JSON feed is recovered before a sing-box JSON under the default UA wins.
|
||||
# Panels commonly gate their Xray branch on a "<client>/<version>" UA shape, so
|
||||
# these are VERSIONED (a bare/version-less UA can be rejected, e.g. with a 502).
|
||||
# Order matters: a versioned Happ is first (empirically yields the Xray-JSON
|
||||
# array body), then versioned v2rayN/v2rayNG forms as panel-agnostic fallbacks.
|
||||
SUBSCRIPTION_USER_AGENT_XRAY_CANDIDATES="Happ/1.0.0 v2rayN/7.0.0 v2rayNG/1.9.0"
|
||||
CLOUDFLARE_OCTETS="8.47 162.159 188.114" # Endpoints https://github.com/ampetelin/warp-endpoint-checker
|
||||
JQ_REQUIRED_VERSION="1.7.1"
|
||||
COREUTILS_BASE64_REQUIRED_VERSION="9.7"
|
||||
RT_TABLE_NAME="netshift"
|
||||
# Pidfile of the detached sing-box health monitor (task-035). The monitor is a
|
||||
# long-lived `while true` loop launched via setsid with the procd lock fd (1000)
|
||||
# closed, so it does NOT hold the procd service lock and consecutive
|
||||
# reload/restart never block on flock. The monitor writes its own pid here.
|
||||
MONITOR_PIDFILE="/var/run/netshift_monitor.pid"
|
||||
|
||||
## nft
|
||||
NFT_TABLE_NAME="NetShiftTable"
|
||||
NFT_LOCALV4_SET_NAME="localv4"
|
||||
NFT_LOCALV6_SET_NAME="localv6"
|
||||
# Destination set holding the UNION of every proxy section's proxied IPv4
|
||||
# subnets (user/local/remote/community subnet lists). Used by the prerouting
|
||||
# `mangle` chain to mark ONLY proxied destinations into the tproxy path, so
|
||||
# non-proxied traffic (e.g. a torrent to a random direct IP) never enters
|
||||
# sing-box (task-034). The per-section outbound is still selected by sing-box
|
||||
# route rules — nft only decides enter-or-not, so a single union set is enough.
|
||||
NFT_COMMON_SET_NAME="netshift_subnets"
|
||||
# IPv6 mirror of NFT_COMMON_SET_NAME (only created/used when IPv6 is enabled).
|
||||
NFT_COMMON_SET_NAME_V6="netshift_subnets_v6"
|
||||
NFT_DISCORD_SET_NAME="netshift_discord_subnets"
|
||||
NFT_INTERFACE_SET_NAME="interfaces"
|
||||
NFT_FAKEIP_MARK="0x00100000"
|
||||
@ -38,6 +68,11 @@ NFT_OUTBOUND_MARK="0x00200000"
|
||||
|
||||
## sing-box
|
||||
SB_REQUIRED_VERSION="1.12.0"
|
||||
# Monitoring
|
||||
MONITOR_CHECK_INTERVAL=10
|
||||
MONITOR_MAX_CRASHES=5
|
||||
MONITOR_BACKOFF_BASE=10
|
||||
MONITOR_BACKOFF_MAX=300
|
||||
# Core-switch connectivity self-heal (task-009). Hosts probed before a core
|
||||
# swap, depending on direction: the stable (stock) install pulls from the
|
||||
# OpenWrt package feeds, the extended install pulls from the GitHub API.
|
||||
@ -53,10 +88,35 @@ UPDATES_RESOLV_BACKUP="/tmp/netshift-resolv.conf.bak"
|
||||
# locations; tests override them.
|
||||
UPDATES_SING_BOX_BIN="/usr/bin/sing-box"
|
||||
UPDATES_LIBCRONET_LIB="/usr/lib/libcronet.so"
|
||||
# Component Manager — NetShift self-update (task-017). The GitHub latest-release
|
||||
# API for NetShift itself (same endpoint install.sh and get_system_info use);
|
||||
# the self-update worker downloads the release .ipk/.apk assets from it.
|
||||
NETSHIFT_RELEASE_API_URL="https://uralgit.ru/api/v1/repos/ural/netshift/releases/latest"
|
||||
# uralgit.ru FRONTEND redirect path (NOT the rate-limited api.github.com)
|
||||
# for the NetShift repo. /releases/latest 303-redirects to /releases/tag/<tag>
|
||||
# (resolve with curl -w '%{redirect_url}' — no API hit, not subject to the
|
||||
# 60/hour/IP anonymous API limit); /releases/download/<tag>/<asset> for direct
|
||||
# asset download. Primary path for version-check + self-update;
|
||||
# NETSHIFT_RELEASE_API_URL stays as the graceful fallback. Repo slug lives here
|
||||
# only — do not hardcode it elsewhere.
|
||||
NETSHIFT_REPO_RELEASES_LATEST_URL="https://uralgit.ru/ural/netshift/releases/latest"
|
||||
NETSHIFT_REPO_RELEASES_DOWNLOAD_BASE="https://uralgit.ru/ural/netshift/releases/download"
|
||||
# tmpfs scratch dir for the self-update download (release packages) — RAM, never
|
||||
# the tiny overlay; reaped on success and on reboot.
|
||||
UPDATES_NETSHIFT_DOWNLOAD_DIR="/tmp/netshift/selfupdate"
|
||||
# tmpfs backup of /etc/config/netshift taken before the self-update package
|
||||
# install (conffiles normally preserve it; this is the defensive belt).
|
||||
UPDATES_NETSHIFT_CONFIG_BACKUP="/tmp/netshift/config.bak"
|
||||
# NetShift package names handled by the self-update (in install order). The RU
|
||||
# i18n package is upgraded ONLY if already installed (never newly installed).
|
||||
UPDATES_NETSHIFT_PKG_CORE="netshift"
|
||||
UPDATES_NETSHIFT_PKG_LUCI="luci-app-netshift"
|
||||
UPDATES_NETSHIFT_PKG_I18N_RU="luci-i18n-netshift-ru"
|
||||
# DNS
|
||||
SB_DNS_SERVER_TAG="dns-server"
|
||||
SB_FAKEIP_DNS_SERVER_TAG="fakeip-server"
|
||||
SB_FAKEIP_INET4_RANGE="198.18.0.0/15"
|
||||
SB_FAKEIP_INET6_RANGE="fd00:ec3a::/32"
|
||||
SB_BOOTSTRAP_SERVER_TAG="bootstrap-dns-server"
|
||||
SB_FAKEIP_DNS_RULE_TAG="fakeip-dns-rule-tag"
|
||||
SB_INVERT_FAKEIP_DNS_RULE_TAG="invert-fakeip-dns-rule-tag"
|
||||
@ -64,23 +124,41 @@ SB_INVERT_FAKEIP_DNS_RULE_TAG="invert-fakeip-dns-rule-tag"
|
||||
SB_TPROXY_INBOUND_TAG="tproxy-in"
|
||||
SB_TPROXY_INBOUND_ADDRESS="127.0.0.1"
|
||||
SB_TPROXY_INBOUND_PORT=1602
|
||||
SB_TPROXY_INBOUND_ADDRESS_V6="::1"
|
||||
SB_TPROXY_INBOUND_PORT_V6=1603
|
||||
SB_DNS_INBOUND_TAG="dns-in"
|
||||
SB_DNS_INBOUND_ADDRESS="127.0.0.42"
|
||||
SB_DNS_INBOUND_PORT=53
|
||||
SB_DNS_INBOUND_ADDRESS_V6="::1"
|
||||
SB_DNS_INBOUND_PORT_V6=5354
|
||||
SB_SERVICE_MIXED_INBOUND_TAG="service-mixed-in"
|
||||
SB_SERVICE_MIXED_INBOUND_ADDRESS="127.0.0.1"
|
||||
SB_SERVICE_MIXED_INBOUND_PORT=4534
|
||||
# Outbounds
|
||||
SB_DIRECT_OUTBOUND_TAG="direct-out"
|
||||
# Subscription grouping (task-044). Default codepoint count for prefix-mode
|
||||
# grouping when subscription_group_prefix_len is unset/invalid.
|
||||
SUBSCRIPTION_GROUP_DEFAULT_PREFIX_LEN=2
|
||||
# Subscription grouping (task-050). Tag/label for the top-level "Fastest"
|
||||
# urltest that probes ACROSS the per-group urltests (a urltest of urltests)
|
||||
# when grouping is on. Valid UTF-8 emoji + English; deliberately distinct from
|
||||
# a per-group "<flag> Fastest" tag so the cross-group auto choice is tellable
|
||||
# apart in the dashboard. Single source for the tag (keep this file UTF-8).
|
||||
SB_SUBSCRIPTION_FASTEST_GROUP_TAG="⚡ Fastest"
|
||||
# Route
|
||||
SB_REJECT_RULE_TAG="reject-rule-tag"
|
||||
SB_EXCLUSION_RULE_TAG="exclusion-rule-tag"
|
||||
SB_DOH_BLOCK_RULE_TAG="doh-block-rule-tag"
|
||||
# Experimental
|
||||
SB_CLASH_API_CONTROLLER_PORT=9090
|
||||
|
||||
## DoH blocking
|
||||
DOH_BLOCK_IPV4_CIDRS="1.1.1.1/32 1.0.0.1/32 8.8.8.8/32 8.8.4.4/32 9.9.9.9/32 9.9.9.11/32 149.112.112.112/32 208.67.222.222/32 208.67.220.220/32 94.140.14.14/32 94.140.15.15/32 77.88.8.8/32 77.88.8.1/32"
|
||||
DOH_BLOCK_IPV6_CIDRS="2606:4700:4700::1111/128 2606:4700:4700::1001/128 2001:4860:4860::8888/128 2001:4860:4860::8844/128 2620:fe::fe/128 2620:fe::9/128 2620:119:35::35/128 2620:119:53::53/128 2a10:50c0::ad1:ff/128 2a10:50c0::ad2:ff/128 2a02:6b8::feed:0ff/128 2a02:6b8:0:1::feed:0ff/128"
|
||||
|
||||
## Lists
|
||||
GITHUB_RAW_URL="https://raw.githubusercontent.com/itdoginfo/allow-domains/main"
|
||||
SRS_MAIN_URL="https://github.com/itdoginfo/allow-domains/releases/latest/download"
|
||||
GITHUB_RAW_URL="https://uralgit.ru/ural/allow-domains/raw/branch/main"
|
||||
SRS_MAIN_URL="https://uralgit.ru/ural/allow-domains/releases/latest/download"
|
||||
SUBNETS_TWITTER="${GITHUB_RAW_URL}/Subnets/IPv4/twitter.lst"
|
||||
SUBNETS_META="${GITHUB_RAW_URL}/Subnets/IPv4/meta.lst"
|
||||
SUBNETS_DISCORD="${GITHUB_RAW_URL}/Subnets/IPv4/discord.lst"
|
||||
|
||||
@ -147,7 +147,11 @@ url_get_host() {
|
||||
url="${url#*@}"
|
||||
url="${url%%[/?#]*}"
|
||||
|
||||
echo "${url%%:*}"
|
||||
case "$url" in
|
||||
\[*\]) echo "${url#\[}" | sed 's/\]$//' ;;
|
||||
\[*\]*) echo "${url#\[}" | sed 's/\].*//' ;;
|
||||
*) echo "${url%%:*}" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Extracts the port number from a URL
|
||||
@ -159,6 +163,7 @@ url_get_port() {
|
||||
url="${url%%[/?#]*}"
|
||||
|
||||
case "$url" in
|
||||
\[*\]:*) echo "${url##*]:}" ;;
|
||||
*:*) echo "${url#*:}" ;;
|
||||
*) echo "" ;;
|
||||
esac
|
||||
@ -567,6 +572,58 @@ convert_crlf_to_lf() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Best-effort, in-place gzip decompression of a downloaded subscription body.
|
||||
#
|
||||
# Some panels unconditionally return a gzip-compressed HTTP body (busybox wget
|
||||
# does NOT transparently decompress and we send no Accept-Encoding), so the raw
|
||||
# bytes are binary and every downstream consumer (validate/normalize) chokes.
|
||||
# This decompresses once at download time so all consumers see text.
|
||||
#
|
||||
# Detection is attempt-based (no od/hexdump/xxd, none of which exist on device):
|
||||
# we try `gzip -dc` (busybox built-in) into a temp file and accept the result
|
||||
# ONLY if (a) gzip returned 0, (b) the result is non-empty, and (c) the result
|
||||
# is NUL-free. gzip -dc on plain-text input returns rc!=0 cleanly, so a
|
||||
# plain-text body is left byte-for-byte untouched; this can never corrupt text.
|
||||
# Modeled on convert_crlf_to_lf: mktemp -> transform -> mv on success / rm on
|
||||
# failure. Best-effort: always returns 0 (never aborts the caller).
|
||||
maybe_gunzip_subscription_file() {
|
||||
local filepath="$1"
|
||||
local tmpfile
|
||||
|
||||
[ -s "$filepath" ] || return 0
|
||||
|
||||
tmpfile=$(mktemp)
|
||||
if gzip -dc "$filepath" > "$tmpfile" 2>/dev/null &&
|
||||
[ -s "$tmpfile" ] &&
|
||||
! subscription_body_is_binary "$tmpfile"; then
|
||||
log "Decompressed gzip subscription body for '$filepath'" "debug"
|
||||
mv "$tmpfile" "$filepath"
|
||||
else
|
||||
rm -f "$tmpfile"
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# Returns 0 (true) if the file contains at least one NUL byte (i.e. it is
|
||||
# binary / undecodable, not text). Busybox-safe, no od/hexdump/xxd: `tr -d`
|
||||
# strips NUL bytes and we compare the resulting byte count to the original; a
|
||||
# difference means a NUL was present. All vars local.
|
||||
subscription_body_is_binary() {
|
||||
local filepath="$1"
|
||||
local raw_count stripped_count
|
||||
|
||||
[ -s "$filepath" ] || return 1
|
||||
|
||||
raw_count="$(wc -c < "$filepath" 2>/dev/null | tr -d ' ')"
|
||||
stripped_count="$(tr -d '\000' < "$filepath" 2>/dev/null | wc -c 2>/dev/null | tr -d ' ')"
|
||||
|
||||
[ -n "$raw_count" ] || raw_count=0
|
||||
[ -n "$stripped_count" ] || stripped_count=0
|
||||
|
||||
[ "$raw_count" != "$stripped_count" ]
|
||||
}
|
||||
|
||||
#######################################
|
||||
# Parses a whitespace-separated string, validates items as either domains
|
||||
# or IPv4 addresses/subnets, and returns a comma-separated string of valid items.
|
||||
@ -724,13 +781,24 @@ get_subscription_user_agent() {
|
||||
# Arguments:
|
||||
# $1 - configured User-Agent (empty for auto mode)
|
||||
# $2 - preferred User-Agent (e.g. the previously cached winner; tried early)
|
||||
# $3 - format preference: "auto" (default) | "xray" | "singbox". Reorders the
|
||||
# auto-mode candidates so the preferred FORMAT's UA is probed first; the
|
||||
# probe loop still keeps the first body that yields valid outbounds.
|
||||
# Behavior:
|
||||
# - configured non-empty: emit ONLY that value (respect the user's choice).
|
||||
# - auto: emit "singbox/<ver>", then the preferred one, then the whitelist
|
||||
# from constants (SUBSCRIPTION_USER_AGENT_CANDIDATES), skipping duplicates.
|
||||
# - configured non-empty: emit ONLY that value (respect the user's choice;
|
||||
# an explicit UA always outranks the format preference).
|
||||
# - auto/empty/unrecognised: emit "singbox/<ver>", then the preferred one,
|
||||
# then the whitelist (SUBSCRIPTION_USER_AGENT_CANDIDATES) — today's order.
|
||||
# - xray: emit the Xray-JSON UAs (SUBSCRIPTION_USER_AGENT_XRAY_CANDIDATES)
|
||||
# FIRST (outranking the cached winner + default), then "singbox/<ver>",
|
||||
# then the preferred one, then the rest of the whitelist.
|
||||
# - singbox: same as auto (singbox/<ver> first); the explicit name for the
|
||||
# current default ordering.
|
||||
# All orderings are de-duplicated with the newline "seen" set below.
|
||||
build_subscription_user_agent_candidates() {
|
||||
local configured_user_agent="${1:-}"
|
||||
local preferred_user_agent="${2:-}"
|
||||
local format_preference="${3:-}"
|
||||
local default_user_agent candidate seen
|
||||
|
||||
if [ -n "$configured_user_agent" ]; then
|
||||
@ -740,8 +808,21 @@ build_subscription_user_agent_candidates() {
|
||||
|
||||
default_user_agent="$(get_subscription_user_agent)"
|
||||
seen=""
|
||||
# shellcheck disable=SC2086 # word-splitting of the candidate list is intentional
|
||||
for candidate in "$default_user_agent" "$preferred_user_agent" $SUBSCRIPTION_USER_AGENT_CANDIDATES; do
|
||||
|
||||
# Order the auto-mode candidate stream by the requested format preference.
|
||||
# "xray" front-loads the Xray-JSON-yielding UAs (so they outrank the cached
|
||||
# winner and the default); "singbox"/"auto"/empty/unknown keep today's order
|
||||
# (default UA -> cached winner -> whitelist). Any unknown value falls through
|
||||
# to the default ordering (forward-compatible).
|
||||
if [ "$format_preference" = "xray" ]; then
|
||||
# shellcheck disable=SC2086 # word-splitting of the candidate lists is intentional
|
||||
set -- $SUBSCRIPTION_USER_AGENT_XRAY_CANDIDATES "$default_user_agent" "$preferred_user_agent" $SUBSCRIPTION_USER_AGENT_CANDIDATES
|
||||
else
|
||||
# shellcheck disable=SC2086 # word-splitting of the candidate list is intentional
|
||||
set -- "$default_user_agent" "$preferred_user_agent" $SUBSCRIPTION_USER_AGENT_CANDIDATES
|
||||
fi
|
||||
|
||||
for candidate in "$@"; do
|
||||
[ -n "$candidate" ] || continue
|
||||
# Skip a candidate already emitted. Wrap stored names in newlines so the
|
||||
# substring test matches whole entries only.
|
||||
@ -757,6 +838,43 @@ $candidate
|
||||
done
|
||||
}
|
||||
|
||||
# Runs a single wget subscription request with the shared client-mimicking
|
||||
# headers and an optional --no-check-certificate flag, so all branches of
|
||||
# download_subscription stay byte-identical.
|
||||
# Arguments:
|
||||
# $1 - cert flag ("" or "--no-check-certificate")
|
||||
# $2 - User-Agent header value
|
||||
# $3 - X-HWID header value
|
||||
# $4 - X-Device-Model header value
|
||||
# $5 - X-Ver-OS header value
|
||||
# $6 - output file path (passed to wget -O)
|
||||
# $7 - error file path (wget stderr is redirected here)
|
||||
# $8 - subscription URL
|
||||
# $9.. - leading wget flags (e.g. -4, -T, <timeout>)
|
||||
# Caller is responsible for exporting http_proxy/https_proxy when needed.
|
||||
_wget_subscription_request() {
|
||||
local cert_flag="$1"
|
||||
local req_user_agent="$2"
|
||||
local req_hwid="$3"
|
||||
local req_device_model="$4"
|
||||
local req_kernel_version="$5"
|
||||
local req_outfile="$6"
|
||||
local req_errfile="$7"
|
||||
local req_url="$8"
|
||||
shift 8
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
wget $cert_flag "$@" -O "$req_outfile" \
|
||||
--header "User-Agent: $req_user_agent" \
|
||||
--header "X-HWID: $req_hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $req_device_model" \
|
||||
--header "X-Ver-OS: $req_kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$req_url" 2>"$req_errfile"
|
||||
}
|
||||
|
||||
# Downloads a subscription body from the given URL with client-mimicking headers
|
||||
# Arguments:
|
||||
# $1 - subscription URL
|
||||
@ -766,6 +884,7 @@ $candidate
|
||||
# $5 - wait between retries (optional, default 2)
|
||||
# $6 - timeout seconds (optional, default 10)
|
||||
# $7 - User-Agent (optional; default "singbox/<version>")
|
||||
# $8 - insecure (optional, default 0; when 1 adds --no-check-certificate)
|
||||
download_subscription() {
|
||||
local url="$1"
|
||||
local filepath="$2"
|
||||
@ -774,6 +893,7 @@ download_subscription() {
|
||||
local wait="${5:-2}"
|
||||
local timeout="${6:-10}"
|
||||
local user_agent="${7:-}"
|
||||
local insecure="${8:-0}"
|
||||
|
||||
local sb_version device_model kernel_version hwid
|
||||
sb_version="$(get_sing_box_version)"
|
||||
@ -782,6 +902,14 @@ download_subscription() {
|
||||
hwid="$(generate_hwid)"
|
||||
[ -n "$user_agent" ] || user_agent="$(get_subscription_user_agent)"
|
||||
|
||||
# Optional TLS-verification bypass for IP-host panels with broken certs.
|
||||
# Empty string keeps the secure default; word-splitting it into the wget
|
||||
# argv (via _wget_subscription_request) yields zero extra args when off.
|
||||
local cert_flag=""
|
||||
if [ "$insecure" = "1" ]; then
|
||||
cert_flag="--no-check-certificate"
|
||||
fi
|
||||
|
||||
local tmpfile errfile rc family
|
||||
tmpfile="${filepath}.part.$$"
|
||||
errfile="${filepath}.err.$$"
|
||||
@ -793,48 +921,24 @@ download_subscription() {
|
||||
family="ipv4"
|
||||
if [ -n "$http_proxy_address" ]; then
|
||||
http_proxy="http://$http_proxy_address" https_proxy="http://$http_proxy_address" \
|
||||
wget -4 -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-4 -T "$timeout"
|
||||
else
|
||||
wget -4 -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-4 -T "$timeout"
|
||||
fi
|
||||
else
|
||||
if [ -n "$http_proxy_address" ]; then
|
||||
http_proxy="http://$http_proxy_address" https_proxy="http://$http_proxy_address" \
|
||||
wget -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-T "$timeout"
|
||||
else
|
||||
wget -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-T "$timeout"
|
||||
fi
|
||||
fi
|
||||
|
||||
@ -861,25 +965,13 @@ download_subscription() {
|
||||
log "Retrying subscription download over IPv4-only" "warn"
|
||||
if [ -n "$http_proxy_address" ]; then
|
||||
http_proxy="http://$http_proxy_address" https_proxy="http://$http_proxy_address" \
|
||||
wget -4 -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-4 -T "$timeout"
|
||||
else
|
||||
wget -4 -T "$timeout" -O "$tmpfile" \
|
||||
--header "User-Agent: $user_agent" \
|
||||
--header "X-HWID: $hwid" \
|
||||
--header "X-Device-OS: OpenWrt Linux" \
|
||||
--header "X-Device-Model: $device_model" \
|
||||
--header "X-Ver-OS: $kernel_version" \
|
||||
--header "Accept-Language: ru-RU,en,*" \
|
||||
--header "X-Device-Locale: EN" \
|
||||
"$url" 2>"$errfile"
|
||||
_wget_subscription_request "$cert_flag" "$user_agent" "$hwid" \
|
||||
"$device_model" "$kernel_version" "$tmpfile" "$errfile" "$url" \
|
||||
-4 -T "$timeout"
|
||||
fi
|
||||
rc=$?
|
||||
if [ "$rc" -eq 0 ] && [ -s "$tmpfile" ]; then
|
||||
@ -1144,17 +1236,34 @@ xray_json_to_uri_lines() {
|
||||
| (.outbounds // [])[]
|
||||
| select(type == "object")
|
||||
| select(.protocol == "vless" or .protocol == "trojan"
|
||||
or .protocol == "shadowsocks")
|
||||
or .protocol == "shadowsocks"
|
||||
or .protocol == "hysteria")
|
||||
# Skip chained / multi-hop outbounds: not representable as one URI.
|
||||
| select((.streamSettings.sockopt.dialerProxy // "") == "")
|
||||
# Hysteria here is always Hysteria2 (hysteriaSettings.version == 2);
|
||||
# the facade has no Hysteria v1 parser, so skip v1/missing-version
|
||||
# silently (no fatal). vless/trojan/shadowsocks are unaffected.
|
||||
| select(.protocol != "hysteria"
|
||||
or ((.streamSettings.hysteriaSettings.version // 0) == 2))
|
||||
| . as $ob
|
||||
| (.streamSettings // {}) as $ss
|
||||
| ($ss.network // "tcp") as $net
|
||||
# splithttp is the pre-rename name of the xhttp transport (sing-box
|
||||
# renamed it). Normalize it to xhttp so the emitted URI uses the modern
|
||||
# name and the facade xhttp branch handles it. No regex.
|
||||
| ($ss.network // "tcp") as $net_raw
|
||||
| (if $net_raw == "splithttp" then "xhttp" else $net_raw end) as $net
|
||||
# xhttp transport settings live under xhttpSettings, or the pre-rename
|
||||
# splithttpSettings alias.
|
||||
| ($ss.xhttpSettings // $ss.splithttpSettings // {}) as $xs
|
||||
| ($ss.security // "") as $sec
|
||||
| ($ss.realitySettings // {}) as $reality
|
||||
| ($ss.tlsSettings // $ss.realitySettings // {}) as $tls
|
||||
# vnext (vless/vmess) vs servers (trojan/shadowsocks) addressing.
|
||||
| ($ob.settings.vnext[0] // $ob.settings.servers[0] // {}) as $peer
|
||||
# Addressing: vnext (vless/vmess) vs servers (trojan/shadowsocks);
|
||||
# hysteria carries the peer directly in settings.address/settings.port
|
||||
# (no vnext/servers), so branch the peer derivation on protocol.
|
||||
| (if $ob.protocol == "hysteria"
|
||||
then {address: $ob.settings.address, port: $ob.settings.port}
|
||||
else ($ob.settings.vnext[0] // $ob.settings.servers[0] // {}) end) as $peer
|
||||
| ($peer.users[0] // {}) as $user
|
||||
| ($peer.address // "") as $host
|
||||
| ($peer.port // "") as $port
|
||||
@ -1180,6 +1289,18 @@ xray_json_to_uri_lines() {
|
||||
(if $sec != "" then ("security=" + ($sec)) else "security=tls" end),
|
||||
kv("sni"; ($tls.serverName // "")),
|
||||
kv("fp"; ($tls.fingerprint // "")) ]
|
||||
elif $ob.protocol == "hysteria" then
|
||||
# Hysteria2: no stream transport, so DO NOT emit type=. The
|
||||
# facade defaults security to tls for hysteria2 and reads
|
||||
# sni/insecure (via _add_outbound_security), obfs/obfs-password.
|
||||
($ss.hysteriaSettings // {}) as $hy
|
||||
| [ kv("sni"; ($tls.serverName // "")),
|
||||
(if (($tls.allowInsecure // $tls.insecure // false) == true)
|
||||
then "insecure=1" else empty end) ]
|
||||
+ (if ($hy.obfs // "") != "" then
|
||||
[ "obfs=salamander",
|
||||
kv("obfs-password"; ($hy.obfsPassword // $hy.obfs_password // "")) ]
|
||||
else [] end)
|
||||
else
|
||||
[ ("type=" + $net) ]
|
||||
end
|
||||
@ -1190,9 +1311,12 @@ xray_json_to_uri_lines() {
|
||||
[ kv("path"; ($ss.wsSettings.path // "")),
|
||||
kv("host"; ($ss.wsSettings.headers.Host // "")) ]
|
||||
elif $net == "xhttp" then
|
||||
[ kv("path"; ($ss.xhttpSettings.path // "")),
|
||||
kv("host"; ($ss.xhttpSettings.host // "")),
|
||||
kv("mode"; ($ss.xhttpSettings.mode // "")) ]
|
||||
# Accept both the modern xhttpSettings and the pre-rename
|
||||
# splithttpSettings key (network was normalized to xhttp above).
|
||||
# $xs binds to whichever settings object is present.
|
||||
[ kv("path"; ($xs.path // "")),
|
||||
kv("host"; ($xs.host // "")),
|
||||
kv("mode"; ($xs.mode // "")) ]
|
||||
elif $net == "grpc" then
|
||||
[ kv("serviceName"; ($ss.grpcSettings.serviceName // "")) ]
|
||||
else [] end
|
||||
@ -1202,12 +1326,17 @@ xray_json_to_uri_lines() {
|
||||
| ($base + $transport
|
||||
+ (if $alpn_str != "" then [ kv("alpn"; $alpn_str) ] else [] end)
|
||||
| map(select(. != null and . != ""))) as $query
|
||||
# Credential: uuid for vless, password for trojan/shadowsocks.
|
||||
# Credential: uuid for vless, hysteriaSettings.auth for hysteria,
|
||||
# password for trojan/shadowsocks.
|
||||
| (if $ob.protocol == "vless" then ($user.id // "")
|
||||
elif $ob.protocol == "hysteria" then
|
||||
($ss.hysteriaSettings.auth // "")
|
||||
else ($peer.password // $ob.settings.password // "") end) as $cred
|
||||
| select($cred != "")
|
||||
| ($ob.protocol
|
||||
| if . == "shadowsocks" then "ss" else . end) as $scheme
|
||||
| if . == "shadowsocks" then "ss"
|
||||
elif . == "hysteria" then "hysteria2"
|
||||
else . end) as $scheme
|
||||
# The connection part (no #fragment) is the dedup key: providers that
|
||||
# ship one server set across many "profiles" repeat identical nodes
|
||||
# with only the display name differing, which would otherwise inflate
|
||||
|
||||
@ -6,6 +6,24 @@ nft_create_table() {
|
||||
nft add table inet "$name"
|
||||
}
|
||||
|
||||
# Delete an nftables inet table if it exists (idempotent, fail-open).
|
||||
# create_nft_rules rebuilds the whole table from scratch, so it MUST start from
|
||||
# a clean slate: `nft add table` is idempotent but `nft add rule`/`nft add
|
||||
# chain` only ever APPEND. Without this flush, a table left behind by a previous
|
||||
# start that was not cleanly stopped (a procd respawn, an in-place package
|
||||
# upgrade, or a crash) keeps its stale rules and the freshly-added rules pile on
|
||||
# top of them. In particular a stale mark-EVERYTHING rule (from global_proxy or
|
||||
# an older mark-all build) would sit at the top of the prerouting chain and mark
|
||||
# all traffic before the new destination-selective rules are ever evaluated,
|
||||
# silently re-introducing the "everything proxied / 100% CPU" regression.
|
||||
nft_delete_table() {
|
||||
local name="$1"
|
||||
|
||||
if nft list table inet "$name" > /dev/null 2>&1; then
|
||||
nft delete table inet "$name" 2>/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
# Create a set within a table for storing IPv4 addresses
|
||||
nft_create_ipv4_set() {
|
||||
local table="$1"
|
||||
@ -14,6 +32,13 @@ nft_create_ipv4_set() {
|
||||
nft add set inet "$table" "$name" '{ type ipv4_addr; flags interval; auto-merge; }'
|
||||
}
|
||||
|
||||
nft_create_ipv6_set() {
|
||||
local table="$1"
|
||||
local name="$2"
|
||||
|
||||
nft add set inet "$table" "$name" '{ type ipv6_addr; flags interval; auto-merge; }'
|
||||
}
|
||||
|
||||
nft_create_ifname_set() {
|
||||
local table="$1"
|
||||
local name="$2"
|
||||
@ -68,4 +93,52 @@ nft_add_set_elements_from_file_chunked() {
|
||||
log "Adding $count elements to nft set $nft_set_name" "debug"
|
||||
nft_add_set_elements "$nft_table_name" "$nft_set_name" "$array"
|
||||
fi
|
||||
}
|
||||
}
|
||||
|
||||
# IPv6 counterpart of nft_add_set_elements_from_file_chunked. Adds only the
|
||||
# IPv6 / IPv6-CIDR lines from the file into an ipv6_addr set. A line is treated
|
||||
# as IPv6 when it contains a ':' (after trimming); anything else (IPv4, blank,
|
||||
# comment) is skipped. Fail-open: a malformed line is simply not added, so the
|
||||
# corresponding traffic goes direct rather than blackholing.
|
||||
nft_add_set_elements_from_file_chunked_v6() {
|
||||
local filepath="$1"
|
||||
local nft_table_name="$2"
|
||||
local nft_set_name="$3"
|
||||
local chunk_size="${4:-5000}"
|
||||
|
||||
local array count
|
||||
count=0
|
||||
while IFS= read -r line; do
|
||||
line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
|
||||
|
||||
[ -z "$line" ] && continue
|
||||
|
||||
case "$line" in
|
||||
*:*) ;;
|
||||
*)
|
||||
log "'$line' is not IPv6 or IPv6 CIDR" "debug"
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$array" ]; then
|
||||
array="$line"
|
||||
else
|
||||
array="$array,$line"
|
||||
fi
|
||||
|
||||
count=$((count + 1))
|
||||
|
||||
if [ "$count" = "$chunk_size" ]; then
|
||||
log "Adding $count elements to nft set $nft_set_name" "debug"
|
||||
nft_add_set_elements "$nft_table_name" "$nft_set_name" "$array"
|
||||
array=""
|
||||
count=0
|
||||
fi
|
||||
done < "$filepath"
|
||||
|
||||
if [ -n "$array" ]; then
|
||||
log "Adding $count elements to nft set $nft_set_name" "debug"
|
||||
nft_add_set_elements "$nft_table_name" "$nft_set_name" "$array"
|
||||
fi
|
||||
}
|
||||
|
||||
@ -174,7 +174,17 @@ sing_box_cf_add_proxy_outbound() {
|
||||
# Generation is gated behind sing-box-extended. On a stock sing-box build
|
||||
# we log a clear message and return the config UNCHANGED (no exit 1, no
|
||||
# outbound added) so generation degrades safely and keeps the last-good
|
||||
# config. tuic/hysteria1/anytls/shadowtls reuse this exact block.
|
||||
# config.
|
||||
#
|
||||
# Schemes this dispatcher PARSES: socks4/socks4a/socks5, vless, ss,
|
||||
# trojan, hysteria2/hy2, and vmess (vmess is extended-gated above). Any
|
||||
# OTHER scheme (tuic, hysteria v1, anytls, shadowtls, wireguard, http,
|
||||
# or a typo) is NOT parsed here: it hits the default `*)` arm below,
|
||||
# which logs a WARNING and returns the config UNCHANGED (rc 1, skip) so a
|
||||
# single bad link in a url/selector/urltest input never aborts the whole
|
||||
# config. Such schemes are reachable only via a raw `outbound_json`
|
||||
# connection (proxy_config_type=outbound) or a native sing-box-JSON
|
||||
# subscription, which bypass this URL dispatcher entirely.
|
||||
if ! is_sing_box_extended; then
|
||||
log "VMess requires sing-box-extended. Install sing-box-extended and retry." "error"
|
||||
echo "$config"
|
||||
@ -221,8 +231,17 @@ sing_box_cf_add_proxy_outbound() {
|
||||
"$vm_tls" "$vm_sni" "$vm_alpn" "$vm_fp" "$vm_server")
|
||||
;;
|
||||
*)
|
||||
log "Unsupported proxy $scheme type. Aborted." "fatal"
|
||||
exit 1
|
||||
# Unsupported scheme: downgrade from fatal to a WARNING + skip. This
|
||||
# dispatcher is shared by the single-URL, selector-loop and urltest-loop
|
||||
# callers, so a single unsupported/typo'd link must NOT abort generation
|
||||
# of the whole config. Echo the input config UNCHANGED (never empty — an
|
||||
# empty echo would wipe the caller's `config=$(...)`) and return non-zero
|
||||
# so the caller knows no outbound was added and can skip this node and
|
||||
# continue with the remaining links. The subscription normalize caller
|
||||
# already understands this non-zero "skip" contract.
|
||||
log "Unsupported proxy scheme '$scheme'; skipping this link (supported: socks/vless/ss/trojan/hysteria2/vmess)" "warn"
|
||||
echo "$config"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
|
||||
@ -255,8 +274,9 @@ _add_outbound_security() {
|
||||
short_id=$(url_get_query_param "$url" "sid")
|
||||
|
||||
# XHTTP transport defaults its ALPN to h2/http/1.1 when none is provided.
|
||||
# `splithttp` is the pre-rename alias of `xhttp` (see _add_outbound_transport).
|
||||
transport_type=$(url_get_query_param "$url" "type")
|
||||
if [ "$transport_type" = "xhttp" ] && [ "$alpn" = "[]" ]; then
|
||||
if { [ "$transport_type" = "xhttp" ] || [ "$transport_type" = "splithttp" ]; } && [ "$alpn" = "[]" ]; then
|
||||
alpn='["h2","http/1.1"]'
|
||||
fi
|
||||
|
||||
@ -325,7 +345,11 @@ _add_outbound_transport() {
|
||||
sing_box_cm_set_grpc_transport_for_outbound "$config" "$outbound_tag" "$grpc_service_name"
|
||||
)
|
||||
;;
|
||||
xhttp)
|
||||
xhttp | splithttp)
|
||||
# `splithttp` is the pre-rename name of the `xhttp` transport (sing-box
|
||||
# renamed it). Accept it as an alias and normalize to xhttp downstream:
|
||||
# sing_box_cm_set_xhttp_transport_for_outbound emits the modern `xhttp`
|
||||
# key, so the config sing-box sees always uses the current name.
|
||||
if ! is_sing_box_extended; then
|
||||
log "XHTTP transport requires sing-box-extended. Install sing-box-extended and retry." "error"
|
||||
echo "$config"
|
||||
|
||||
@ -223,15 +223,20 @@ sing_box_cm_add_fakeip_dns_server() {
|
||||
local config="$1"
|
||||
local tag="$2"
|
||||
local inet4_range="$3"
|
||||
local inet6_range="$4"
|
||||
|
||||
echo "$config" | jq \
|
||||
--arg tag "$tag" \
|
||||
--arg inet4_range "$inet4_range" \
|
||||
'.dns.servers += [{
|
||||
type: "fakeip",
|
||||
tag: $tag,
|
||||
inet4_range: $inet4_range,
|
||||
}]'
|
||||
--arg inet6_range "$inet6_range" \
|
||||
'.dns.servers += [(
|
||||
{
|
||||
type: "fakeip",
|
||||
tag: $tag,
|
||||
inet4_range: $inet4_range
|
||||
}
|
||||
+ (if $inet6_range != "" then { inet6_range: $inet6_range } else {} end)
|
||||
)]'
|
||||
}
|
||||
|
||||
#######################################
|
||||
@ -1192,10 +1197,13 @@ sing_box_cm_add_selector_outbound() {
|
||||
# auto_detect_interface: boolean, enable or disable automatic interface detection
|
||||
# default_domain_resolver: string, default DNS resolver for domain-based routing
|
||||
# default_interface: string, default network interface to use when auto detection is disabled (optional)
|
||||
# default_mark: integer, routing mark stamped on sing-box's own egress
|
||||
# connections so the nft/ip-rule tproxy path does not re-capture them
|
||||
# (optional; empty -> omitted, byte-identical to the no-mark output)
|
||||
# Outputs:
|
||||
# Writes updated JSON configuration to stdout
|
||||
# Example:
|
||||
# CONFIG=$(sing_box_cm_configure_route "$CONFIG" "direct-out" true "udp-server")
|
||||
# CONFIG=$(sing_box_cm_configure_route "$CONFIG" "direct-out" true "udp-server" "" 2097152)
|
||||
#######################################
|
||||
sing_box_cm_configure_route() {
|
||||
local config="$1"
|
||||
@ -1203,12 +1211,14 @@ sing_box_cm_configure_route() {
|
||||
local auto_detect_interface="$3"
|
||||
local default_domain_resolver="$4"
|
||||
local default_interface="$5"
|
||||
local default_mark="$6"
|
||||
|
||||
echo "$config" | jq \
|
||||
--arg final "$final" \
|
||||
--argjson auto_detect_interface "$auto_detect_interface" \
|
||||
--arg default_domain_resolver "$default_domain_resolver" \
|
||||
--arg default_interface "$default_interface" \
|
||||
--arg default_mark "$default_mark" \
|
||||
'.route = {
|
||||
rules: (.route.rules // []),
|
||||
rule_set: (.route.rule_set // []),
|
||||
@ -1217,6 +1227,7 @@ sing_box_cm_configure_route() {
|
||||
default_domain_resolver: $default_domain_resolver
|
||||
}
|
||||
+ (if $default_interface != "" then { default_interface: $default_interface } else {} end)
|
||||
+ (if $default_mark != "" then { default_mark: ($default_mark | tonumber) } else {} end)
|
||||
'
|
||||
}
|
||||
|
||||
@ -1353,6 +1364,51 @@ sing_box_cm_add_reject_route_rule() {
|
||||
}]'
|
||||
}
|
||||
|
||||
#######################################
|
||||
# Add a DoH blocking reject route rule with an inline ruleset containing known
|
||||
# public DoH server IP ranges.
|
||||
# Arguments:
|
||||
# config: string (JSON), sing-box configuration to modify
|
||||
# tag: string, identifier for the route rule and ruleset
|
||||
# inbound: string, inbound tag to match
|
||||
# doh_ipv4_cidrs: string, space-separated IPv4 CIDRs to block
|
||||
# doh_ipv6_cidrs: string, space-separated IPv6 CIDRs to block
|
||||
# Outputs:
|
||||
# Writes updated JSON configuration to stdout
|
||||
#######################################
|
||||
sing_box_cm_add_doh_block_route_rule() {
|
||||
local config="$1"
|
||||
local tag="$2"
|
||||
local inbound="$3"
|
||||
local doh_ipv4_cidrs="$4"
|
||||
local doh_ipv6_cidrs="${5:-}"
|
||||
|
||||
local ruleset_tag cidrs_json
|
||||
ruleset_tag="${tag}-ruleset"
|
||||
cidrs_json=$(printf '%s %s' "$doh_ipv4_cidrs" "$doh_ipv6_cidrs" | jq -R 'split(" ") | map(select(. != ""))')
|
||||
|
||||
config=$(echo "$config" | jq \
|
||||
--arg tag "$ruleset_tag" \
|
||||
--argjson ip_cidr "$cidrs_json" \
|
||||
'.route.rule_set += [{
|
||||
type: "inline",
|
||||
tag: $tag,
|
||||
rules: [{ ip_cidr: $ip_cidr }]
|
||||
}]')
|
||||
|
||||
echo "$config" | jq \
|
||||
--arg service_tag "$SERVICE_TAG" \
|
||||
--arg tag "$tag" \
|
||||
--arg inbound "$inbound" \
|
||||
--arg ruleset_tag "$ruleset_tag" \
|
||||
'.route.rules += [{
|
||||
action: "reject",
|
||||
inbound: $inbound,
|
||||
rule_set: $ruleset_tag,
|
||||
$service_tag: $tag
|
||||
}]'
|
||||
}
|
||||
|
||||
#######################################
|
||||
# Add a hijack-dns rule to the route section of a sing-box JSON configuration.
|
||||
# Arguments:
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
# This file is sourced from /usr/bin/netshift, so log() is available.
|
||||
|
||||
SB_EXT_ARCH_SUFFIX=""
|
||||
UPDATES_SING_BOX_EXTENDED_REPO="shtorm-7/sing-box-extended"
|
||||
UPDATES_SING_BOX_EXTENDED_REPO="ural/sing-box-extended"
|
||||
|
||||
# Async component-action job state. State lives on tmpfs (/var/run): it survives
|
||||
# the rpcd call that started the worker but is intentionally transient (cleared
|
||||
@ -27,6 +27,42 @@ updates_log() {
|
||||
log "Updater: $message" "$level"
|
||||
}
|
||||
|
||||
# Verify that a backup copy is byte-complete, guarding the core-swap rollback
|
||||
# against a TRUNCATED backup written under tmpfs ENOSPC (busybox `cp` does not
|
||||
# reliably return non-zero on a partial write). Returns 0 iff $dst exists and
|
||||
# its byte size equals $src's size. A size match is sufficient here: this is a
|
||||
# same-machine copy of the same file and we are guarding truncation, not bit-rot
|
||||
# — do NOT md5/sha a ~40 MB binary on a slow armv7 router. If $src is absent
|
||||
# there is nothing to back up, so verification trivially succeeds (0).
|
||||
updates_verify_copy() {
|
||||
local src="$1"
|
||||
local dst="$2"
|
||||
local ssz dsz
|
||||
|
||||
[ -f "$src" ] || return 0
|
||||
[ -f "$dst" ] || return 1
|
||||
ssz="$(wc -c < "$src" 2>/dev/null)" || return 1
|
||||
dsz="$(wc -c < "$dst" 2>/dev/null)" || return 1
|
||||
[ -n "$ssz" ] && [ "$ssz" = "$dsz" ]
|
||||
}
|
||||
|
||||
# Verify that a stashed backup is still byte-complete BEFORE a rollback restores
|
||||
# it over the live path. Compares the backup's current byte size against the
|
||||
# expected source size recorded at backup time. Returns 0 iff $backup exists and
|
||||
# its size equals $expected_size. Refusing to restore a truncated backup is
|
||||
# safer than installing a segfaulting core as the "safe" fallback.
|
||||
updates_backup_is_complete() {
|
||||
local backup="$1"
|
||||
local expected_size="$2"
|
||||
local bsz
|
||||
|
||||
[ -n "$backup" ] || return 1
|
||||
[ -f "$backup" ] || return 1
|
||||
[ -n "$expected_size" ] || return 1
|
||||
bsz="$(wc -c < "$backup" 2>/dev/null)" || return 1
|
||||
[ -n "$bsz" ] && [ "$bsz" = "$expected_size" ]
|
||||
}
|
||||
|
||||
# ── Async component-action job state (jq, atomic) ───────────────────
|
||||
#
|
||||
# The UI starts long-running component actions (e.g. switching the sing-box
|
||||
@ -514,7 +550,7 @@ updates_http_get_once() {
|
||||
# mistaken for a releases list.
|
||||
updates_fetch_sing_box_extended_releases() {
|
||||
local url response proxy
|
||||
url="https://api.github.com/repos/${UPDATES_SING_BOX_EXTENDED_REPO}/releases?per_page=30"
|
||||
url="https://uralgit.ru/api/v1/repos/${UPDATES_SING_BOX_EXTENDED_REPO}/releases?per_page=30"
|
||||
|
||||
response="$(updates_http_get_once "$url" "")"
|
||||
if updates_response_is_release_array "$response"; then
|
||||
@ -918,6 +954,7 @@ _updates_install_sing_box_extended_core() {
|
||||
local tmp_dir archive releases tag rel asset_url
|
||||
local binary_path cronet_path
|
||||
local backup_binary="" backup_cronet="" new_version
|
||||
local backup_binary_size="" backup_cronet_size=""
|
||||
|
||||
# Interruption-tolerant heal: a run killed mid-flight (e.g. the old rpcd 30s
|
||||
# timeout) could leave a non-executable /usr/bin/sing-box behind. Such a
|
||||
@ -996,21 +1033,29 @@ _updates_install_sing_box_extended_core() {
|
||||
# no room for a second copy of the binary.
|
||||
if [ -e /usr/bin/sing-box ]; then
|
||||
backup_binary="$tmp_dir/sing-box.backup"
|
||||
if ! cp -p /usr/bin/sing-box "$backup_binary" 2>/dev/null; then
|
||||
# Gate on a byte-complete backup, not just cp's exit code: a partial
|
||||
# write under tmpfs ENOSPC could otherwise pass and later be restored as
|
||||
# a truncated, segfaulting "safe" fallback. Abort here — the live binary
|
||||
# has NOT been touched yet, so the working core is left intact.
|
||||
if ! cp -p /usr/bin/sing-box "$backup_binary" 2>/dev/null ||
|
||||
! updates_verify_copy /usr/bin/sing-box "$backup_binary"; then
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to backup current sing-box binary" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to backup current sing-box binary\"}"
|
||||
return 1
|
||||
fi
|
||||
backup_binary_size="$(wc -c < "$backup_binary" 2>/dev/null)"
|
||||
fi
|
||||
if [ -n "$cronet_path" ] && [ -e /usr/lib/libcronet.so ]; then
|
||||
backup_cronet="$tmp_dir/libcronet.so.backup"
|
||||
if ! cp -p /usr/lib/libcronet.so "$backup_cronet" 2>/dev/null; then
|
||||
if ! cp -p /usr/lib/libcronet.so "$backup_cronet" 2>/dev/null ||
|
||||
! updates_verify_copy /usr/lib/libcronet.so "$backup_cronet"; then
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to backup current libcronet.so" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to backup current libcronet.so\"}"
|
||||
return 1
|
||||
fi
|
||||
backup_cronet_size="$(wc -c < "$backup_cronet" 2>/dev/null)"
|
||||
fi
|
||||
|
||||
# Free overlay space by removing the live binary BEFORE extracting, then
|
||||
@ -1019,7 +1064,16 @@ _updates_install_sing_box_extended_core() {
|
||||
rm -f /usr/bin/sing-box
|
||||
if ! tar -xzf "$archive" -O "$binary_path" > /usr/bin/sing-box 2>/dev/null || [ ! -s /usr/bin/sing-box ]; then
|
||||
rm -f /usr/bin/sing-box
|
||||
[ -n "$backup_binary" ] && mv -f "$backup_binary" /usr/bin/sing-box
|
||||
# Only restore from a backup that is still byte-complete — restoring a
|
||||
# truncated backup would install a segfaulting core as the "safe"
|
||||
# fallback (worse than leaving the path absent).
|
||||
if [ -n "$backup_binary" ]; then
|
||||
if updates_backup_is_complete "$backup_binary" "$backup_binary_size"; then
|
||||
mv -f "$backup_binary" /usr/bin/sing-box
|
||||
else
|
||||
updates_log "Rollback: sing-box backup is corrupt/incomplete; NOT restoring to avoid installing a broken core" "error"
|
||||
fi
|
||||
fi
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to extract sing-box-extended binary (out of space on overlay?)" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to extract sing-box-extended binary (not enough free space on the router?)\"}"
|
||||
@ -1031,8 +1085,20 @@ _updates_install_sing_box_extended_core() {
|
||||
rm -f /usr/lib/libcronet.so
|
||||
if ! tar -xzf "$archive" -O "$cronet_path" > /usr/lib/libcronet.so 2>/dev/null || [ ! -s /usr/lib/libcronet.so ]; then
|
||||
rm -f /usr/bin/sing-box /usr/lib/libcronet.so
|
||||
[ -n "$backup_binary" ] && mv -f "$backup_binary" /usr/bin/sing-box
|
||||
[ -n "$backup_cronet" ] && mv -f "$backup_cronet" /usr/lib/libcronet.so
|
||||
if [ -n "$backup_binary" ]; then
|
||||
if updates_backup_is_complete "$backup_binary" "$backup_binary_size"; then
|
||||
mv -f "$backup_binary" /usr/bin/sing-box
|
||||
else
|
||||
updates_log "Rollback: sing-box backup is corrupt/incomplete; NOT restoring to avoid installing a broken core" "error"
|
||||
fi
|
||||
fi
|
||||
if [ -n "$backup_cronet" ]; then
|
||||
if updates_backup_is_complete "$backup_cronet" "$backup_cronet_size"; then
|
||||
mv -f "$backup_cronet" /usr/lib/libcronet.so
|
||||
else
|
||||
updates_log "Rollback: libcronet.so backup is corrupt/incomplete; NOT restoring" "error"
|
||||
fi
|
||||
fi
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to extract libcronet.so" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to extract libcronet.so\"}"
|
||||
@ -1049,9 +1115,21 @@ _updates_install_sing_box_extended_core() {
|
||||
*extended*) ;;
|
||||
*)
|
||||
rm -f /usr/bin/sing-box
|
||||
[ -n "$backup_binary" ] && mv -f "$backup_binary" /usr/bin/sing-box
|
||||
if [ -n "$backup_binary" ]; then
|
||||
if updates_backup_is_complete "$backup_binary" "$backup_binary_size"; then
|
||||
mv -f "$backup_binary" /usr/bin/sing-box
|
||||
else
|
||||
updates_log "Rollback: sing-box backup is corrupt/incomplete; NOT restoring to avoid installing a broken core" "error"
|
||||
fi
|
||||
fi
|
||||
[ -n "$cronet_path" ] && rm -f /usr/lib/libcronet.so
|
||||
[ -n "$backup_cronet" ] && mv -f "$backup_cronet" /usr/lib/libcronet.so
|
||||
if [ -n "$backup_cronet" ]; then
|
||||
if updates_backup_is_complete "$backup_cronet" "$backup_cronet_size"; then
|
||||
mv -f "$backup_cronet" /usr/lib/libcronet.so
|
||||
else
|
||||
updates_log "Rollback: libcronet.so backup is corrupt/incomplete; NOT restoring" "error"
|
||||
fi
|
||||
fi
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Installed sing-box failed extended validation; previous binary restored" "error"
|
||||
echo "{\"success\":false,\"message\":\"Installed sing-box failed extended validation; previous binary restored\"}"
|
||||
@ -1122,6 +1200,7 @@ updates_install_sing_box_stable() {
|
||||
_updates_install_sing_box_stable_core() {
|
||||
local new_version installed=1
|
||||
local tmp_dir backup_binary="" backup_cronet=""
|
||||
local backup_binary_size="" backup_cronet_size=""
|
||||
|
||||
# Remove stale temp dirs from an interrupted earlier run (tmpfs is small).
|
||||
rm -rf /tmp/netshift-sbstable.* 2>/dev/null
|
||||
@ -1137,21 +1216,29 @@ _updates_install_sing_box_stable_core() {
|
||||
# touches anything, so a failed install can be rolled back to a working core.
|
||||
if [ -e "$UPDATES_SING_BOX_BIN" ]; then
|
||||
backup_binary="$tmp_dir/sing-box.backup"
|
||||
if ! cp -p "$UPDATES_SING_BOX_BIN" "$backup_binary" 2>/dev/null; then
|
||||
# Gate on a byte-complete backup, not just cp's exit code (busybox cp can
|
||||
# truncate under tmpfs ENOSPC and still return 0). Abort here — the
|
||||
# package manager has not touched the binary yet, so the working core
|
||||
# stays intact.
|
||||
if ! cp -p "$UPDATES_SING_BOX_BIN" "$backup_binary" 2>/dev/null ||
|
||||
! updates_verify_copy "$UPDATES_SING_BOX_BIN" "$backup_binary"; then
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to backup current sing-box binary" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to backup current sing-box binary\"}"
|
||||
return 1
|
||||
fi
|
||||
backup_binary_size="$(wc -c < "$backup_binary" 2>/dev/null)"
|
||||
fi
|
||||
if [ -e "$UPDATES_LIBCRONET_LIB" ]; then
|
||||
backup_cronet="$tmp_dir/libcronet.so.backup"
|
||||
if ! cp -p "$UPDATES_LIBCRONET_LIB" "$backup_cronet" 2>/dev/null; then
|
||||
if ! cp -p "$UPDATES_LIBCRONET_LIB" "$backup_cronet" 2>/dev/null ||
|
||||
! updates_verify_copy "$UPDATES_LIBCRONET_LIB" "$backup_cronet"; then
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to backup current libcronet.so" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to backup current libcronet.so\"}"
|
||||
return 1
|
||||
fi
|
||||
backup_cronet_size="$(wc -c < "$backup_cronet" 2>/dev/null)"
|
||||
fi
|
||||
|
||||
if command -v apk >/dev/null 2>&1; then
|
||||
@ -1179,7 +1266,7 @@ _updates_install_sing_box_stable_core() {
|
||||
if [ "$installed" -eq 0 ]; then
|
||||
# Package install failed (it may have already removed/half-replaced the
|
||||
# binary). Restore the tmpfs backup so a working core remains.
|
||||
updates_stable_rollback "$backup_binary" "$backup_cronet"
|
||||
updates_stable_rollback "$backup_binary" "$backup_cronet" "$backup_binary_size" "$backup_cronet_size"
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Failed to install stable sing-box via package manager; previous binary restored" "error"
|
||||
echo "{\"success\":false,\"message\":\"Failed to install stable sing-box (package manager error); previous binary restored\"}"
|
||||
@ -1193,7 +1280,7 @@ _updates_install_sing_box_stable_core() {
|
||||
# longer be an "extended" build. If it still is, the install did not land —
|
||||
# restore the backup so the router keeps a known-good core.
|
||||
if is_sing_box_extended "$new_version"; then
|
||||
updates_stable_rollback "$backup_binary" "$backup_cronet"
|
||||
updates_stable_rollback "$backup_binary" "$backup_cronet" "$backup_binary_size" "$backup_cronet_size"
|
||||
rm -rf "$tmp_dir"
|
||||
updates_log "Stable install reported success but sing-box is still extended ($new_version); previous binary restored" "error"
|
||||
echo "{\"success\":false,\"message\":\"sing-box is still the extended build after install; rollback did not take effect (previous binary restored)\"}"
|
||||
@ -1217,25 +1304,42 @@ _updates_install_sing_box_stable_core() {
|
||||
# Restores the tmpfs backup of /usr/bin/sing-box (and libcronet.so) into place.
|
||||
# Used by the stable path when the package install or validation fails so the
|
||||
# router never ends core-less. Best-effort; logs the outcome.
|
||||
#
|
||||
# Args 3/4 are the byte sizes recorded at backup time. The restore is performed
|
||||
# ONLY if the backup is still byte-complete (size match) — a truncated backup
|
||||
# (tmpfs ENOSPC) is refused rather than restored as a segfaulting core.
|
||||
updates_stable_rollback() {
|
||||
local backup_binary="$1"
|
||||
local backup_cronet="$2"
|
||||
local backup_binary_size="$3"
|
||||
local backup_cronet_size="$4"
|
||||
|
||||
if [ -n "$backup_binary" ] && [ -e "$backup_binary" ]; then
|
||||
rm -f "$UPDATES_SING_BOX_BIN" 2>/dev/null
|
||||
if mv -f "$backup_binary" "$UPDATES_SING_BOX_BIN" 2>/dev/null; then
|
||||
chmod 0755 "$UPDATES_SING_BOX_BIN" 2>/dev/null || true
|
||||
updates_log "Rollback: restored previous sing-box binary from tmpfs backup"
|
||||
if [ -n "$backup_binary" ]; then
|
||||
# Only restore a byte-complete backup: a truncated backup (tmpfs ENOSPC)
|
||||
# would otherwise be installed as a segfaulting "safe" core, which is
|
||||
# worse than not restoring. Surface a loud error and leave the live path.
|
||||
if updates_backup_is_complete "$backup_binary" "$backup_binary_size"; then
|
||||
rm -f "$UPDATES_SING_BOX_BIN" 2>/dev/null
|
||||
if mv -f "$backup_binary" "$UPDATES_SING_BOX_BIN" 2>/dev/null; then
|
||||
chmod 0755 "$UPDATES_SING_BOX_BIN" 2>/dev/null || true
|
||||
updates_log "Rollback: restored previous sing-box binary from tmpfs backup"
|
||||
else
|
||||
updates_log "Rollback: FAILED to restore sing-box binary from backup" "error"
|
||||
fi
|
||||
else
|
||||
updates_log "Rollback: FAILED to restore sing-box binary from backup" "error"
|
||||
updates_log "Rollback: sing-box backup is corrupt/incomplete; NOT restoring to avoid installing a broken core" "error"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -n "$backup_cronet" ] && [ -e "$backup_cronet" ]; then
|
||||
rm -f "$UPDATES_LIBCRONET_LIB" 2>/dev/null
|
||||
if mv -f "$backup_cronet" "$UPDATES_LIBCRONET_LIB" 2>/dev/null; then
|
||||
chmod 0644 "$UPDATES_LIBCRONET_LIB" 2>/dev/null || true
|
||||
updates_log "Rollback: restored previous libcronet.so from tmpfs backup"
|
||||
if [ -n "$backup_cronet" ]; then
|
||||
if updates_backup_is_complete "$backup_cronet" "$backup_cronet_size"; then
|
||||
rm -f "$UPDATES_LIBCRONET_LIB" 2>/dev/null
|
||||
if mv -f "$backup_cronet" "$UPDATES_LIBCRONET_LIB" 2>/dev/null; then
|
||||
chmod 0644 "$UPDATES_LIBCRONET_LIB" 2>/dev/null || true
|
||||
updates_log "Rollback: restored previous libcronet.so from tmpfs backup"
|
||||
fi
|
||||
else
|
||||
updates_log "Rollback: libcronet.so backup is corrupt/incomplete; NOT restoring" "error"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
@ -1243,7 +1347,7 @@ updates_stable_rollback() {
|
||||
# Checks whether a newer sing-box-extended release is available.
|
||||
# Echoes a JSON status (latest|outdated) on stdout.
|
||||
updates_check_sing_box_extended() {
|
||||
local current_version releases tag status
|
||||
local current_version releases tag status cur_norm tag_norm
|
||||
|
||||
current_version="$(get_sing_box_version)"
|
||||
|
||||
@ -1259,15 +1363,560 @@ updates_check_sing_box_extended() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Normalize a single leading "v" off BOTH sides before comparing/emitting.
|
||||
# get_sing_box_version yields "1.13.12-extended-2.3.2" (no v) while the
|
||||
# GitHub .tag_name is "v1.13.12-extended-2.3.2" (with v), so the old
|
||||
# substring match never fired and reported a false "outdated". ${x#v} strips
|
||||
# exactly one leading "v" if present and leaves the string otherwise — safe
|
||||
# for both forms. NB: `tag` itself (with v) is untouched and is NOT used by
|
||||
# the install/asset path here; the installer re-derives its own tag.
|
||||
cur_norm="${current_version#v}"
|
||||
tag_norm="${tag#v}"
|
||||
|
||||
# EXACT equality after the v-strip: the extended version string is the full
|
||||
# token (e.g. "1.13.12-extended-2.3.2"), so an exact match is correct and
|
||||
# avoids the accidental partial matches the old `case *"$tag"*` form allowed.
|
||||
status="outdated"
|
||||
if [ "$cur_norm" = "$tag_norm" ]; then
|
||||
status="latest"
|
||||
fi
|
||||
|
||||
# Emit BOTH versions v-stripped so the UI shows a consistent string.
|
||||
echo "{\"success\":true,\"current_version\":\"$cur_norm\",\"latest_version\":\"$tag_norm\",\"status\":\"$status\"}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# ── Package-manager abstraction (Component Manager, task-017) ───────
|
||||
#
|
||||
# updater.sh does NOT source install.sh, so these are the tiny `updates_`-prefixed
|
||||
# equivalents of install.sh's pkg_is_apk / pkg_install / pkg_is_installed. On a
|
||||
# real device exactly ONE of apk/opkg exists. Package output is parsed with
|
||||
# cut/awk/grep only — NEVER Oniguruma jq.
|
||||
|
||||
# Returns 0 if the device uses apk (the apk binary is present), non-zero for opkg.
|
||||
updates_pkg_is_apk() {
|
||||
command -v apk >/dev/null 2>&1
|
||||
}
|
||||
|
||||
# Installs a package FILE (downloaded .ipk/.apk) non-interactively. Returns the
|
||||
# package manager's exit status. apk needs --allow-untrusted for self-built
|
||||
# packages; opkg install handles the local file path directly.
|
||||
updates_pkg_install_file() {
|
||||
local pkg_file="$1"
|
||||
|
||||
if updates_pkg_is_apk; then
|
||||
apk add --allow-untrusted "$pkg_file" </dev/null >/dev/null 2>&1
|
||||
else
|
||||
# --force-downgrade: a legacy v-prefixed build (e.g. v0.8.6) sorts ABOVE
|
||||
# the no-v target (0.8.7) in opkg's dpkg-style compare, so a plain
|
||||
# `opkg install` returns rc=0 and refuses ("Not downgrading ..."). The
|
||||
# flag forces the v->no-v transition to actually land.
|
||||
# --force-reinstall: covers the "already installed at this exact version"
|
||||
# no-op. opkg rc is NOT a reliable success signal either way — the
|
||||
# verify-after-install belt in _updates_self_update_netshift_core is the
|
||||
# authoritative check.
|
||||
opkg install --force-downgrade --force-reinstall "$pkg_file" </dev/null >/dev/null 2>&1
|
||||
fi
|
||||
}
|
||||
|
||||
# Returns 0 if a package NAME is currently installed. Mirrors install.sh's
|
||||
# pkg_is_installed grep-based detection (busybox-safe; no regex needed).
|
||||
updates_pkg_is_installed() {
|
||||
local pkg_name="$1"
|
||||
|
||||
if updates_pkg_is_apk; then
|
||||
apk list --installed 2>/dev/null | grep -q "$pkg_name"
|
||||
else
|
||||
opkg list-installed 2>/dev/null | grep -q "$pkg_name"
|
||||
fi
|
||||
}
|
||||
|
||||
# Echoes the FEED/candidate version of a package (the version the package
|
||||
# manager would install), or nothing if unavailable. Parsed with cut/awk only.
|
||||
# opkg list <pkg> -> "<name> - <version>" (field after " - ")
|
||||
# apk list <pkg> -> "<name>-<version> <arch> {...} ..." (strip "<name>-")
|
||||
updates_pkg_candidate_version() {
|
||||
local pkg_name="$1"
|
||||
local line version=""
|
||||
|
||||
if updates_pkg_is_apk; then
|
||||
# First matching list line; the token is "<name>-<version>". Strip the
|
||||
# leading "<pkg>-" so only the version (e.g. "1.12.22-r1") remains.
|
||||
line="$(apk list "$pkg_name" 2>/dev/null | grep -v '\[installed\]' | awk '{print $1}' | head -n1)"
|
||||
[ -n "$line" ] || line="$(apk list "$pkg_name" 2>/dev/null | awk '{print $1}' | head -n1)"
|
||||
case "$line" in
|
||||
"$pkg_name"-*) version="${line#"$pkg_name"-}" ;;
|
||||
esac
|
||||
else
|
||||
# opkg list prints "<name> - <version>"; take the field after " - ".
|
||||
version="$(opkg list "$pkg_name" 2>/dev/null | grep "^${pkg_name} " | head -n1 | awk -F' - ' '{print $2}')"
|
||||
fi
|
||||
|
||||
printf '%s' "$version"
|
||||
}
|
||||
|
||||
# Echoes the INSTALLED version of a package (what is on the system right now),
|
||||
# or nothing if the package is not installed. Distinct from
|
||||
# updates_pkg_candidate_version (that reads the FEED candidate). Parsed with
|
||||
# grep/awk only — NEVER Oniguruma jq. Mirrors updates_pkg_is_installed.
|
||||
# opkg list-installed -> "<name> - <version>" (field after " - ")
|
||||
# apk list --installed <pkg> -> "<name>-<version> <arch> {...} ..." (strip "<name>-")
|
||||
updates_pkg_installed_version() {
|
||||
local pkg_name="$1"
|
||||
local line version=""
|
||||
|
||||
if updates_pkg_is_apk; then
|
||||
# First installed-list token is "<name>-<version>"; strip the leading
|
||||
# "<pkg>-" so only the version (e.g. "0.8.7-r1") remains.
|
||||
line="$(apk list --installed "$pkg_name" 2>/dev/null | awk '{print $1}' | head -n1)"
|
||||
case "$line" in
|
||||
"$pkg_name"-*) version="${line#"$pkg_name"-}" ;;
|
||||
esac
|
||||
else
|
||||
# opkg list-installed prints "<name> - <version>"; take the field after
|
||||
# " - " for the exact package name.
|
||||
version="$(opkg list-installed 2>/dev/null | grep "^${pkg_name} " | head -n1 | awk -F' - ' '{print $2}')"
|
||||
fi
|
||||
|
||||
printf '%s' "$version"
|
||||
}
|
||||
|
||||
# Checks whether a newer STOCK (stable) sing-box is available via the system
|
||||
# package manager. SYNC (quick call → stays on the synchronous component_action
|
||||
# path). Graceful on an unreachable feed / parse failure: echoes
|
||||
# {"success":false,"message":"..."} and returns non-zero. NEVER exits.
|
||||
#
|
||||
# Output (STABLE, mirrors updates_check_sing_box_extended):
|
||||
# {"success":true,"current_version":"...","latest_version":"...",
|
||||
# "status":"latest"|"outdated"|"not_installed"}
|
||||
updates_check_sing_box_stable() {
|
||||
local current_version candidate cur_semver cand_semver status
|
||||
|
||||
# Refresh the package index so the candidate version reflects the feed.
|
||||
# Best-effort: a failure here just means we compare against whatever index
|
||||
# is cached; the candidate-empty branch below reports the unreachable feed.
|
||||
if updates_pkg_is_apk; then
|
||||
apk update </dev/null >/dev/null 2>&1 || true
|
||||
else
|
||||
opkg update </dev/null >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
candidate="$(updates_pkg_candidate_version "sing-box")"
|
||||
if [ -z "$candidate" ]; then
|
||||
echo "{\"success\":false,\"message\":\"Could not determine the stock sing-box version from the package feed (feed unreachable or package not found)\"}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# sing-box absent → not_installed (no running binary to compare).
|
||||
if ! command -v sing-box >/dev/null 2>&1; then
|
||||
echo "{\"success\":true,\"current_version\":\"not installed\",\"latest_version\":\"$candidate\",\"status\":\"not_installed\"}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
current_version="$(get_sing_box_version)"
|
||||
|
||||
# Compare on the leading semver only (drop any "-r1"/"-extended-..." suffix)
|
||||
# so the sort -V based >= test in is_min_package_version is well-defined.
|
||||
cur_semver="${current_version%%-*}"
|
||||
cand_semver="${candidate%%-*}"
|
||||
|
||||
if is_min_package_version "$cur_semver" "$cand_semver"; then
|
||||
status="latest"
|
||||
else
|
||||
status="outdated"
|
||||
fi
|
||||
|
||||
echo "{\"success\":true,\"current_version\":\"$current_version\",\"latest_version\":\"$candidate\",\"status\":\"$status\"}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Checks whether a newer NetShift release is available on GitHub. ON-DEMAND
|
||||
# (the "Check for updates" button) — mirrors the sing-box cores so get_system_info
|
||||
# never touches the network. SYNC (quick call → component_action path). Graceful
|
||||
# on an unreachable/rate-limited API: echoes {"success":false,"message":"..."}
|
||||
# and returns non-zero. NEVER exits (runs via component_action → JSON + rc).
|
||||
#
|
||||
# Output (mirrors updates_check_sing_box_stable):
|
||||
# {"success":true,"current_version":"...","latest_version":"...",
|
||||
# "status":"latest"|"outdated"}
|
||||
#
|
||||
# v-normalization: a single leading "v" is stripped from BOTH the installed
|
||||
# version and the GitHub tag before comparing (task-028 dropped the v from the
|
||||
# build, but a v-tagged release would still break a raw compare). The compare is
|
||||
# on the leading semver (drop any "-..." suffix) via the same sort -V based
|
||||
# is_min_package_version the cores use.
|
||||
updates_check_netshift() {
|
||||
local current_version latest cur_norm latest_norm cur_semver latest_semver status
|
||||
|
||||
current_version="$NETSHIFT_VERSION"
|
||||
|
||||
# Dev/unstamped build: the placeholder __COMPILED_VERSION_VARIABLE__ contains
|
||||
# "COMPILED" and is not a real semver. Report it honestly as "latest" (a dev
|
||||
# build is never "outdated"; the UI also guards dev separately) and still fetch
|
||||
# the real latest tag for display.
|
||||
case "$current_version" in
|
||||
*"$tag"*) status="latest" ;;
|
||||
*COMPILED*)
|
||||
latest="$(updates_netshift_latest_tag)"
|
||||
if [ -z "$latest" ]; then
|
||||
echo "{\"success\":false,\"message\":\"Could not determine the latest NetShift release (GitHub API unreachable or rate-limited)\"}"
|
||||
return 1
|
||||
fi
|
||||
echo "{\"success\":true,\"current_version\":\"$current_version\",\"latest_version\":\"$latest\",\"status\":\"latest\"}"
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "{\"success\":true,\"current_version\":\"$current_version\",\"latest_version\":\"$tag\",\"status\":\"$status\"}"
|
||||
latest="$(updates_netshift_latest_tag)"
|
||||
if [ -z "$latest" ]; then
|
||||
echo "{\"success\":false,\"message\":\"Could not determine the latest NetShift release (GitHub API unreachable or rate-limited)\"}"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Strip a single leading "v" from both sides (no-op if absent), then compare
|
||||
# on the leading semver only.
|
||||
cur_norm="${current_version#v}"
|
||||
latest_norm="${latest#v}"
|
||||
cur_semver="${cur_norm%%-*}"
|
||||
latest_semver="${latest_norm%%-*}"
|
||||
|
||||
if is_min_package_version "$cur_semver" "$latest_semver"; then
|
||||
status="latest"
|
||||
else
|
||||
status="outdated"
|
||||
fi
|
||||
|
||||
echo "{\"success\":true,\"current_version\":\"$current_version\",\"latest_version\":\"$latest\",\"status\":\"$status\"}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# ── NetShift self-update (Component Manager, task-017) ──────────────
|
||||
#
|
||||
# Variant A: a targeted package upgrade (download the release .ipk/.apk from
|
||||
# GitHub and pkg_install them) — NOT install.sh (interactive). Runs as the async
|
||||
# worker `component_action netshift self_update`.
|
||||
#
|
||||
# Public wrapper — EXACTLY mirrors the updates_install_sing_box_extended epilogue
|
||||
# (single cleanup path): reset heal flags → ensure GitHub connectivity (preflight
|
||||
# + self-heal) → run the private core capturing JSON to a tmpfs file + rc →
|
||||
# ALWAYS updates_restore_after_swap → re-emit the JSON → return rc. No early
|
||||
# return skips the restore; no trap needed.
|
||||
updates_self_update_netshift() {
|
||||
local rc out json
|
||||
|
||||
UPDATES_HEAL_RESOLV_REPLACED=0
|
||||
UPDATES_HEAL_REDIRECT_DOWN=0
|
||||
|
||||
if ! updates_ensure_connectivity "extended"; then
|
||||
# Heal failed BEFORE anything was touched: NetShift is left fully intact.
|
||||
updates_restore_after_swap
|
||||
updates_log "Aborting NetShift self-update: GitHub unreachable and self-heal failed (NetShift left intact)" "error"
|
||||
echo '{"success":false,"message":"GitHub unreachable and self-heal failed; self-update aborted (NetShift left intact)"}'
|
||||
return 1
|
||||
fi
|
||||
|
||||
out="/tmp/netshift-selfupdate-result.$$"
|
||||
_updates_self_update_netshift_core >"$out" 2>/dev/null
|
||||
rc=$?
|
||||
json="$(cat "$out" 2>/dev/null)"
|
||||
rm -f "$out" 2>/dev/null
|
||||
|
||||
updates_restore_after_swap
|
||||
|
||||
[ -n "$json" ] && printf '%s\n' "$json"
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
# Resolve a URL's HTTP redirect target via curl WITHOUT hitting the rate-limited
|
||||
# API or downloading the body. Echoes the redirect URL (empty if curl absent or
|
||||
# no redirect). Stubbable in tests.
|
||||
updates_github_resolve_redirect() {
|
||||
local url="$1"
|
||||
command -v curl >/dev/null 2>&1 || return 1
|
||||
curl -sI -o /dev/null -w '%{redirect_url}' --connect-timeout 5 -m 15 -A 'netshift-updater' "$url" 2>/dev/null
|
||||
}
|
||||
|
||||
# Echoes the GitHub latest-release tag for NetShift (e.g. "0.8.8"), or nothing.
|
||||
# PRIMARY: resolve the uralgit.ru frontend redirect of /releases/latest — it
|
||||
# 303s to /releases/tag/<tag>. That frontend is NOT the 60/hour-per-IP
|
||||
# api.github.com, so it sidesteps the anonymous rate limit entirely (the common
|
||||
# failure on CGNAT / shared-IP / shared-VPN-egress routers). FALLBACK: the
|
||||
# uralgit.ru API release object parsed with jq (task-047) so a curl-less box or a
|
||||
# changed-redirect still degrades gracefully instead of hard-failing.
|
||||
# jq is format-independent (minified or pretty); a field-positional grep|cut
|
||||
# grabbed the wrong key on minified JSON, causing a false "outdated".
|
||||
# Bare tag on success / non-zero otherwise (contract consumed by
|
||||
# updates_check_netshift and the self-update worker).
|
||||
updates_netshift_latest_tag() {
|
||||
local response tag redirect
|
||||
|
||||
# PRIMARY: uralgit.ru/<repo>/releases/latest 303-redirects to
|
||||
# /releases/tag/<tag>. Parse with case/param-expansion (no Oniguruma).
|
||||
redirect="$(updates_github_resolve_redirect "$NETSHIFT_REPO_RELEASES_LATEST_URL")"
|
||||
case "$redirect" in
|
||||
*/releases/tag/*)
|
||||
tag="${redirect##*/releases/tag/}"
|
||||
case "$tag" in '' | */*) tag="" ;; esac
|
||||
;;
|
||||
*) tag="" ;;
|
||||
esac
|
||||
if [ -n "$tag" ]; then
|
||||
printf '%s' "$tag"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# FALLBACK: api.github.com (rate-limited) parsed with jq.
|
||||
response="$(updates_http_get_once "$NETSHIFT_RELEASE_API_URL" "")"
|
||||
if [ -z "$response" ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
tag="$(printf '%s' "$response" | jq -r '.tag_name // empty' 2>/dev/null)"
|
||||
[ -n "$tag" ] || return 1
|
||||
printf '%s' "$tag"
|
||||
}
|
||||
|
||||
# Echo the deterministic release asset filename for a package + tag + ext.
|
||||
# ipk core/luci carry "-r1-all"; apk core/luci carry "-r1"; the i18n package
|
||||
# carries neither suffix (just "<pkg>-<tag>.<ext>"). Single source of the asset
|
||||
# naming pattern so it lives in one place, not scattered.
|
||||
updates_netshift_asset_filename() {
|
||||
local pkg="$1" tag="$2" ext="$3"
|
||||
case "$pkg" in
|
||||
"$UPDATES_NETSHIFT_PKG_I18N_RU") printf '%s-%s.%s' "$pkg" "$tag" "$ext" ;;
|
||||
*)
|
||||
if [ "$ext" = "ipk" ]; then
|
||||
printf '%s-%s-r1-all.%s' "$pkg" "$tag" "$ext"
|
||||
else
|
||||
printf '%s-%s-r1.%s' "$pkg" "$tag" "$ext"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Downloads the NetShift release assets for the active package manager into $dir.
|
||||
# Echoes nothing; returns 0 if at least the core "netshift" package was
|
||||
# downloaded, non-zero otherwise.
|
||||
# PRIMARY: resolve the latest tag (redirect-based, rate-limit-free) and build the
|
||||
# deterministic github.com/<repo>/releases/download/<tag>/<asset> URLs — the
|
||||
# CDN 302 is followed by updates_download_to_file (curl -L / wget both follow it).
|
||||
# FALLBACK: if the tag can't be resolved, scrape the api.github.com release JSON
|
||||
# for .ipk/.apk URLs (busybox grep -o) as before, so a curl-less box still works.
|
||||
_updates_self_update_download_assets() {
|
||||
local dir="$1"
|
||||
local response ext pattern url filename dest attempt got_core=0
|
||||
local tag pkg
|
||||
|
||||
if updates_pkg_is_apk; then
|
||||
ext="apk"
|
||||
else
|
||||
ext="ipk"
|
||||
fi
|
||||
|
||||
tag="$(updates_netshift_latest_tag)"
|
||||
if [ -n "$tag" ]; then
|
||||
# Direct deterministic asset URLs (no API). Core + luci always; the RU
|
||||
# i18n package only if already installed.
|
||||
for pkg in "$UPDATES_NETSHIFT_PKG_CORE" "$UPDATES_NETSHIFT_PKG_LUCI" "$UPDATES_NETSHIFT_PKG_I18N_RU"; do
|
||||
if [ "$pkg" = "$UPDATES_NETSHIFT_PKG_I18N_RU" ]; then
|
||||
updates_pkg_is_installed "$UPDATES_NETSHIFT_PKG_I18N_RU" || continue
|
||||
fi
|
||||
filename="$(updates_netshift_asset_filename "$pkg" "$tag" "$ext")"
|
||||
url="$NETSHIFT_REPO_RELEASES_DOWNLOAD_BASE/$tag/$filename"
|
||||
dest="$dir/$filename"
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 3 ]; do
|
||||
if updates_download_to_file "$url" "$dest"; then
|
||||
break
|
||||
fi
|
||||
rm -f "$dest" 2>/dev/null
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
if [ "$pkg" = "$UPDATES_NETSHIFT_PKG_CORE" ] && [ -s "$dest" ]; then
|
||||
got_core=1
|
||||
fi
|
||||
done
|
||||
[ "$got_core" -eq 1 ]
|
||||
return $?
|
||||
fi
|
||||
|
||||
# FALLBACK: scrape the API release JSON for direct asset URLs.
|
||||
response="$(updates_http_get_once "$NETSHIFT_RELEASE_API_URL" "")"
|
||||
if [ -z "$response" ]; then
|
||||
return 1
|
||||
fi
|
||||
pattern="https://[^\"[:space:]]*\.${ext}"
|
||||
|
||||
# Iterate the matching browser_download_url values. Only keep assets whose
|
||||
# filename starts with one of the NetShift package-name prefixes; the RU
|
||||
# i18n package is kept ONLY if already installed.
|
||||
printf '%s' "$response" | grep -o "$pattern" | while read -r url; do
|
||||
filename="$(basename "$url")"
|
||||
case "$filename" in
|
||||
"$UPDATES_NETSHIFT_PKG_CORE"* | "$UPDATES_NETSHIFT_PKG_LUCI"*) ;;
|
||||
"$UPDATES_NETSHIFT_PKG_I18N_RU"*)
|
||||
updates_pkg_is_installed "$UPDATES_NETSHIFT_PKG_I18N_RU" || continue
|
||||
;;
|
||||
*) continue ;;
|
||||
esac
|
||||
|
||||
dest="$dir/$filename"
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 3 ]; do
|
||||
if updates_download_to_file "$url" "$dest"; then
|
||||
break
|
||||
fi
|
||||
rm -f "$dest" 2>/dev/null
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
done
|
||||
|
||||
# Verify the core package landed (the subshell-piped loop can't set a parent
|
||||
# var, so re-check the directory contents here).
|
||||
if ls "$dir/$UPDATES_NETSHIFT_PKG_CORE"* >/dev/null 2>&1; then
|
||||
got_core=1
|
||||
fi
|
||||
[ "$got_core" -eq 1 ]
|
||||
}
|
||||
|
||||
# Private core of the self-update. Runs NON-interactively; every variable local.
|
||||
# Echoes a single JSON object; NEVER exits (returns non-zero on recoverable
|
||||
# failure so the wrapper still runs the restore epilogue).
|
||||
_updates_self_update_netshift_core() {
|
||||
local installed latest pkg file_path candidate_file
|
||||
local core_installed core_installed_semver latest_semver
|
||||
local backup_made=0
|
||||
|
||||
installed="$NETSHIFT_VERSION"
|
||||
|
||||
latest="$(updates_netshift_latest_tag)"
|
||||
if [ -z "$latest" ]; then
|
||||
updates_log "Self-update: could not determine the latest NetShift release tag" "error"
|
||||
echo '{"success":false,"message":"Could not determine the latest NetShift release (GitHub API unreachable or rate-limited)"}'
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Idempotent defense: compare ignoring a leading "v" so "v0.8.1" vs "0.8.1"
|
||||
# still match (the UI also gates on the "outdated" status).
|
||||
if [ "${installed#v}" = "${latest#v}" ]; then
|
||||
updates_log "Self-update: NetShift already at the latest version ($installed)"
|
||||
echo "{\"success\":true,\"message\":\"Already up to date\",\"version\":\"$installed\"}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Minimal backup: /etc/config/netshift to tmpfs (conffiles normally preserve
|
||||
# it; this is the defensive belt).
|
||||
rm -rf "$UPDATES_NETSHIFT_DOWNLOAD_DIR" 2>/dev/null
|
||||
if ! mkdir -p "$UPDATES_NETSHIFT_DOWNLOAD_DIR"; then
|
||||
updates_log "Self-update: failed to create download directory" "error"
|
||||
echo '{"success":false,"message":"Failed to create the self-update download directory"}'
|
||||
return 1
|
||||
fi
|
||||
mkdir -p "$(dirname "$UPDATES_NETSHIFT_CONFIG_BACKUP")" 2>/dev/null || true
|
||||
if [ -f "$NETSHIFT_CONFIG" ]; then
|
||||
if cp -p "$NETSHIFT_CONFIG" "$UPDATES_NETSHIFT_CONFIG_BACKUP" 2>/dev/null; then
|
||||
backup_made=1
|
||||
else
|
||||
updates_log "Self-update: failed to back up $NETSHIFT_CONFIG (continuing; conffiles preserve it)" "warn"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Download the release assets (.ipk/.apk) for this package manager.
|
||||
updates_log "Self-update: downloading NetShift $latest release packages"
|
||||
if ! _updates_self_update_download_assets "$UPDATES_NETSHIFT_DOWNLOAD_DIR"; then
|
||||
rm -rf "$UPDATES_NETSHIFT_DOWNLOAD_DIR" 2>/dev/null
|
||||
updates_log "Self-update: failed to download the NetShift release packages" "error"
|
||||
echo '{"success":false,"message":"Failed to download the NetShift release packages (GitHub unreachable or no matching assets)"}'
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Install core, then LuCI app, then RU i18n if applicable (already filtered
|
||||
# to "installed-only" at download time). NON-interactive. The netshift
|
||||
# package replaces /usr/bin/netshift (this very script) — busybox ash has
|
||||
# already read the whole script into memory, so the in-flight worker and the
|
||||
# subsequent updates_write_finished_job_state complete from memory. We MUST
|
||||
# NOT re-exec /usr/bin/netshift after this install (no updates_restart that
|
||||
# re-runs the CLI; only /etc/init.d/netshift restart, which spawns a fresh
|
||||
# process that may safely load the new binary).
|
||||
for pkg in "$UPDATES_NETSHIFT_PKG_CORE" "$UPDATES_NETSHIFT_PKG_LUCI" "$UPDATES_NETSHIFT_PKG_I18N_RU"; do
|
||||
file_path=""
|
||||
for candidate_file in "$UPDATES_NETSHIFT_DOWNLOAD_DIR/$pkg"*; do
|
||||
if [ -f "$candidate_file" ]; then
|
||||
file_path="$candidate_file"
|
||||
break
|
||||
fi
|
||||
done
|
||||
[ -n "$file_path" ] || continue
|
||||
|
||||
updates_log "Self-update: installing $(basename "$file_path")"
|
||||
if ! updates_pkg_install_file "$file_path"; then
|
||||
# The core is the critical package; if it fails, surface the failure.
|
||||
# conffiles preserve /etc/config/netshift; restore defensively below.
|
||||
if [ "$pkg" = "$UPDATES_NETSHIFT_PKG_CORE" ]; then
|
||||
_updates_self_update_restore_config "$backup_made"
|
||||
rm -rf "$UPDATES_NETSHIFT_DOWNLOAD_DIR" 2>/dev/null
|
||||
updates_log "Self-update: failed to install the NetShift core package" "error"
|
||||
echo '{"success":false,"message":"Failed to install the NetShift core package; configuration preserved"}'
|
||||
return 1
|
||||
fi
|
||||
updates_log "Self-update: failed to install $pkg (non-critical; continuing)" "warn"
|
||||
fi
|
||||
done
|
||||
|
||||
# Verify-after-install for the CORE package (authoritative success signal).
|
||||
# opkg returns rc=0 for "already installed"/"up to date"/"Not downgrading",
|
||||
# so the install rc above is NOT trustworthy. RE-READ the installed version
|
||||
# and confirm it actually became the target before declaring success. apk's
|
||||
# equal-version no-overwrite quirk is caught by this same belt.
|
||||
core_installed="$(updates_pkg_installed_version "$UPDATES_NETSHIFT_PKG_CORE")"
|
||||
# Normalize with the SAME rules the version-decision uses: drop a leading "v"
|
||||
# and any "-rN"/"-suffix" so we compare semver-to-semver.
|
||||
core_installed_semver="${core_installed#v}"
|
||||
core_installed_semver="${core_installed_semver%%-*}"
|
||||
latest_semver="${latest#v}"
|
||||
latest_semver="${latest_semver%%-*}"
|
||||
|
||||
# The install took iff the installed semver equals the target, OR the
|
||||
# installed semver is now >= the target (is_min_package_version current
|
||||
# required → 0 when current >= required).
|
||||
if [ "$core_installed_semver" != "$latest_semver" ] \
|
||||
&& ! is_min_package_version "$core_installed_semver" "$latest_semver"; then
|
||||
_updates_self_update_restore_config "$backup_made"
|
||||
rm -rf "$UPDATES_NETSHIFT_DOWNLOAD_DIR" 2>/dev/null
|
||||
updates_log "Self-update: core package version did not change after install (package manager reported success but no upgrade occurred)" "error"
|
||||
echo '{"success":false,"message":"NetShift core package did not upgrade (package manager refused or no-op); configuration preserved"}'
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Defensive: if the config got clobbered/emptied, restore from the backup.
|
||||
_updates_self_update_restore_config "$backup_made"
|
||||
|
||||
# Success cleanup: drop the download dir and the config backup.
|
||||
rm -rf "$UPDATES_NETSHIFT_DOWNLOAD_DIR" 2>/dev/null
|
||||
[ "$backup_made" -eq 1 ] && rm -f "$UPDATES_NETSHIFT_CONFIG_BACKUP" 2>/dev/null
|
||||
|
||||
updates_log "Self-update: NetShift updated to $latest"
|
||||
echo "{\"success\":true,\"version\":\"$latest\",\"message\":\"NetShift updated to $latest\"}"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Restores /etc/config/netshift from the tmpfs backup IF the live file is missing
|
||||
# or empty (conffiles normally keep it; this is the defensive belt). $1 = 1 when
|
||||
# a backup was taken.
|
||||
_updates_self_update_restore_config() {
|
||||
local backup_made="$1"
|
||||
|
||||
[ "$backup_made" -eq 1 ] || return 0
|
||||
[ -f "$UPDATES_NETSHIFT_CONFIG_BACKUP" ] || return 0
|
||||
|
||||
if [ ! -s "$NETSHIFT_CONFIG" ]; then
|
||||
if cp -p "$UPDATES_NETSHIFT_CONFIG_BACKUP" "$NETSHIFT_CONFIG" 2>/dev/null; then
|
||||
updates_log "Self-update: restored $NETSHIFT_CONFIG from backup (live file was missing/empty)" "warn"
|
||||
else
|
||||
updates_log "Self-update: FAILED to restore $NETSHIFT_CONFIG from backup" "error"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# Dispatcher for component-related actions.
|
||||
component_action() {
|
||||
local component="$1"
|
||||
@ -1283,6 +1932,24 @@ component_action() {
|
||||
sing_box:check_update)
|
||||
updates_check_sing_box_extended
|
||||
;;
|
||||
sing_box:check_update_stable)
|
||||
updates_check_sing_box_stable
|
||||
;;
|
||||
netshift:check_update)
|
||||
updates_check_netshift
|
||||
;;
|
||||
netshift:self_update)
|
||||
updates_self_update_netshift
|
||||
;;
|
||||
subscription:clear_cache)
|
||||
# Worker lives in bin/netshift (where subscription_update + the cache-path
|
||||
# builders + SUBSCRIPTION_CACHE_FOLDER are in scope). updater.sh is sourced
|
||||
# by bin/netshift, and the async fork re-execs "$0" component_action ...,
|
||||
# so the function is always defined when this arm dispatches. Reachable via
|
||||
# BOTH the sync `component_action subscription clear_cache` and the async
|
||||
# component_action_async/component_action_status paths.
|
||||
subscription_clear_cache_and_redownload
|
||||
;;
|
||||
*)
|
||||
echo '{"success":false,"message":"Unknown component action"}'
|
||||
return 1
|
||||
|
||||
@ -9,7 +9,10 @@
|
||||
# docker compose -f tests/docker-compose.yml run --rm netshift-test <test-name>
|
||||
#
|
||||
# Test names: all, deps, syntax, config, helpers, jq, cm, sb, nft,
|
||||
# diagnostics, subscription, rejected, jobstate, selfheal
|
||||
# nftv6, selmark, isolation, monfd, unsupported, textlist, diagnostics, subscription, fastest, insecure, rejected,
|
||||
# jobstate, selfheal, dnsdetour, suburlopt, globalproxy, stablecheck,
|
||||
# extcheck, netshiftcheck, latesttag, ghredirect, selfupdate,
|
||||
# backupguard
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
|
||||
services:
|
||||
|
||||
4532
tests/entrypoint.sh
4532
tests/entrypoint.sh
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user