Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1267d20fb8 | ||
|
|
35f697ed08 | ||
|
|
d0fb6befb1 | ||
|
|
81c96019b5 | ||
|
|
baed8ff8f2 | ||
|
|
f80fb4dd1b | ||
|
|
b71b793681 | ||
|
|
61c87ad1d9 | ||
|
|
4dee508e12 | ||
|
|
76da5134ef | ||
|
|
4c630c9a13 | ||
|
|
d8dbefcd07 | ||
|
|
974208fc05 | ||
|
|
2eb71e8244 | ||
|
|
668cccbf24 | ||
|
|
4ea4585402 | ||
|
|
dc6d102473 | ||
|
|
683afc0a47 | ||
|
|
2c3e20512e | ||
|
|
51b2f04672 | ||
|
|
f190c8251e | ||
|
|
1945404eaa | ||
|
|
6476722372 | ||
|
|
4078334d85 | ||
|
|
0a6689b29e | ||
|
|
ef22167b1a | ||
|
|
cbda0fee0a | ||
|
|
7234817adb | ||
|
|
f1c36d6eea | ||
|
|
bb21ceb7f5 | ||
|
|
a8970b8ace | ||
|
|
4996bc0984 | ||
|
|
a0de597d69 | ||
|
|
544da29863 | ||
|
|
daaa0fda41 | ||
|
|
56a276bcc1 | ||
|
|
754bbcf1fa | ||
|
|
63e6b709f8 | ||
|
|
8612b0a9e9 | ||
|
|
96d9cfaa63 | ||
|
|
3c7536dba0 | ||
|
|
3c92e1cbfd | ||
|
|
bcc9df9282 | ||
|
|
ee3641fe45 | ||
|
|
439f62238f | ||
|
|
d971eb85ee | ||
|
|
a0f6083e28 | ||
|
|
77369aedfe | ||
|
|
515ae6d1b7 | ||
|
|
a2ffbb1292 | ||
|
|
1746d4d0ef | ||
|
|
f86501bf77 | ||
|
|
eccfc6136c | ||
|
|
244b7c4199 | ||
|
|
a8ef887c56 | ||
|
|
8fd5c52488 | ||
|
|
32e8f8ff0b | ||
|
|
c562579ef3 | ||
|
|
6f89acbae7 | ||
|
|
88a82c7297 | ||
|
|
a8f2b0f068 | ||
|
|
0b32a6d58b | ||
|
|
893fdc500c | ||
|
|
02c266188f | ||
|
|
024e9308c9 | ||
|
|
eab1db2c3f | ||
|
|
22d7161c08 | ||
|
|
24c5a1615d | ||
|
|
4492f0599c | ||
|
|
bc2b53069a | ||
|
|
c257d6c5cc | ||
|
|
225cce5397 | ||
|
|
84d2766592 | ||
|
|
33f940c2fb | ||
|
|
a57717dabb | ||
|
|
129e31fbdc | ||
|
|
4f0618515e | ||
|
|
fd698162c9 | ||
|
|
ffa78d67bc | ||
|
|
61e51495c3 | ||
|
|
bfe71cd1dd | ||
|
|
9b3644becb | ||
|
|
0a8bdbaf46 | ||
|
|
ebe2e7807b | ||
|
|
c1e1b17a61 | ||
|
|
782770f306 | ||
|
|
8980a25a59 |
+290
-249
@@ -1,51 +1,62 @@
|
||||
# Shater v0.2 — build the 4-package signed opkg feed and publish it as a rolling
|
||||
# Gitea release consumable as an `src/gz` feed.
|
||||
# Shater v0.2 — build the 4-package signed **apk** feed and publish it as
|
||||
# per-arch Gitea releases consumable as an apk repository.
|
||||
#
|
||||
# WHAT CHANGED FROM v0.1
|
||||
# v0.1 shipped 3 packages: xrayctl (SDK-compiled Go) + shater-core +
|
||||
# luci-app-shater (hand-packed data .ipk). v0.2 collapses the runtime into ONE
|
||||
# forked binary and ships 4 packages, all built the canonical SDK way:
|
||||
# WHAT WE SHIP
|
||||
# ONE forked binary plus its OpenWrt glue, 4 packages, all built the canonical
|
||||
# SDK way:
|
||||
# - shaterd PREBUILT static-musl + SPA-embedded + UPX binary. Built
|
||||
# OUT OF TREE by scripts/build-shaterd.sh (Go + Node + UPX)
|
||||
# and staged into openwrt/shaterd/files/ BEFORE the SDK
|
||||
# build; the openwrt/shaterd package just $(INSTALL_BIN)s
|
||||
# the arch-matched artifact. (arch-specific .ipk)
|
||||
# the arch-matched artifact. (arch-specific .apk)
|
||||
# - shater-core data glue, PKGARCH=all
|
||||
# - luci-app-shater LuCI thin launcher, PKGARCH=all (uses feeds/luci/luci.mk)
|
||||
# - byedpi ciadpi, C cross-compiled from source by the SDK (arch-specific)
|
||||
#
|
||||
# TARGET HARDWARE / ARCH MATRIX
|
||||
# x86_64 -> the QEMU testbed VM (generic x86-64).
|
||||
# aarch64_cortex-a53 -> BOTH production routers (BPI-R3 + BPI-R4, mediatek/filogic).
|
||||
# aarch64_cortex-a53 -> BOTH production routers (BPI-R3 mini + BPI-R4,
|
||||
# mediatek/filogic), both on 25.12 with apk-tools 3.
|
||||
# Only shaterd + byedpi are arch-specific; shater-core + luci-app-shater are
|
||||
# PKGARCH=all, so one build of each covers every device. opkg filters by
|
||||
# Architecture at install time, so a single combined feed URL serves all.
|
||||
# PKGARCH=all, so one build of each covers every device — but the RELEASES
|
||||
# are still per-arch (see the release-apk job for why).
|
||||
#
|
||||
# FEED SIGNING (opkg / usign — OpenWrt 24.10 is opkg, not apk; apk lands at 25.12)
|
||||
# The feed index (Packages) is usign-signed with the SECRET key in the Gitea
|
||||
# repo secret KEY_BUILD; routers verify it with the committed public key
|
||||
# dist/shater-feed.pub (fingerprint 5ac4b177689cb8e0). Do NOT regenerate the
|
||||
# key — that invalidates every deployed router's trust.
|
||||
# FORMAT: apk ONLY (25.12+)
|
||||
# The fleet runs OpenWrt/ImmortalWrt 25.12, where opkg is replaced by Alpine
|
||||
# apk (.apk files, binary packages.adb index, EC keys in /etc/apk/keys/). The
|
||||
# old .ipk lane was removed in 2026-07 (docs-shater/DECISIONS.md D22): no
|
||||
# device we serve has an opkg binary at all, so building and signing a second
|
||||
# feed served nobody.
|
||||
#
|
||||
# FEED SIGNING (EC / apk)
|
||||
# packages.adb is signed with the EC (prime256v1) SECRET key in the Gitea repo
|
||||
# secret KEY_APK; routers verify it with the committed public key
|
||||
# dist/shater-apk.pem (ci/gen-apk-key.sh). Do NOT regenerate the key — that
|
||||
# invalidates every deployed router's trust.
|
||||
#
|
||||
# AUTO-RELEASE
|
||||
# push a tag `vX.Y.Z` -> versioned release. workflow_dispatch / (optional) main
|
||||
# -> rolling `latest` pre-release (always-fresh feed). Publish uses the Gitea
|
||||
# API via curl (ci/gitea-release.sh) — no external action needed.
|
||||
# push a tag `vX.Y.Z` -> versioned per-arch releases `apk-vX.Y.Z-<arch>`.
|
||||
# workflow_dispatch -> rolling per-arch `apk-latest-<arch>` (always-fresh
|
||||
# feed). Publish uses the Gitea API via curl (ci/gitea-release.sh) — no
|
||||
# external action needed. NOTE: the apk release tags deliberately do NOT start
|
||||
# with `v` so publishing them cannot re-trigger this workflow's `v*` filter.
|
||||
#
|
||||
# APK LANE (25.12+, ADDITIVE — T2)
|
||||
# The fleet is migrating to BananaWRT 25.12-mtk-vendor (= ImmortalWrt 25.12
|
||||
# base), where opkg is replaced by Alpine apk (.apk, binary packages.adb
|
||||
# index, EC keys in /etc/apk/keys/). The `build-apk` + `release-apk` jobs
|
||||
# below build the SAME 4 packages through the ImmortalWrt 25.12 apk-SDK and
|
||||
# publish PER-ARCH apk repos as releases `apk-latest-<arch>` (rolling) /
|
||||
# `apk-<tag>-<arch>` (versioned). Per-arch because apk filenames carry no
|
||||
# architecture (shaterd-0.2.0-r1.apk would collide across arches in one flat
|
||||
# release) and apk fetches packages relative to the packages.adb URL.
|
||||
# Signed with the EC key in the Gitea secret KEY_APK; trust anchor
|
||||
# dist/shater-apk.pem (ci/gen-apk-key.sh). The usign/opkg lane above is
|
||||
# UNCHANGED and keeps serving the 24.10 fleet. NOTE: the apk release tags
|
||||
# deliberately do NOT start with `v` so publishing them cannot re-trigger
|
||||
# this workflow's `v*` tag filter.
|
||||
# PACKAGE VERSIONING (bug B4)
|
||||
# PKG_VERSION/PKG_RELEASE are NOT hand-written in the Makefiles any more. They
|
||||
# used to be, and nobody bumped them: v0.2.2…v0.2.6 all shipped as
|
||||
# `shaterd 0.2.0-r3` with different binaries inside, so `apk update` never saw
|
||||
# a new version and routers could not be updated at all. Now `ci/version.sh`
|
||||
# derives them from the git tag ONCE per job (the "Compute version" step,
|
||||
# exported via $GITHUB_ENV):
|
||||
# tag `vX.Y.Z` -> X.Y.Z-r1
|
||||
# anything else -> <nearest tag>-r<commits since it + 1>
|
||||
# and hands them to the SDK build as SHATER_PKG_VERSION/SHATER_PKG_RELEASE;
|
||||
# $SHATER_VERSION (the same numbers, plus the short sha off-tag) is stamped
|
||||
# into the binary's constant.Version. ci/sdk-build-apk.sh then ASSERTS that the
|
||||
# built .apk really carry that version, so the failure can never be silent
|
||||
# again. This is also why the build job checks out with fetch-depth: 0
|
||||
# — `git describe` needs tags and ancestry. `byedpi` is excluded: it keeps
|
||||
# upstream ByeDPI's own PKG_VERSION (see openwrt/byedpi/Makefile).
|
||||
|
||||
# CACHING (T3 — fast CI)
|
||||
# All caches use actions/cache pinned to v3.3.2: the LAST release speaking the
|
||||
@@ -63,14 +74,33 @@
|
||||
# (PKG_VERSION/PKG_HASH live there). Stale-safe: the buildroot verifies
|
||||
# PKG_HASH on every dl/ file and re-downloads on mismatch, so restore-keys
|
||||
# prefix fallback is allowed.
|
||||
# - Go module + build cache — key = hash of go.sum; shared by all 4 build
|
||||
# - Go module + build cache — key = hash of go.sum; shared by both build
|
||||
# jobs (each builds both GOARCHes).
|
||||
# - panel/node_modules — key = hash of panel/package-lock.json, exact-only
|
||||
# (a lockfile change MUST miss); on hit build-shaterd.sh gets --fast.
|
||||
# - apt .deb archives for the apk lane's debian:bookworm host-deps
|
||||
# (.cache/apt) — key = hash of ci/sdk-build-apk.sh (the apt list is in it).
|
||||
# - usign binary (.cache/tools) — static helper, fixed key.
|
||||
|
||||
# - apt .deb archives for the debian:bookworm host-deps of the apk SDK
|
||||
# container (.cache/apt) — key = hash of ci/sdk-build-apk.sh (the apt list
|
||||
# is in it).
|
||||
# - SDK feeds/ git checkouts (.cache/feeds) — the single biggest recurring
|
||||
# cost: `scripts/feeds update -a` cloned base+packages+luci+routing+
|
||||
# telephony EVERY run (~7 min/job; github.com is ~1 MB/s from this
|
||||
# runner — run 51 evidence). The feeds dir is symlinked into the SDK
|
||||
# container from the workspace cache; `feeds update` on an existing clone
|
||||
# is a fast fetch+checkout of the pinned revs. Correctness-safe: update
|
||||
# always checks out feeds.conf's pins, and ci/sdk-build-apk.sh wipes the
|
||||
# cache + re-clones fresh if update ever fails on a cached checkout.
|
||||
# Key = lane + SDK release (shared across the two arch jobs — the same
|
||||
# release pins identical feed revs; the sequential runner means the second
|
||||
# arch restores what the first saved). restore-keys lets an SDK version
|
||||
# bump start from the old clones (git fetch delta, not re-clone).
|
||||
# Act_runner facts this design leans on (verified in run 51 logs):
|
||||
# - the cache backend works: restores/saves confirmed, hashFiles() works;
|
||||
# - docker images (debian:bookworm, runner-images) live on the PERSISTENT
|
||||
# host daemon — "Image is up to date" each run, no re-download;
|
||||
# - each actions/cache SAVE is followed by an exact 3-minute act_runner
|
||||
# stall (node process lingers; hit→no-save→no stall). Steady state saves
|
||||
# nothing, so adding cache entries is fine, but keys that change every
|
||||
# run (e.g. github.sha) would cost +3 min/entry/run — do NOT do that.
|
||||
name: release
|
||||
|
||||
on:
|
||||
@@ -88,41 +118,49 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: ${{ matrix.arch }}
|
||||
# ---------------------------------------------------------------------------
|
||||
# THE TEST GATE (2026-07-26). Everything below `needs:` this job, so a red test
|
||||
# stops the release instead of shipping with it.
|
||||
#
|
||||
# WHY IT IS A JOB HERE AND NOT JUST .gitea/workflows/test.yml: a separate
|
||||
# workflow cannot block another one — they run side by side and a red `test`
|
||||
# workflow would have published anyway. Only a `needs:` edge inside THIS
|
||||
# workflow is a gate. test.yml exists too, for fast feedback on `main`; both
|
||||
# call the same scripts/run-tests.sh so they cannot drift.
|
||||
#
|
||||
# WHAT WAS BROKEN: the release tract ran two `go test` invocations in total —
|
||||
# build-shaterd.sh's one-package buildtags check and check-router-tags.sh's
|
||||
# three named tests. 115 of the 116 test files under shater/** had never run in
|
||||
# CI (upstream's .github/workflows/test.yml triggers on branches this fork does
|
||||
# not have, and Gitea ignores .github/workflows entirely once .gitea/workflows
|
||||
# exists). TestDNSFilterRemoteBlocklistHTTPClient shipped red twice.
|
||||
#
|
||||
# WHAT IT COVERS: the whole suite under the SHIPPED build tags
|
||||
# (scripts/router-tags.sh) on linux — the two dimensions that were missing.
|
||||
# transport/wireguard compiles 1 test file without the tag set and 7 with it
|
||||
# (the AmneziaWG ones); shater/generate has 44 test files on linux against 32
|
||||
# elsewhere. Plus a -race pass and the panel's TypeScript tests. Details and
|
||||
# the named, reasoned exclusions are in scripts/run-tests.sh.
|
||||
test:
|
||||
name: test gate
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { arch: x86_64, sdk: x86_64-24.10.4 } # testbed VM (generic x86-64)
|
||||
- { arch: aarch64_cortex-a53, sdk: mediatek-filogic-24.10.4 } # BPI-R3 + BPI-R4 (mediatek/filogic)
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# scripts/build-shaterd.sh builds the engine via a go.mod
|
||||
# `replace => ./submodules/wireguard-go` (AmneziaWG fork), so that submodule
|
||||
# must be present or `go build` dies with "no such file or directory".
|
||||
# actions/checkout does not fetch submodules by default; init ONLY this one
|
||||
# (clients/apple+android are large and unused here).
|
||||
# go.mod `replace`s wireguard-go to ./submodules/wireguard-go, so without
|
||||
# this even `go list` fails. Same step/reason as in build-apk below.
|
||||
- name: Init wireguard-go submodule (awg)
|
||||
run: git submodule update --init --depth 1 submodules/wireguard-go
|
||||
|
||||
# Toolchain for scripts/build-shaterd.sh: Go (daemon), Node (Vite SPA), UPX.
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod # pins Go 1.24.7 (go.mod `go` line)
|
||||
cache: false # explicit actions/cache@v3.3.2 below (setup-go's
|
||||
# built-in cache uses the new API act_runner lacks)
|
||||
go-version-file: go.mod
|
||||
cache: false # explicit actions/cache@v3.3.2 below
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20' # Vite 5 needs Node 18+; 20 LTS
|
||||
|
||||
# ---- caches (see the header comment for keys + version pin rationale) ----
|
||||
# Same cache key as build-apk: this job runs first, so it warms the module
|
||||
# + build cache the SDK-lane build then restores. (v3.3.2 pin: see header.)
|
||||
- name: Cache Go modules + build cache
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
@@ -133,79 +171,36 @@ jobs:
|
||||
restore-keys: |
|
||||
go-
|
||||
|
||||
# Node 24, NOT the 20 build-apk uses for the SPA: panel's tests are
|
||||
# TypeScript run directly by `node --test`, and type stripping only exists
|
||||
# from 22.6 — on node 20 `npm test` dies before running a single case.
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Cache panel node_modules
|
||||
id: npm-cache
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: panel/node_modules
|
||||
key: npm-${{ hashFiles('panel/package-lock.json') }}
|
||||
# NO restore-keys: node_modules must exactly match the lockfile;
|
||||
# on any lockfile change this misses and `npm ci` runs fresh.
|
||||
|
||||
- name: Cache SDK dl/ (package sources)
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: .cache/dl
|
||||
key: dl-${{ hashFiles('openwrt/*/Makefile') }}
|
||||
restore-keys: |
|
||||
dl-
|
||||
- name: Panel tests
|
||||
run: bash scripts/run-panel-tests.sh
|
||||
|
||||
- name: Cache CI tools (usign)
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: .cache/tools
|
||||
key: tools-usign-v1
|
||||
|
||||
- name: Install UPX
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq upx-ucl
|
||||
|
||||
# Build the SPA-embedded, static-musl, UPX'd shaterd for BOTH arches and
|
||||
# stage dist/shaterd-<a>.upx into openwrt/shaterd/files/. MUST run before
|
||||
# the SDK package build (the openwrt/shaterd package installs the staged
|
||||
# artifact). VERSION is stamped into constant.Version. On an exact
|
||||
# node_modules cache hit, --fast skips the redundant `npm ci`.
|
||||
- name: Build & stage shaterd artifact
|
||||
env:
|
||||
NPM_CACHE_HIT: ${{ steps.npm-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ "${GITHUB_REF#refs/tags/}" != "$GITHUB_REF" ]; then
|
||||
V="${GITHUB_REF#refs/tags/}"
|
||||
else
|
||||
V="v0.2.0-dev"
|
||||
fi
|
||||
FAST=""
|
||||
if [ "${NPM_CACHE_HIT:-}" = "true" ]; then FAST="--fast"; fi
|
||||
echo "shaterd version: $V (npm cache hit: ${NPM_CACHE_HIT:-false})"
|
||||
bash scripts/build-shaterd.sh "$V" $FAST
|
||||
|
||||
# Compile the 4 packages through the arch-matched OpenWrt SDK and produce a
|
||||
# signed per-arch opkg feed (Packages + Packages.gz + Packages.sig + .ipk).
|
||||
- name: Build signed feed (SDK)
|
||||
env:
|
||||
KEY_BUILD: ${{ secrets.KEY_BUILD }}
|
||||
run: bash ci/build-feed.sh "${{ matrix.arch }}" "${{ matrix.sdk }}" "out/${{ matrix.arch }}"
|
||||
|
||||
- name: Show feed
|
||||
run: ls -l "out/${{ matrix.arch }}" && cat "out/${{ matrix.arch }}/Packages"
|
||||
|
||||
- name: Upload feed artifact
|
||||
# v4 uses an artifact backend Gitea Actions does not implement
|
||||
# (GHESNotSupportedError); v3 works on Gitea's act_runner.
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: shater-${{ matrix.arch }}
|
||||
path: out/${{ matrix.arch }}/*
|
||||
if-no-files-found: error
|
||||
- name: Go tests (shipped tags, linux, + race)
|
||||
run: bash scripts/run-tests.sh
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# APK lane (additive): the same 4 packages through the ImmortalWrt 25.12
|
||||
# apk-SDK for the 25.12/apk fleet (BananaWRT 25.12-mtk-vendor routers + the
|
||||
# future 25.12 VM). Produces a per-arch apk repo dir: *.apk + EC-signed
|
||||
# packages.adb + shater-apk.pem. Artifact prefix `apkfeed-` (NOT `shater-`)
|
||||
# so the opkg release job's `artifacts/shater-*` glob never picks these up.
|
||||
# Build the 4 packages through the ImmortalWrt 25.12 apk-SDK for the 25.12/apk
|
||||
# fleet (BPI-R3 mini on BananaWRT 25.12-mtk-vendor, BPI-R4 on OpenWrt 25.12,
|
||||
# and the testbed VM). Produces a per-arch apk repo dir: *.apk + EC-signed
|
||||
# packages.adb + shater-apk.pem, uploaded as the artifact `apkfeed-<arch>`.
|
||||
build-apk:
|
||||
name: apk ${{ matrix.arch }}
|
||||
# THE GATE EDGE. A red test skips this job, which leaves no artifact, which
|
||||
# (with the guards in release-apk) leaves nothing published.
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -218,8 +213,14 @@ jobs:
|
||||
- arch: aarch64_cortex-a53 # BPI-R3 mini (BananaWRT 25.12-mtk-vendor) + BPI-R4
|
||||
sdk_url: https://downloads.immortalwrt.org/releases/25.12.1/targets/mediatek/filogic/immortalwrt-sdk-25.12.1-mediatek-filogic_gcc-14.3.0_musl.Linux-x86_64.tar.zst
|
||||
steps:
|
||||
# fetch-depth: 0 — the package version is DERIVED from the git tag
|
||||
# (ci/version.sh: nearest `vX.Y.Z` + commits since it). The default
|
||||
# shallow checkout has neither tags nor ancestry, so `git describe` would
|
||||
# fail and every dispatch build would fall back to 0.0.0.
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# scripts/build-shaterd.sh builds the AmneziaWG-patched wireguard-go via a
|
||||
# go.mod `replace => ./submodules/wireguard-go`, so that submodule must be
|
||||
@@ -228,6 +229,13 @@ jobs:
|
||||
- name: Init wireguard-go submodule (awg)
|
||||
run: git submodule update --init --depth 1 submodules/wireguard-go
|
||||
|
||||
# THE version step (bug B4). One computation, used by both the binary
|
||||
# (constant.Version) and the three tag-versioned packages, exported to
|
||||
# every later step of this job:
|
||||
# tag vX.Y.Z -> X.Y.Z-r1 ; off-tag -> <last tag>-r<commits+1>
|
||||
- name: Compute version from git tag
|
||||
run: bash ci/version.sh --env >> "$GITHUB_ENV"
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
@@ -281,7 +289,9 @@ jobs:
|
||||
# mirror) — so even with a dead cache server this never wedges the run.
|
||||
- name: Compute SDK cache key
|
||||
id: sdkkey
|
||||
run: echo "tarball=$(basename '${{ matrix.sdk_url }}')" >> "$GITHUB_OUTPUT"
|
||||
run: |
|
||||
echo "tarball=$(basename '${{ matrix.sdk_url }}')" >> "$GITHUB_OUTPUT"
|
||||
echo "relver=$(echo '${{ matrix.sdk_url }}' | sed -n 's#.*/releases/\([^/]*\)/.*#\1#p')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Cache ImmortalWrt SDK tarball
|
||||
uses: actions/cache@v3.3.2
|
||||
@@ -289,25 +299,46 @@ jobs:
|
||||
path: .cache/sdk
|
||||
key: sdk-${{ steps.sdkkey.outputs.tarball }}
|
||||
|
||||
# feeds git checkouts (see header) — one entry shared by both apk arch
|
||||
# jobs of one ImmortalWrt release (identical feeds.conf.default pins).
|
||||
- name: Cache SDK feeds checkouts
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: .cache/feeds
|
||||
key: feeds-apk-${{ steps.sdkkey.outputs.relver }}
|
||||
restore-keys: |
|
||||
feeds-apk-
|
||||
|
||||
# D23 — the shipped tag set is a TRIMMED subset (scripts/router-tags.sh);
|
||||
# everything else in CI builds with the full upstream set, so without this
|
||||
# step the one combination we actually ship is never exercised. That is how
|
||||
# `with_gvisor` was trimmed while `with_wireguard` stayed and every shipped
|
||||
# binary answered a WireGuard node with "gVisor is not included in this
|
||||
# build" (2026-07-25). The check runs the declared-feature/tag comparison
|
||||
# and then constructs one node of every declared protocol through box.New
|
||||
# UNDER THE SHIPPED TAGS. It runs before the artifact build so a tag trim
|
||||
# that breaks a feature fails the release instead of shipping.
|
||||
- name: Verify the shipped build-tag set (D23)
|
||||
run: bash scripts/check-router-tags.sh
|
||||
|
||||
- name: Install UPX
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq upx-ucl
|
||||
|
||||
# Same artifact-order contract as the opkg lane: the SPA-embedded shaterd
|
||||
# binary is built OUT of the SDK and staged before the package build.
|
||||
# Artifact-order contract: the SPA-embedded shaterd binary is built OUT of
|
||||
# the SDK and staged into openwrt/shaterd/files/ BEFORE the package build
|
||||
# (the openwrt/shaterd package only installs the staged artifact).
|
||||
# $SHATER_VERSION (from the version step above) is stamped into
|
||||
# constant.Version, so the binary and the package agree. On an exact
|
||||
# node_modules cache hit, --fast skips the redundant `npm ci`.
|
||||
- name: Build & stage shaterd artifact
|
||||
env:
|
||||
NPM_CACHE_HIT: ${{ steps.npm-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ "${GITHUB_REF#refs/tags/}" != "$GITHUB_REF" ]; then
|
||||
V="${GITHUB_REF#refs/tags/}"
|
||||
else
|
||||
V="v0.2.0-dev"
|
||||
fi
|
||||
FAST=""
|
||||
if [ "${NPM_CACHE_HIT:-}" = "true" ]; then FAST="--fast"; fi
|
||||
echo "shaterd version: $V (npm cache hit: ${NPM_CACHE_HIT:-false})"
|
||||
bash scripts/build-shaterd.sh "$V" $FAST
|
||||
echo "shaterd version: $SHATER_VERSION / package ${SHATER_PKG_VERSION}-r${SHATER_PKG_RELEASE} (npm cache hit: ${NPM_CACHE_HIT:-false})"
|
||||
bash scripts/build-shaterd.sh $FAST
|
||||
|
||||
# Compile the 4 packages as .apk through the ImmortalWrt 25.12 SDK and
|
||||
# sign the per-arch packages.adb with the EC key (secret KEY_APK).
|
||||
@@ -330,116 +361,34 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Publish once both arches are built. Rolling `latest` on dispatch, a versioned
|
||||
# release on a `vX.Y.Z` tag. Self-contained (curl -> Gitea API).
|
||||
release:
|
||||
name: release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download all arch feeds
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Assemble release assets
|
||||
id: assets
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p release
|
||||
# For each downloaded arch feed: one ready-to-serve tarball + loose ipks.
|
||||
for d in artifacts/shater-*; do
|
||||
[ -d "$d" ] || continue
|
||||
arch="${d#artifacts/shater-}"
|
||||
tar -C "$d" -czf "release/shater-feed-${arch}.tar.gz" .
|
||||
# loose .ipk for direct `opkg install <url>` (dedupe shared _all ipks by name)
|
||||
for ipk in "$d"/*.ipk; do
|
||||
[ -e "$ipk" ] || continue
|
||||
cp -n "$ipk" "release/$(basename "$ipk")"
|
||||
done
|
||||
done
|
||||
# ship the feed's public key so routers can verify (see docs-shater/INSTALL.md)
|
||||
cp -f dist/shater-feed.pub release/shater-feed.pub
|
||||
ls -l release
|
||||
echo "count=$(ls release | wc -l)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# restore the prebuilt usign binary (skips apt + cmake + clone + build)
|
||||
- name: Cache CI tools (usign)
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: .cache/tools
|
||||
key: tools-usign-v1
|
||||
|
||||
- name: Install usign (feed signer)
|
||||
run: bash ci/install-usign.sh
|
||||
|
||||
- name: Build & sign combined opkg feed index
|
||||
# One Packages/Packages.gz over ALL loose .ipk (every arch + arch=all),
|
||||
# with basename Filenames. opkg filters by Architecture, so a single
|
||||
# release URL serves every device: BPI routers pick aarch64_cortex-a53 +
|
||||
# all, the x86 testbed picks x86_64 + all. Signed with KEY_BUILD so
|
||||
# routers keep check_signature on. This is what makes the release directly
|
||||
# consumable as an `src/gz` feed (see docs-shater/INSTALL.md).
|
||||
env:
|
||||
KEY_BUILD: ${{ secrets.KEY_BUILD }}
|
||||
run: bash ci/make-index.sh release
|
||||
|
||||
- name: Determine release identity
|
||||
id: rel
|
||||
run: |
|
||||
set -eu
|
||||
if [ "${GITHUB_REF#refs/tags/}" != "$GITHUB_REF" ]; then
|
||||
echo "tag=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT"
|
||||
echo "name=shater ${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "rolling=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "tag=latest" >> "$GITHUB_OUTPUT"
|
||||
echo "name=shater latest (main)" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "rolling=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Publish Gitea release
|
||||
env:
|
||||
TOKEN: ${{ secrets.RELEASE_TOKEN != '' && secrets.RELEASE_TOKEN || github.token }}
|
||||
TAG: ${{ steps.rel.outputs.tag }}
|
||||
NAME: ${{ steps.rel.outputs.name }}
|
||||
PRERELEASE: ${{ steps.rel.outputs.prerelease }}
|
||||
ROLLING: ${{ steps.rel.outputs.rolling }}
|
||||
BODY: |
|
||||
Automated build. Packages: shaterd + byedpi (per-arch), shater-core +
|
||||
luci-app-shater (arch=all).
|
||||
Targets: x86_64 (testbed) and aarch64_cortex-a53 (BPI-R3 + BPI-R4, mediatek/filogic).
|
||||
|
||||
── Add as an opkg feed (recommended — then `opkg upgrade` just works) ──
|
||||
This release is itself a SIGNED package feed; opkg filters by
|
||||
architecture, so the same lines work on every device:
|
||||
wget -O /etc/opkg/keys/5ac4b177689cb8e0 https://git.qomar.pw/omar/shater/releases/download/latest/shater-feed.pub
|
||||
echo "src/gz shater https://git.qomar.pw/omar/shater/releases/download/latest" >> /etc/opkg/customfeeds.conf
|
||||
opkg update
|
||||
opkg install luci-app-shater # pulls shater-core + shaterd too
|
||||
The public-key install is one-time; after it, `opkg update/upgrade`
|
||||
verify the signature with check_signature left on. Full guide: docs-shater/INSTALL.md.
|
||||
|
||||
── Or install the loose .ipk directly / from the tarball feed ──
|
||||
wget -O /tmp/f.tgz <this release>/shater-feed-aarch64_cortex-a53.tar.gz
|
||||
mkdir -p /tmp/shater && tar -C /tmp/shater -xzf /tmp/f.tgz
|
||||
opkg install /tmp/shater/luci-app-shater_*_all.ipk
|
||||
run: bash ci/gitea-release.sh release/*
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Publish the apk lane: ONE release PER ARCH (apk package filenames carry no
|
||||
# arch, and apk fetches `<name>-<ver>.apk` relative to the packages.adb URL —
|
||||
# a flat multi-arch release would collide). Rolling `apk-latest-<arch>` on
|
||||
# dispatch, `apk-<tag>-<arch>` on a version tag. The tags do NOT match the
|
||||
# workflow's `v*` trigger, so publishing them cannot re-trigger the build.
|
||||
# Publish: ONE release PER ARCH (apk package filenames carry no arch, and apk
|
||||
# fetches `<name>-<ver>.apk` relative to the packages.adb URL — a flat
|
||||
# multi-arch release would collide). Every run refreshes the ROLLING pointer
|
||||
# `apk-latest-<arch>`; a `vX.Y.Z` tag run ALSO publishes the pinnable
|
||||
# `apk-vX.Y.Z-<arch>`. The tags do NOT match the workflow's `v*` trigger, so
|
||||
# publishing them cannot re-trigger the build.
|
||||
#
|
||||
# WHY THE ROLLING RELEASE IS PUBLISHED ON TAG RUNS TOO (fixed 2026-07-25):
|
||||
# it used to be an either/or — `TAG=apk-latest-<arch>` on dispatch, ELSE
|
||||
# `TAG=apk-<ver>-<arch>` — so once releases moved to tag pushes the rolling
|
||||
# pointer was never written again. It froze at 0.2.0 (published 2026-07-24)
|
||||
# while v0.2.9/v0.2.10 published fine, and every router whose
|
||||
# /etc/apk/repositories.d/shater.list points at the rolling URL kept getting a
|
||||
# successful, silent `apk update` with nothing new. Rolling is the whole point
|
||||
# of that URL, so it is now written unconditionally and asserted afterwards.
|
||||
release-apk:
|
||||
name: release apk
|
||||
needs: build-apk
|
||||
needs: [test, build-apk]
|
||||
# Publish whatever arch feeds succeeded — do NOT block the aarch64 release
|
||||
# when an unrelated arch (e.g. x86_64) fails. download-artifact only fetches
|
||||
# artifacts that exist, and the publish loop skips missing apkfeed-* dirs.
|
||||
#
|
||||
# `needs.test.result == 'success'` is the second half of the gate. Without
|
||||
# it, `!cancelled()` is true when the test job FAILS (build-apk is then
|
||||
# skipped), this job runs with no artifacts at all, and — see the guard at
|
||||
# the end of the publish step — used to exit 0 having published nothing. Red
|
||||
# tests must SKIP this job, not "succeed" through it.
|
||||
if: ${{ !cancelled() && needs.test.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -450,6 +399,9 @@ jobs:
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
# Identity of the VERSIONED release only. The rolling pointer is published
|
||||
# on every run with fixed prerelease=true/rolling=true, so it needs nothing
|
||||
# from here.
|
||||
- name: Determine release identity
|
||||
id: rel
|
||||
run: |
|
||||
@@ -471,25 +423,114 @@ jobs:
|
||||
PRERELEASE: ${{ steps.rel.outputs.prerelease }}
|
||||
ROLLING: ${{ steps.rel.outputs.rolling }}
|
||||
run: |
|
||||
set -eu
|
||||
set -euo pipefail
|
||||
# Counted, and asserted non-zero at the end. Until 2026-07-26 this loop
|
||||
# was the step's whole body: with no artifacts the glob stayed
|
||||
# unexpanded, `[ -d ... ]` was false, `continue` ran once, the loop
|
||||
# ended and the step exited 0 — "release apk" went GREEN having
|
||||
# published absolutely nothing. Any upstream failure (all arches
|
||||
# failing to build, an artifact-name change, a download-artifact
|
||||
# hiccup) therefore looked like a successful release.
|
||||
published=0
|
||||
for d in artifacts/apkfeed-*; do
|
||||
[ -d "$d" ] || continue
|
||||
arch="${d#artifacts/apkfeed-}"
|
||||
if [ "$VER" = latest ]; then TAG="apk-latest-$arch"; else TAG="apk-$VER-$arch"; fi
|
||||
ROLL="apk-latest-$arch"
|
||||
|
||||
# The version we just built, read straight off the artifact
|
||||
# (`shaterd-<ver>-r<rel>.apk`). NOT recomputed with ci/version.sh:
|
||||
# this job checks out shallow, so it has no tags to describe from.
|
||||
pkg=""
|
||||
for a in "$d"/shaterd-*.apk; do
|
||||
if [ -f "$a" ]; then pkg="$(basename "$a")"; fi
|
||||
done
|
||||
[ -n "$pkg" ] || { echo "[release-apk] ERROR: no shaterd-*.apk in $d"; exit 11; }
|
||||
want="${pkg#shaterd-}"; want="${want%.apk}"
|
||||
echo "[release-apk] arch=$arch built version=$want"
|
||||
|
||||
BODY="Automated apk (OpenWrt/ImmortalWrt 25.12+) package repo for \`$arch\`.
|
||||
Packages: shaterd + byedpi (per-arch), shater-core + luci-app-shater (arch=all).
|
||||
This build: \`$want\`.
|
||||
The index \`packages.adb\` is EC-signed; trust anchor \`shater-apk.pem\` (also in \`dist/\`).
|
||||
|
||||
── Add as an apk repository (auto-updates via \`apk upgrade\`) ──
|
||||
wget -O /etc/apk/keys/shater-apk.pem https://git.qomar.pw/omar/shater/releases/download/$TAG/shater-apk.pem
|
||||
── Add as an apk repository (rolling — install once, then just update) ──
|
||||
wget -O /etc/apk/keys/shater-apk.pem https://git.qomar.pw/omar/shater/releases/download/$ROLL/shater-apk.pem
|
||||
echo \"https://git.qomar.pw/omar/shater/releases/download/apk-latest-\$(cat /etc/apk/arch)/packages.adb\" > /etc/apk/repositories.d/shater.list
|
||||
apk update
|
||||
apk add luci-app-shater # pulls shater-core + shaterd too
|
||||
apk add byedpi # optional: ByeDPI desync egress
|
||||
Update: apk update && apk upgrade shaterd shater-core luci-app-shater byedpi
|
||||
Full guide: docs-shater/INSTALL.md §6. The opkg/24.10 feed lives in the \`latest\` release."
|
||||
echo "[release-apk] publishing $TAG from $d"
|
||||
TAG="$TAG" NAME="shater apk $VER ($arch)" BODY="$BODY" \
|
||||
PRERELEASE="$PRERELEASE" ROLLING="$ROLLING" \
|
||||
\`apk-latest-<arch>\` is a MOVING pointer: every release run replaces its
|
||||
assets, so the same repo line keeps serving the newest build. To pin a
|
||||
version instead, point the repo line at
|
||||
\`.../download/apk-vX.Y.Z-\$(cat /etc/apk/arch)/packages.adb\` — then the
|
||||
file must be edited by hand for each upgrade.
|
||||
── Update — ALWAYS name the packages, NEVER a bare \`apk upgrade\` ──
|
||||
apk update
|
||||
apk upgrade shaterd shater-core luci-app-shater byedpi
|
||||
A bare \`apk upgrade\` reconciles EVERY installed package against every
|
||||
configured repo and can downgrade unrelated system packages; naming them
|
||||
upgrades only those (apk-tools 3: \"If list of packages is provided, only
|
||||
those packages are upgraded along with needed dependencies\").
|
||||
Full guide: docs-shater/INSTALL.md §5."
|
||||
|
||||
# 1) the pinnable versioned release (tag runs only)
|
||||
if [ "$VER" != latest ]; then
|
||||
echo "[release-apk] publishing apk-$VER-$arch from $d"
|
||||
TAG="apk-$VER-$arch" NAME="shater apk $VER ($arch)" BODY="$BODY" \
|
||||
PRERELEASE="$PRERELEASE" ROLLING="$ROLLING" \
|
||||
bash ci/gitea-release.sh "$d"/*
|
||||
fi
|
||||
|
||||
# 2) the rolling pointer — ALWAYS, tag run included. ci/gitea-release.sh
|
||||
# deletes the existing release before recreating it, so the old
|
||||
# version's assets are REPLACED, never accumulated (two versions of
|
||||
# one package in one index would let apk choose, not us).
|
||||
echo "[release-apk] publishing $ROLL from $d"
|
||||
TAG="$ROLL" NAME="shater apk latest ($arch)" BODY="$BODY" \
|
||||
PRERELEASE=true ROLLING=true \
|
||||
bash ci/gitea-release.sh "$d"/*
|
||||
|
||||
# 3) ASSERT the rolling release really serves THIS build — same class
|
||||
# of check as ci/sdk-build-apk.sh's package-version assert, and for
|
||||
# the same reason: the previous failure mode was silent. Reads the
|
||||
# published release back over the API and requires our three
|
||||
# tag-versioned packages at $want, the index, the key — and NO
|
||||
# left-over package asset at any other version.
|
||||
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases/tags/$ROLL"
|
||||
got="$(curl -fsS -H "Authorization: token $TOKEN" "$api" \
|
||||
| tr '{},' '\n\n\n' \
|
||||
| sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | sort -u)" || {
|
||||
echo "[release-apk] ERROR: cannot read back $ROLL from the API"; exit 12; }
|
||||
echo "[release-apk] $ROLL assets: $(printf '%s ' $got)"
|
||||
# here-string, NOT `printf | grep -q`: under `pipefail` the early
|
||||
# exit of grep -q can SIGPIPE the writer and fail a passing check.
|
||||
for f in "shaterd-$want.apk" "shater-core-$want.apk" \
|
||||
"luci-app-shater-$want.apk" packages.adb shater-apk.pem; do
|
||||
grep -qxF "$f" <<<"$got" || {
|
||||
echo "[release-apk] ERROR: $ROLL does not contain '$f' after publish."
|
||||
echo " A router pinned to the rolling URL would have silently"
|
||||
echo " stayed on its old version with a successful apk update."
|
||||
exit 13; }
|
||||
done
|
||||
stale="$(grep -E '^(shaterd|shater-core|luci-app-shater)-.*\.apk$' <<<"$got" \
|
||||
| grep -vxF -e "shaterd-$want.apk" -e "shater-core-$want.apk" \
|
||||
-e "luci-app-shater-$want.apk" || true)"
|
||||
[ -z "$stale" ] || {
|
||||
echo "[release-apk] ERROR: $ROLL still holds stale package assets:"
|
||||
printf ' %s\n' $stale
|
||||
echo " Two versions of one package in one feed = apk picks by its"
|
||||
echo " own rules, not by our intent."
|
||||
exit 14; }
|
||||
echo "[release-apk] OK — $ROLL serves $want"
|
||||
published=$((published + 1))
|
||||
done
|
||||
|
||||
# The assert the loop above never had. Zero feeds published is a failed
|
||||
# release, not a quiet success — say so with a non-zero exit.
|
||||
if [ "$published" -eq 0 ]; then
|
||||
echo "[release-apk] ERROR: no apkfeed-* artifact reached this job, so"
|
||||
echo " NOTHING was published. Downloaded tree:"
|
||||
ls -la artifacts 2>&1 | sed 's/^/ /' || echo " (no artifacts/ dir at all)"
|
||||
exit 10
|
||||
fi
|
||||
echo "[release-apk] published $published arch feed(s)"
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Shater — the test gate, on every push to `main`.
|
||||
#
|
||||
# WHY THIS FILE EXISTS (2026-07-26)
|
||||
# The fork had a full suite and no CI that ran it. Upstream's
|
||||
# .github/workflows/test.yml triggers on `stable`/`testing`/`unstable`; this
|
||||
# repo only has `main`. And Gitea does not read .github/workflows AT ALL once
|
||||
# .gitea/workflows exists — so those files are decoration here. Result: 115 of
|
||||
# the 116 test files under shater/** had never once executed in CI, and
|
||||
# TestDNSFilterRemoteBlocklistHTTPClient stayed red across two published
|
||||
# releases.
|
||||
#
|
||||
# RELATIONSHIP TO release.yml
|
||||
# This workflow is the FAST FEEDBACK loop on `main`. It is NOT the release
|
||||
# gate: a separate workflow cannot block another one. The gate is the `test`
|
||||
# JOB inside .gitea/workflows/release.yml, which build-apk `needs:` — see the
|
||||
# comment there. Both run the very same scripts/run-tests.sh, so they cannot
|
||||
# drift apart.
|
||||
name: test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
- 'docs-shater/**'
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: test-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: go + panel tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
# go.mod has `replace github.com/sagernet/wireguard-go => ./submodules/
|
||||
# wireguard-go`, so WITHOUT this every `go list`/`go test` fails before it
|
||||
# starts. Same step, same reason, as in release.yml's build job.
|
||||
- name: Init wireguard-go submodule (awg)
|
||||
run: git submodule update --init --depth 1 submodules/wireguard-go
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: false # explicit actions/cache@v3.3.2 below
|
||||
|
||||
# v3.3.2 is the last release speaking the cache API act_runner implements
|
||||
# (see the header of release.yml). Same key as the release build job, so
|
||||
# whichever runs first warms the other.
|
||||
- name: Cache Go modules + build cache
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: |
|
||||
~/go/pkg/mod
|
||||
~/.cache/go-build
|
||||
key: go-${{ hashFiles('go.sum') }}
|
||||
restore-keys: |
|
||||
go-
|
||||
|
||||
# Node 24, NOT the 20 the SPA build uses: panel's tests are TypeScript run
|
||||
# through `node --test`, and type stripping only exists from 22.6. On
|
||||
# node 20 `npm test` dies with a syntax error before running anything.
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
|
||||
- name: Cache panel node_modules
|
||||
uses: actions/cache@v3.3.2
|
||||
with:
|
||||
path: panel/node_modules
|
||||
key: npm-${{ hashFiles('panel/package-lock.json') }}
|
||||
|
||||
- name: Panel tests
|
||||
run: bash scripts/run-panel-tests.sh
|
||||
|
||||
- name: Go tests (shipped tags, linux, + race)
|
||||
run: bash scripts/run-tests.sh
|
||||
+20
-14
@@ -1,28 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# mod from https://gist.github.com/pldubouilh/c5703052986bfdd404005951dee54683
|
||||
|
||||
set -e -o pipefail
|
||||
set -euo pipefail
|
||||
|
||||
ARCH=$1
|
||||
DEB_SRC=$2
|
||||
OUT_IPK=$3
|
||||
|
||||
PROJECT=$(dirname "$0")/../..
|
||||
TMP_PATH=`mktemp -d`
|
||||
cp $2 $TMP_PATH
|
||||
pushd $TMP_PATH
|
||||
TMP_PATH=$(mktemp -d)
|
||||
trap 'rm -rf "$TMP_PATH"' EXIT
|
||||
|
||||
DEB_NAME=`ls *.deb`
|
||||
ar x $DEB_NAME
|
||||
cp "$DEB_SRC" "$TMP_PATH"/
|
||||
pushd "$TMP_PATH" >/dev/null
|
||||
|
||||
# Derive the name from the file we copied — do not glob-parse `ls *.deb`.
|
||||
DEB_NAME=$(basename "$DEB_SRC")
|
||||
ar x "$DEB_NAME"
|
||||
|
||||
mkdir control
|
||||
pushd control
|
||||
pushd control >/dev/null
|
||||
tar xf ../control.tar.gz
|
||||
rm md5sums
|
||||
sed "s/Architecture:\\ \w*/Architecture:\\ $1/g" ./control -i
|
||||
rm -f md5sums
|
||||
sed "s/Architecture:\\ \w*/Architecture:\\ $ARCH/g" ./control -i
|
||||
cat control
|
||||
tar czf ../control.tar.gz ./*
|
||||
popd
|
||||
popd >/dev/null
|
||||
|
||||
DEB_NAME=${DEB_NAME%.deb}
|
||||
tar czf $DEB_NAME.ipk control.tar.gz data.tar.gz debian-binary
|
||||
popd
|
||||
tar czf "$DEB_NAME.ipk" control.tar.gz data.tar.gz debian-binary
|
||||
popd >/dev/null
|
||||
|
||||
cp $TMP_PATH/$DEB_NAME.ipk $3
|
||||
rm -r $TMP_PATH
|
||||
cp "$TMP_PATH/$DEB_NAME.ipk" "$OUT_IPK"
|
||||
|
||||
+8
-1
@@ -36,8 +36,15 @@ nul
|
||||
# playwright MCP screenshots/snapshots
|
||||
.playwright-mcp/
|
||||
|
||||
# working-session screenshots dropped in the repo root (not shipped docs)
|
||||
/*.png
|
||||
|
||||
# throwaway build binaries / scratch staged under tmp/
|
||||
/tmp/
|
||||
|
||||
# -- upstream sing-box-lx -----------------------------------------
|
||||
/.idea/
|
||||
.idea/
|
||||
/vendor/
|
||||
/*.json
|
||||
/*.srs
|
||||
@@ -56,7 +63,7 @@ nul
|
||||
/venv/
|
||||
/test/cache.db
|
||||
|
||||
# feed artifacts (tracked public key dist/shater-feed.pub is force-added)
|
||||
# feed artifacts (the tracked apk trust anchor dist/shater-apk.pem is force-added)
|
||||
/dist/
|
||||
|
||||
# local agent config (CLAUDE.md is deliberately tracked; .claude local settings are not)
|
||||
|
||||
+7
-1
@@ -7,4 +7,10 @@
|
||||
[submodule "submodules/wireguard-go"]
|
||||
path = submodules/wireguard-go
|
||||
url = https://github.com/Leadaxe/wireguard-go-awg2-lx
|
||||
branch = lx
|
||||
# The pin lives on lx-awg2-v005, NOT on lx: the two are separate lines (42
|
||||
# commits apart one way, 131 the other). `lx` has no hasReserved() gate in
|
||||
# conn/bind_std.go at all, so a `git submodule update --remote` against it
|
||||
# would silently restore the bug where ClientBind/StdNetBind shred the
|
||||
# AmneziaWG magic header and no chain carries traffic. Keep this pointing at
|
||||
# the line the pin is actually on.
|
||||
branch = lx-awg2-v005
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
## Правила делегирования
|
||||
|
||||
1. ЛЮБАЯ реализация (код, тесты, конфиги, рефакторинг, отладка) выполняется
|
||||
субагентами через инструмент Agent с `model: "opus"`. Сам ты правишь файлы
|
||||
субагентами через инструмент Agent с `model: "fable"`. Сам ты правишь файлы
|
||||
только в одном случае: тривиальная правка в 1–2 строки, где постановка
|
||||
задачи дороже самой правки.
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
названия скиллов прямо в текст задания.
|
||||
|
||||
4. Независимые задачи запускай ПАРАЛЛЕЛЬНО — несколько вызовов Agent в одном
|
||||
сообщении, каждый с `model: "opus"`. Зависимые — последовательно, передавая
|
||||
сообщении, каждый с `model: "fable"`. Зависимые — последовательно, передавая
|
||||
в следующее ТЗ результаты предыдущего.
|
||||
|
||||
5. Приёмка: результат каждого субагента ты проверяешь сам (читаешь diff
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<!-- Language: [Русский](README.md) · **English** -->
|
||||
|
||||
# shater
|
||||
|
||||
**A self-hosted internet-control appliance for OpenWrt routers.** One box turns a
|
||||
home or office network into a transparent VPN gateway, a network-wide
|
||||
ad/tracker/malware blocker, per-device parental control, and a live traffic
|
||||
dashboard — all local, all configured from a rich built-in web panel.
|
||||
|
||||
> The primary README is Russian — [README.md](README.md). This is a condensed
|
||||
> English mirror.
|
||||
|
||||
[](LICENSE)
|
||||

|
||||
|
||||
## What it is
|
||||
|
||||
shater is a network proxy stack for **OpenWrt / ImmortalWrt / BananaWRT** routers
|
||||
(Banana Pi BPI-R3, BPI-R4 and compatible). It transparently routes all LAN traffic
|
||||
through a proxy (split by domain/geo/client), filters DNS, gathers statistics, and
|
||||
is managed from a built-in web panel.
|
||||
|
||||
The engine is a **fork of [sing-box](https://github.com/SagerNet/sing-box) via
|
||||
[sing-box-lx](https://github.com/Leadaxe/sing-box-lx)**, compiled into a single Go
|
||||
binary `shaterd` together with the control plane, DNS filter, stats aggregator and
|
||||
the web panel itself. Broad protocol set: VLESS/VMess/Trojan/Shadowsocks,
|
||||
Reality/XTLS, WireGuard, **AmneziaWG 2.0**, Hysteria2, TUIC, XHTTP, MASQUE/CONNECT-IP.
|
||||
|
||||
A thin **LuCI launcher** (mini-dashboard + "Open panel" button) hands the browser a
|
||||
single-use token into the standalone SPA the daemon serves on its own port
|
||||
(default `:8088`).
|
||||
|
||||
## Highlights
|
||||
|
||||
- Transparent **TPROXY** data plane (TCP + UDP), SNI/Host/QUIC sniffing, no DNS leaks
|
||||
— `:53` interception is on by default and covers the queries a client sends to the
|
||||
router itself, not just the ones aimed around it (`globals.dns_intercept`, D24).
|
||||
- First-match routing by source / destination / list / geo / client → outbound /
|
||||
selector / chain / direct / block; node groups with balancer/observatory;
|
||||
multi-hop chains; per-rule egress.
|
||||
- **Fail-closed kill-switch** (dead group → block, never a silent direct leak); own
|
||||
`inet shater` nft table; atomic apply with `nft -c` validation and commit-confirm
|
||||
auto-rollback.
|
||||
- **DNS filtering & blocklists** with flexible sources (inline / file / url /
|
||||
geosite), compiled `.srs` matcher; Block-DoH/DoT to stop filter bypass.
|
||||
- Subscriptions (Clash / sing-box / Xray-JSON) and manual nodes; node health board.
|
||||
- Per-device control (proxy/blocklist toggles, exit country, per-device block/allow,
|
||||
schedules) and per-domain/client/device statistics from in-process DNS events.
|
||||
|
||||
Full list with MVP/T1/T2 tags — [`docs-shater/FEATURES.md`](docs-shater/FEATURES.md).
|
||||
|
||||
## Install
|
||||
|
||||
One signed **apk** feed (OpenWrt / ImmortalWrt / BananaWRT **25.12+**), one
|
||||
release per arch. Verbatim commands, the manual `.apk` install and the
|
||||
rolling-vs-pinned choice are in
|
||||
[`docs-shater/INSTALL.md`](docs-shater/INSTALL.md).
|
||||
|
||||
```sh
|
||||
wget -O /etc/apk/keys/shater-apk.pem "https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/shater-apk.pem"
|
||||
echo "https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/packages.adb" > /etc/apk/repositories.d/shater.list
|
||||
apk update && apk add luci-app-shater # -> shater-core -> shaterd
|
||||
```
|
||||
|
||||
`apk-latest-<arch>` is a moving pointer refreshed by every release run — install
|
||||
once and `apk update && apk upgrade shaterd shater-core luci-app-shater byedpi`
|
||||
keeps the router current. Point the repo line at `apk-vX.Y.Z-<arch>` instead to
|
||||
pin a build; that file then has to be edited by hand for every upgrade.
|
||||
|
||||
shater ships **inert** (globals off) so install never breaks connectivity. After
|
||||
configuring nodes/rules: `uci set shater.globals.enabled=1 && uci commit shater`,
|
||||
then `shaterd apply` and `shaterd confirm`.
|
||||
|
||||
## Build from source
|
||||
|
||||
`scripts/build-shaterd.sh [VERSION] [--fast]` builds the SPA (Vite), embeds it via
|
||||
`//go:embed`, cross-builds musl-static `{amd64, arm64}` and UPX-packs the artifact
|
||||
into `openwrt/shaterd/files/`. Details in
|
||||
[`docs-shater/INSTALL.md`](docs-shater/INSTALL.md).
|
||||
|
||||
## Repository layout
|
||||
|
||||
| Path | What |
|
||||
|------|------|
|
||||
| `shater/` | Go control plane, DNS filter, stats aggregator, engine host |
|
||||
| `panel/` | Admin SPA (Vite + React + TS) and its Go server |
|
||||
| `openwrt/` | Packages: `shaterd`, `shater-core`, `luci-app-shater`, `byedpi` |
|
||||
| `docs-shater/` | Product documentation |
|
||||
| `scripts/`, `ci/`, `.gitea/workflows/` | Build script, apk feed/release scripts, CI |
|
||||
| `SPECS/`, `docs-lx/` | Engine-fork constitution/specs and feature-config reference |
|
||||
| `docs/`, `mkdocs.yml` | **Upstream** sing-box docs (mkdocs) — kept as-is |
|
||||
| `adapter/ cmd/ dns/ route/ option/ protocol/ transport/ …` | sing-box-lx engine tree |
|
||||
|
||||
## CI, upstream & license
|
||||
|
||||
CI (`.gitea/workflows/release.yml`) builds all 4 packages and publishes a signed
|
||||
per-arch apk repo (EC key `shater-apk.pem`). A `vX.Y.Z` tag → the pinnable
|
||||
`apk-vX.Y.Z-<arch>`; every run also refreshes the rolling `apk-latest-<arch>` and
|
||||
asserts over the API that it really serves the version just built.
|
||||
|
||||
The engine is the **sing-box-lx** fork — a thin downstream of upstream sing-box that
|
||||
lives by **rebase, never merge**; its constitution is
|
||||
[`SPECS/CONSTITUTION.md`](SPECS/CONSTITUTION.md). Licensed under
|
||||
[GPL-3.0](LICENSE), like upstream sing-box. Unofficial fork, not affiliated with
|
||||
SagerNet.
|
||||
@@ -1,71 +1,317 @@
|
||||
<!-- Язык: **Русский** · [English](README.en.md) -->
|
||||
|
||||
# shater
|
||||
|
||||
**A self-hosted internet-control appliance for OpenWrt.** One box turns your
|
||||
network into a transparent VPN gateway, a network-wide ad/tracker/malware blocker,
|
||||
per-device parental control, and a live traffic dashboard — configured from a rich
|
||||
web admin panel, all local.
|
||||
**Управляемый интернет-шлюз для роутеров на OpenWrt.** Одна коробка превращает
|
||||
домашнюю или офисную сеть в прозрачный VPN-шлюз, сетевой блокировщик рекламы,
|
||||
трекеров и вредоносных доменов, средство родительского контроля по устройствам
|
||||
и живую панель аналитики трафика — всё локально, всё self-hosted, всё
|
||||
настраивается из богатой веб-панели.
|
||||
|
||||
[](LICENSE)
|
||||

|
||||

|
||||

|
||||
|
||||
> ⚠️ **v0.2 is under active development on a new foundation.** The previous,
|
||||
> complete and VM-verified xray-based version lives on the **[`v0.1`](../../src/branch/v0.1)**
|
||||
> branch and still installs from the signed feed.
|
||||
---
|
||||
|
||||
## What v0.2 is
|
||||
## Что это
|
||||
|
||||
shater v0.2 is built as a **fork of [sing-box](https://github.com/SagerNet/sing-box)
|
||||
(via [sing-box-lx](https://github.com/Leadaxe/sing-box-lx))** with our whole
|
||||
product embedded in the one binary: the proxy engine, a control plane, a DNS
|
||||
filter, and a full admin panel. Riding sing-box gives a broad, up-to-date protocol
|
||||
set — VLESS/VMess/Trojan/Shadowsocks, Reality, **AmneziaWG 2.0**, Hysteria2, TUIC —
|
||||
without reinventing the anti-DPI arms race.
|
||||
**shater** — это сетевой прокси-стек для роутеров на **OpenWrt / ImmortalWrt /
|
||||
BananaWRT** (Banana Pi BPI-R3, BPI-R4 и совместимые). Он прозрачно (без настройки
|
||||
клиентов) заворачивает весь LAN-трафик через прокси с маршрутизацией по домену,
|
||||
гео и клиенту, фильтрует DNS, собирает статистику и управляется из встроенной
|
||||
веб-панели.
|
||||
|
||||
The UI is split for both integration and a great experience: a **thin LuCI app**
|
||||
(a small dashboard + an "Open panel" button) hands a short-lived token to a
|
||||
**standalone admin panel** the daemon serves on its own port — so panel auth is
|
||||
bootstrapped from LuCI's existing login, and the real UX is a modern SPA we fully
|
||||
own.
|
||||
Ядро — **форк движка [sing-box](https://github.com/SagerNet/sing-box) через
|
||||
[sing-box-lx](https://github.com/Leadaxe/sing-box-lx)** — вкомпилировано в один
|
||||
Go-бинарь `shaterd` вместе с control-plane, DNS-фильтром, агрегатором статистики и
|
||||
самой веб-панелью. За счёт sing-box поддерживается широкий и актуальный набор
|
||||
протоколов: VLESS/VMess/Trojan/Shadowsocks, Reality/XTLS, WireGuard,
|
||||
**AmneziaWG 2.0**, Hysteria2, TUIC, XHTTP, MASQUE/CONNECT-IP.
|
||||
|
||||
## Highlights (planned)
|
||||
Интеграция в OpenWrt — тонкий **LuCI-лаунчер**: мини-дашборд и кнопка «Открыть
|
||||
панель», которая по одноразовому токену передаёт браузер в полноценную SPA-панель,
|
||||
поднятую демоном на собственном порту (по умолчанию `:8088`).
|
||||
|
||||
- Transparent TPROXY proxy (TCP+UDP), split by domain/geo/client, no DNS leaks.
|
||||
- Broad protocols incl. **AmneziaWG 2.0**, Reality, Hysteria2, TUIC.
|
||||
- Network-wide **DNS blocklists** with flexible sources (inline / file / url /
|
||||
geosite) and an efficient matcher for million-entry lists.
|
||||
- **Per-domain, per-client, per-device statistics** — fed by the engine's DNS
|
||||
events in-process (no log scraping).
|
||||
- **Per-device control**: block a site for one device or everyone; per-device
|
||||
exit/proxy toggles; schedules; alerts.
|
||||
- Fail-closed kill-switch, atomic apply with commit-confirm rollback, signed opkg
|
||||
feed.
|
||||
---
|
||||
|
||||
See **[`docs-shater/FEATURES.md`](docs-shater/FEATURES.md)** for the full list.
|
||||
## Ключевые возможности
|
||||
|
||||
## Documentation
|
||||
**Прозрачный прокси и маршрутизация**
|
||||
- TPROXY data-plane для нескольких LAN-интерфейсов (TCP + UDP), сниффинг
|
||||
SNI/Host/QUIC, без утечек DNS.
|
||||
- Правила маршрутизации по источнику (IP/CIDR/MAC/интерфейс/зона), назначению
|
||||
(domain/suffix/keyword/geosite), спискам, порту, протоколу →
|
||||
outbound / selector / chain / direct / block.
|
||||
- Группы узлов с балансировщиком/обсерваторией (least-ping / failover /
|
||||
round-robin), **мульти-хоп цепочки** и выбор egress по правилу.
|
||||
|
||||
| Doc | What |
|
||||
|-----|------|
|
||||
| [`docs-shater/CONTEXT.md`](docs-shater/CONTEXT.md) | **Start here** — project context, v0.1→v0.2 history, decisions in brief, testbed/infra |
|
||||
| [`docs-shater/ROADMAP.md`](docs-shater/ROADMAP.md) | Phased plan (Phase 1 = fork + embedding prototype) |
|
||||
| [`docs-shater/FEATURES.md`](docs-shater/FEATURES.md) | Full feature list with MVP/T1/T2 tags |
|
||||
| [`docs-shater/ARCHITECTURE.md`](docs-shater/ARCHITECTURE.md) | One-binary design, auth handoff, data/DNS/apply flow (diagrams) |
|
||||
| [`docs-shater/DECISIONS.md`](docs-shater/DECISIONS.md) | Why sing-box, why fork, why the panel split, license, etc. |
|
||||
| [`docs-shater/DESIGN.md`](docs-shater/DESIGN.md) | Admin-panel visual system — the "Faceplate" direction, tokens, components, north-star prototype |
|
||||
**Надёжность («железно»)**
|
||||
- **Fail-closed kill-switch**: мёртвая группа → block, а не тихая утечка мимо
|
||||
прокси; собственная nft-таблица `inet shater` и свои марки/таблицы, fw4 не
|
||||
трогаем.
|
||||
- Атомарный apply с валидацией движком и `nft -c`, **commit-confirm** с
|
||||
авто-откатом к последней рабочей конфигурации.
|
||||
- Идемпотентный reconcile из hotplug/boot под flock; management-bypass
|
||||
(SSH/LuCI/LAN) всегда в обход.
|
||||
|
||||
## Status
|
||||
**DNS, фильтрация, блокировки**
|
||||
- Перехват `:53`, DNS движка sing-box в процессе; резолверы DoH/DoT/plain/FakeIP,
|
||||
выбор резолвера по домену.
|
||||
- **Блок-листы с гибкими источниками**: `inline` / `file` / `url` (авто-обновление) /
|
||||
категория `geosite`; hosts-файл, plain-список или AdBlock-стиль `||domain^`
|
||||
компилируются в локальный `.srs`. Эффективный компилированный матчер вместо
|
||||
dnsmasq-мегасписков.
|
||||
- **Block-DoH/DoT** — не даёт устройствам обходить фильтр через свой шифрованный DNS.
|
||||
|
||||
Foundation reset complete: v0.1 preserved on its branch, `main` reset for v0.2.
|
||||
Next is **Phase 1** — fork sing-box-lx into `main` and stand up the embedding
|
||||
prototype (prove AmneziaWG 2.0, measure binary size). Follow `docs-shater/ROADMAP.md`.
|
||||
**Подписки и узлы**
|
||||
- Подписки (VLESS/VMess/Trojan/SS/WG/AmneziaWG), форматы Clash/sing-box/Xray-JSON,
|
||||
интервал обновления + вручную + на загрузке; стабильная идентичность узла между
|
||||
обновлениями; квоты/срок из `subscription-userinfo`.
|
||||
- Ручные узлы: share-ссылки, импорт файла, `wg-quick`/AmneziaWG `.conf`.
|
||||
- Health board: TCP + реальная проба через прокси-путь, exit-IP, «протестировать
|
||||
все».
|
||||
|
||||
## Hardware
|
||||
**Контроль по устройствам**
|
||||
- Авто-обнаружение устройств (dhcp.leases + `ip neigh`), имена, живой статус/трафик.
|
||||
- Тумблеры на устройство: прокси on/off, блок-листы on/off, страна/узел выхода;
|
||||
блок/allow домена для одного устройства или для всех; расписания.
|
||||
|
||||
`aarch64_cortex-a53` covers Banana Pi **BPI-R3** (MT7986/Filogic 830) and **BPI-R4**
|
||||
(MT7988/Filogic 880), both the OpenWrt `mediatek/filogic` target. `x86_64` is the
|
||||
QEMU test VM.
|
||||
**Статистика и видимость**
|
||||
- Топ доменов (запрошенные/заблокированные), allowed-vs-blocked, разбивка по
|
||||
устройствам, таймлайны — из DNS-событий движка в процессе (без скрейпинга логов).
|
||||
- Трафик по клиенту/узлу/правилу (байты) из nft-счётчиков; живой query-log.
|
||||
|
||||
## License
|
||||
**Панель и профили**
|
||||
- Встроенная SPA-панель (собственный порт, вшита в бинарь): overview, узлы и
|
||||
подписки, правила маршрутизации, DNS/блок-листы, устройства, apply/rollback.
|
||||
- Именованные профили/сцены и WAN-профили (условные оверрайды).
|
||||
|
||||
[GPL-3.0](LICENSE) (sing-box is GPL-3.0). See `docs-shater/DECISIONS.md` D6.
|
||||
Полный список с тегами MVP/T1/T2 — [`docs-shater/FEATURES.md`](docs-shater/FEATURES.md).
|
||||
|
||||
---
|
||||
|
||||
## Архитектура
|
||||
|
||||
Один бинарь `shaterd` держит движок, control-plane, DNS-фильтр и веб-сервер панели
|
||||
в одном процессе; OpenWrt-обвязка (тонкий LuCI + procd/system glue) оборачивает его.
|
||||
Конфиг — UCI desired-state; демон рендерит его в конфиг движка и применяет;
|
||||
телеметрия течёт обратно в панель.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph BIN["shaterd — один бинарь (форк sing-box-lx)"]
|
||||
ENG["движок sing-box\nпротоколы · Reality · AmneziaWG 2.0 · DNS · routing · stats"]
|
||||
CTRL["control-plane (shater/)\nUCI-модель · генерация конфига · apply/rollback · nft/routing"]
|
||||
FILT["DNS-фильтр + блок-листы + политика по устройствам (shater/)"]
|
||||
STAT["агрегатор статистики (shater/)"]
|
||||
PANEL["веб-сервер панели + вшитая SPA (свой порт, токен-auth)"]
|
||||
end
|
||||
subgraph WRT["OpenWrt-обвязка (openwrt/)"]
|
||||
LUCI["тонкий LuCI — мини-дашборд + кнопка «Открыть панель»"]
|
||||
PROCD["procd init · hotplug · uci-defaults · fw4/routing"]
|
||||
end
|
||||
LUCI -->|"ubus: mint token"| PANEL
|
||||
PROCD --> BIN
|
||||
CTRL --> ENG
|
||||
FILT --> ENG
|
||||
ENG --> STAT
|
||||
STAT --> PANEL
|
||||
```
|
||||
|
||||
Путь трафика: LAN-клиент → `nft tproxy` (mark → tproxy-порт) → tproxy-inbound
|
||||
sing-box (сниффинг SNI/Host/QUIC) → маршрут по правилу → outbound/selector/chain
|
||||
(проксировано) · direct (flow-offload) · block. Подробные диаграммы (auth-handoff,
|
||||
data-plane, DNS-flow, apply-flow) — в [`docs-shater/ARCHITECTURE.md`](docs-shater/ARCHITECTURE.md).
|
||||
|
||||
---
|
||||
|
||||
## Установка
|
||||
|
||||
shater поставляется одним подписанным **apk-фидом** (OpenWrt / ImmortalWrt /
|
||||
BananaWRT **25.12+**: `.apk`, индекс `packages.adb`, EC-ключ в `/etc/apk/keys/`).
|
||||
Старый opkg-фид (`.ipk`, 24.10) снят — оба наших роутера на 25.12 с apk-tools 3,
|
||||
бинаря `opkg` там просто нет (`docs-shater/DECISIONS.md` D22).
|
||||
|
||||
Пакеты ставятся по зависимостям: `shaterd` → `shater-core` → `luci-app-shater`
|
||||
(+ опциональный `byedpi`). `shaterd` подтягивается автоматически как зависимость.
|
||||
|
||||
### Фид apk
|
||||
|
||||
`/etc/apk/arch` сам выбирает нужный per-arch релиз (apk-релизы раздельны по арке):
|
||||
|
||||
```sh
|
||||
# 1) доверяем ключу apk-фида (любое имя *.pem под /etc/apk/keys подходит).
|
||||
wget -O /etc/apk/keys/shater-apk.pem \
|
||||
"https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/shater-apk.pem"
|
||||
|
||||
# 2) добавляем репозиторий — строка указывает на сам ФАЙЛ-ИНДЕКС packages.adb.
|
||||
echo "https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/packages.adb" \
|
||||
> /etc/apk/repositories.d/shater.list
|
||||
|
||||
# 3) обновляемся и ставим (shaterd подтянется как зависимость).
|
||||
apk update
|
||||
apk add luci-app-shater # -> shater-core -> shaterd
|
||||
apk add byedpi # опционально: ByeDPI desync-egress
|
||||
```
|
||||
|
||||
Обновление — **перечисляйте пакеты явно, голый `apk upgrade` не запускайте**: без
|
||||
аргументов apk пересобирает состояние ВСЕХ установленных пакетов по ВСЕМ
|
||||
подключённым репозиториям и может задеть (в т.ч. откатить) посторонние системные
|
||||
пакеты.
|
||||
|
||||
```sh
|
||||
apk update
|
||||
apk upgrade shaterd shater-core luci-app-shater byedpi
|
||||
# эквивалент, дополнительно закрепляющий пакеты в world:
|
||||
# apk add -u shaterd shater-core luci-app-shater byedpi
|
||||
```
|
||||
|
||||
Документация apk-tools 3 про `apk upgrade`: *«If list of packages is provided,
|
||||
only those packages are upgraded along with needed dependencies»*. Проверить
|
||||
установленные версии: `apk list -I shaterd shater-core luci-app-shater byedpi`.
|
||||
|
||||
> **Роллинг или фиксация — это выбор URL в `shater.list`.** `apk-latest-<arch>`
|
||||
> — движущийся указатель: каждый релизный прогон заменяет его ассеты, поэтому
|
||||
> «поставил и забыл»: `apk update` сам видит новую сборку. `apk-vX.Y.Z-<arch>` —
|
||||
> фиксация на конкретной сборке: роутер не получит ничего нового, пока
|
||||
> `/etc/apk/repositories.d/shater.list` не отредактируют руками — на каждом
|
||||
> роутере и на каждый релиз. На `mini_router` сознательно прописан
|
||||
> версионированный URL, и ручная правка — его цена. Подробнее —
|
||||
> [`docs-shater/INSTALL.md`](docs-shater/INSTALL.md) §5.1.
|
||||
|
||||
> Версии пакетов CI берёт из git-тега (`vX.Y.Z` → `X.Y.Z-r1`, сборка вне тега →
|
||||
> `X.Y.Z-r<коммитов+1>`), поэтому каждая новая сборка действительно видна
|
||||
> менеджеру пакетов как новая. Подробности — `docs-shater/INSTALL.md` §2.1.
|
||||
|
||||
> Полные инструкции — ручная установка из `.apk`, фиксация версии
|
||||
> (`apk-vX.Y.Z-<arch>`), совместимость с BananaWRT `25.12-mtk-vendor` — в
|
||||
> [`docs-shater/INSTALL.md`](docs-shater/INSTALL.md).
|
||||
|
||||
### Включение
|
||||
|
||||
shater ставится **инертным** (globals выключены), чтобы установка не рвала связь.
|
||||
Настройте узлы/правила (через панель или `uci`), затем включите и примените:
|
||||
|
||||
```sh
|
||||
uci set shater.globals.enabled=1
|
||||
uci commit shater
|
||||
shaterd apply # apply + вооружить commit-confirm на живом демоне
|
||||
shaterd confirm # подтвердить (отменяет авто-откат)
|
||||
```
|
||||
|
||||
`/etc/init.d/shater enable && /etc/init.d/shater start` поднимает демона под procd.
|
||||
Кнопка «Открыть панель» в LuCI чеканит одноразовый токен и передаёт браузер в
|
||||
панель (`:8088` по умолчанию).
|
||||
|
||||
---
|
||||
|
||||
## Сборка из исходников
|
||||
|
||||
Ship-артефакт — бинарь `shaterd` со вшитой SPA. Собирается вне дерева SDK скриптом
|
||||
`scripts/build-shaterd.sh`:
|
||||
|
||||
```sh
|
||||
scripts/build-shaterd.sh [VERSION] [--fast]
|
||||
```
|
||||
|
||||
Что он делает: (1) собирает панель — `cd panel && npm ci && npm run build` (Vite →
|
||||
`panel/dist`); (2) копирует `panel/dist/*` в `shater/panel/webroot/`, откуда
|
||||
`//go:embed` вшивает **реальную** SPA в бинарь; (3) кросс-собирает под `{amd64,
|
||||
arm64}` с musl-static набором тегов (`CGO_ENABLED=0 GOOS=linux`), stripped/trimmed;
|
||||
(4) прогоняет UPX `--lzma --best` (~42 МБ → ~8–11 МБ); (5) стейджит артефакт в
|
||||
`openwrt/shaterd/files/` для пакета.
|
||||
|
||||
Затем OpenWrt-пакеты из `openwrt/` собираются каноническим путём SDK. Детали
|
||||
(набор build-тегов, почему `shaterd` — prebuilt-пакет, порядок CI) — в
|
||||
[`docs-shater/INSTALL.md`](docs-shater/INSTALL.md).
|
||||
|
||||
---
|
||||
|
||||
## Структура репозитория
|
||||
|
||||
Репозиторий — это оверлей продукта **shater** поверх дерева форка движка
|
||||
**sing-box-lx** (конфликт-фри: движок в апстрим-каталогах, продукт в своих).
|
||||
|
||||
| Путь | Что это |
|
||||
|------|---------|
|
||||
| `shater/` | Go: control-plane, DNS-фильтр, агрегатор статистики, хост движка |
|
||||
| `panel/` | Админ-SPA (Vite + React + TS) и её Go-сервер |
|
||||
| `openwrt/` | Пакеты: `shaterd`, `shater-core`, `luci-app-shater`, `byedpi` |
|
||||
| `docs-shater/` | Документация продукта (см. таблицу ниже) |
|
||||
| `scripts/` | `build-shaterd.sh` — сборка ship-артефакта |
|
||||
| `ci/` | Скрипты сборки apk-фида и релизов (SDK, EC-подпись, Gitea API) |
|
||||
| `.gitea/workflows/` | `release.yml` — CI: сборка пакетов + подписанный apk-фид |
|
||||
| `SPECS/` | Конституция форка движка и спеки (Spec Kit) |
|
||||
| `docs-lx/` | Справочник конфигурации фич движка (`lx-config.md`, `.ru.md`) |
|
||||
| `lx-test/`, `submodules/` | Примеры конфигов движка и submodule AmneziaWG-рантайма |
|
||||
| `docs/`, `mkdocs.yml` | **Апстрим** документация sing-box (mkdocs) — как есть |
|
||||
| `adapter/ cmd/ dns/ route/ option/ protocol/ transport/ …` | Дерево движка sing-box-lx |
|
||||
|
||||
---
|
||||
|
||||
## CI и релизы
|
||||
|
||||
CI на **Gitea Actions** (`.gitea/workflows/release.yml`) собирает все 4 пакета и
|
||||
публикует **подписанные фиды**:
|
||||
|
||||
- **apk (25.12+)** — единственный формат: **по релизу на арку**, индекс
|
||||
`packages.adb` подписан EC-ключом (публичный `dist/shater-apk.pem`; секрет — в
|
||||
Gitea-secret `KEY_APK`).
|
||||
|
||||
Триггеры: push тега **`vX.Y.Z`** → версионный релиз `apk-vX.Y.Z-<arch>`;
|
||||
`workflow_dispatch` → только роллинг. Роллинг `apk-latest-<arch>` обновляется
|
||||
**на каждом прогоне**, включая теговый, и после публикации проверяется через API:
|
||||
в нём обязаны лежать наши три пакета ровно собранной версии и ни одного ассета
|
||||
другой версии. Публикация — через Gitea API (`ci/gitea-release.sh`). Ключ
|
||||
**никогда не перегенерируется** — это инвалидировало бы доверие на всех
|
||||
развёрнутых роутерах.
|
||||
|
||||
---
|
||||
|
||||
## Связь с upstream и движок
|
||||
|
||||
shater вкомпилирует **форк движка sing-box-lx** — тонкий downstream апстрима
|
||||
[SagerNet/sing-box](https://github.com/SagerNet/sing-box), добавляющий набор
|
||||
клиентских фич (XHTTP, AmneziaWG 2.0, MASQUE, расширения наблюдаемости) за
|
||||
build-тегами и живущий **ребейзом на каждый upstream-тег, а не merge**. Форк
|
||||
разрабатывается по Spec Kit; неизменяемые принципы — в
|
||||
[`SPECS/CONSTITUTION.md`](SPECS/CONSTITUTION.md), справочник фич движка — в
|
||||
[`docs-lx/lx-config.ru.md`](docs-lx/lx-config.ru.md).
|
||||
|
||||
История: **v0.1** (движок на xray-core, полностью рабочая и VM-проверенная версия)
|
||||
сохранена на ветке **[`v0.1`](../../src/branch/v0.1)**. v0.2 схлопнула runtime в
|
||||
один форкнутый бинарь.
|
||||
|
||||
---
|
||||
|
||||
## Документация
|
||||
|
||||
| Документ | О чём |
|
||||
|----------|-------|
|
||||
| [`docs-shater/CONTEXT.md`](docs-shater/CONTEXT.md) | **Начните здесь** — контекст проекта, история v0.1→v0.2, testbed/инфра |
|
||||
| [`docs-shater/INSTALL.md`](docs-shater/INSTALL.md) | Сборка ship-артефакта и установка apk-фида (роллинг/фиксация) |
|
||||
| [`docs-shater/ARCHITECTURE.md`](docs-shater/ARCHITECTURE.md) | One-binary дизайн, auth-handoff, data/DNS/apply-потоки (диаграммы) |
|
||||
| [`docs-shater/FEATURES.md`](docs-shater/FEATURES.md) | Полный список фич с тегами MVP/T1/T2 |
|
||||
| [`docs-shater/ROADMAP.md`](docs-shater/ROADMAP.md) | Фазовый план |
|
||||
| [`docs-shater/DECISIONS.md`](docs-shater/DECISIONS.md) | Почему sing-box, почему форк, split панели, лицензия |
|
||||
| [`docs-shater/DESIGN.md`](docs-shater/DESIGN.md) | Визуальная система панели — «Faceplate», токены, компоненты |
|
||||
| [`docs-shater/PORTING.md`](docs-shater/PORTING.md) | Порт проверенных кусков из v0.1 |
|
||||
|
||||
Индекс папки — [`docs-shater/README.md`](docs-shater/README.md).
|
||||
|
||||
---
|
||||
|
||||
## Оборудование
|
||||
|
||||
Арка `aarch64_cortex-a53` покрывает Banana Pi **BPI-R3** (MT7986/Filogic 830) и
|
||||
**BPI-R4** (MT7988/Filogic 880) — оба таргет OpenWrt `mediatek/filogic`. `x86_64` —
|
||||
QEMU-стенд для тестов.
|
||||
|
||||
---
|
||||
|
||||
## Лицензия
|
||||
|
||||
[GPL-3.0](LICENSE) — как у upstream sing-box. Подробности — в
|
||||
[`docs-shater/DECISIONS.md`](docs-shater/DECISIONS.md) (D6). Неофициальный форк, не
|
||||
аффилирован с SagerNet.
|
||||
|
||||
+15
-235
@@ -1,239 +1,19 @@
|
||||
[English](README.md) · **Русский**
|
||||
# shater — этот файл переехал
|
||||
|
||||
# sing-box-lx
|
||||
Лицо этого репозитория — продукт **shater** (управляемый интернет-шлюз для
|
||||
роутеров на OpenWrt). Основной README на русском — **[README.md](README.md)**;
|
||||
краткая английская версия — **[README.en.md](README.en.md)**.
|
||||
|
||||
> **Тонкий downstream-форк [SagerNet/sing-box](https://github.com/SagerNet/sing-box).**
|
||||
> Небольшой набор клиентских фич поверх upstream — транспорт **XHTTP**, **AmneziaWG 2.0**, **MASQUE** (CONNECT-IP / Cloudflare WARP), расширения **наблюдаемости** (CommandClient) и балансировка нагрузки **round_robin** — каждая за своим build-tag.
|
||||
> Набор может расти, философия — нет: жить ребейзом на каждый upstream-тег, а не отдельной жизнью.
|
||||
Раньше здесь лежал README форка движка **sing-box-lx**, который shater
|
||||
вкомпилирует в свой бинарь. Документация именно движка-форка живёт в его слое:
|
||||
|
||||
> 📄 README самого upstream sing-box — **[на GitHub](https://github.com/SagerNet/sing-box/blob/main/README.md)** (всегда актуальный).
|
||||
- **[docs-lx/lx-config.ru.md](docs-lx/lx-config.ru.md)** — справочник конфигурации
|
||||
фич движка (XHTTP, AmneziaWG 2.0, MASQUE).
|
||||
- **[SPECS/CONSTITUTION.md](SPECS/CONSTITUTION.md)** — конституция тонкого форка
|
||||
(принципы, build-tag изоляция, ребейз-модель).
|
||||
- **[SPECS/README.md](SPECS/README.md)** — формат задач Spec Kit.
|
||||
- Апстрим-README самого sing-box —
|
||||
[на GitHub](https://github.com/Leadaxe/sing-box-lx).
|
||||
|
||||
Это не отдельный проект и не «улучшенный sing-box». Это upstream sing-box **плюс несколько фич**, реализованных так, чтобы их можно было переносить на новые версии sing-box годами, почти без конфликтов. Со временем фич может становиться больше — другие протоколы, новые возможности, — но каждая обязана жить по тем же правилам тонкого форка ([CONSTITUTION](SPECS/CONSTITUTION.md)).
|
||||
|
||||
---
|
||||
|
||||
## Уникальное позиционирование
|
||||
|
||||
В экосистеме sing-box форки, добавляющие XHTTP/AmneziaWG, делятся на два лагеря — и `sing-box-lx` не входит ни в один:
|
||||
|
||||
| Форк | Фичи | Подход | Синк с upstream |
|
||||
|------|------|--------|-----------------|
|
||||
| **SagerNet/sing-box** (upstream) | базовый | — | — |
|
||||
| **shtorm-7/sing-box-extended** | десятки (WARP, MASQUE, MTProxy, XHTTP, AWG2, …) | «комбайн», правки повсюду | отдельная ветка, без ребейза на теги |
|
||||
| **amnezia-vpn/amnezia-box**, **hoaxisr/amnezia-box** | только AWG | толстый форк, правки in-place | синк по веткам (`dev-next`/`stable-next`) |
|
||||
| **➡ sing-box-lx** (этот репозиторий) | **малый набор (XHTTP, AWG2, наблюдаемость, round_robin)** | **тонкий: новые файлы за build-tag, минимум касаний upstream** | **ребейз атомарных `// lx`-коммитов на upstream-теги** |
|
||||
|
||||
**Чем мы отличаемся:**
|
||||
|
||||
- **Минимальная дивергенция.** Новый код живёт в новых файлах. Существующие upstream-файлы трогаются только в крошечных помеченных швах `// lx:begin … // lx:end`. → дешёвые ребейзы.
|
||||
- **Изоляция за build-tag.** Фичи включаются тегами `with_xhttp` / `with_awg`. Сборка **без** них байт-в-байт повторяет поведение upstream — фичи ничего не ломают по умолчанию.
|
||||
- **Идентичность сохранена.** Go-модуль остаётся `github.com/sagernet/sing-box`, бинарь называется `sing-box`. Суффикс `-lx` есть только в строке версии (`1.13.13-lx.N`).
|
||||
- **Build-tag — родная конвенция sing-box**, а не наше изобретение (`with_quic`, `with_wireguard`, …). Мы просто применяем её с максимальной дисциплиной.
|
||||
|
||||
> Готовые форки-комбайны мы **не тянем как зависимость**, а используем только как референс wire-протокола.
|
||||
|
||||
---
|
||||
|
||||
## Фичи и статус
|
||||
|
||||
| # | Фича | Что это | Статус |
|
||||
|---|------|---------|--------|
|
||||
| **XHTTP** | клиентский транспорт | Xray-совместимый «splithttp» (режимы `auto`/`packet-up`/`stream-up`/`stream-one`) поверх Reality/TLS/h2c | ✅ **проверен живым Xray (3x-ui) сервером** (packet-up/auto): handshake + DNS + HTTPS + скачивание. `stream-one` — известный баг framing |
|
||||
| **AmneziaWG 2.0** | клиентский endpoint | обфускация WireGuard: `Jc/Jmin/Jmax`, `S1–S4`, `H1–H4` + **2.0**: `I1–I5` (CPS — кастомные пакеты-приманки) | ✅ собирается, проходит `check`; зависимость **активирована** ([Leadaxe/wireguard-go-awg2-lx](https://github.com/Leadaxe/wireguard-go-awg2-lx) — sagernet-база + обфускация); **проверено живым AWG2-сервером**: handshake + keepalive + трафик наружу |
|
||||
| **Маскировка `id/ip/ib`** | сахар над AWG | WireSock-стиль: декларативная маскировка поверх `I1` — домен (`id`) + протокол (`ip`: `quic`/`dns`/`stun`/`sip`) + браузер (`ib`), ядро строит клиент-инициированную `I1`-приманку: `quic` = out-of-order фрагментированный Initial (i1+i2), `dns`/`stun`/`sip` = query/Binding-Request/INVITE | ✅ **`ip=quic` device-проверен на реальном LTE/WARP DPI** (~330 мс, упрощает Cloudflare WARP); `dns`/`stun`/`sip` собираются и проходят `check`, но режутся как класс протокола к WARP-edge — для других провайдеров |
|
||||
| **Наблюдаемость** (расширения CommandClient) | live-стрим для UI | нативные расширения libbox gRPC за `with_lx_command`: `URLTestOutbound`, `GetRules`, `GetGroups`, `GetOutbounds`, `GetPool`, плюс `Connection.detourList` (хвост detour'а отдельным полем, SPEC 017) и `SubscribeDNSQueries` — структурный live-поток DNS (домен, qtype, rcode `-1`=ошибка, CNAME-цепочка, привязка к процессу, `dnsServer`/`dnsServerType`/`outbound`, SPEC 018) | ✅ в rc-серии, потребляется **LxBox**. SPEC 014–018: [`014`](SPECS/014-CLASH_API_TO_COMMANDCLIENT_MIGRATION/SPEC.md) · [`015`](SPECS/015-COMMAND_PROTOCOL_RPC_EXTENSIONS/SPEC.md) · [`017`](SPECS/017-CONNECTION_DETOUR_CHAIN/SPEC.md) · [`018`](SPECS/018-DNS_QUERY_STREAM/SPEC.md) |
|
||||
| **round_robin** (балансировка нагрузки) | режим `urltest` | пул-балансировка на `urltest` за `with_lx_command` (для `GetPool`): `mode` `least_test` (дефолт) \| `round_robin`; `balancer{pool (дефолт 3), pool_tolerance (0=держать живые / >0=топ по задержке), sticky_hash}`. Sticky-ключ: пропущен/`[]` → дефолт `["process","domain"]`, `["none"]` → выкл; компоненты `process`/`domain`/`source_ip`/`dest_ip`/`dest_port`. Фиксированные слоты `slot[hash(key)%pool]` (FNV-64a), замена в слоте; `GetPool` отдаёт слоты | ✅ локально равномерно (10/10/10, sticky off); rc.15 починил схлопывание `domain`-ключа (теперь читается `metadata.Domain`, переживающий resolve домен→IP, а не пустой `destination.Fqdn`) — на устройстве равномерность 0.27 → 0.95+. SPEC [`019`](SPECS/019-URLTEST_MODE_STICKY/SPEC.md), конфиг — [docs/.../urltest.md](docs/configuration/outbound/urltest.md) |
|
||||
| **MASQUE** (`type: masque`) | клиентский outbound | CONNECT-IP (RFC 9484) поверх HTTP/3 **или** HTTP/2 для **Cloudflare WARP** (SPEC 021): туннелирует целые IP-пакеты через userspace gVisor-стек; `profile` (`cloudflare`/`standard`), `network` (`h3`/`h2`), pinning ECDSA public key, idle-suspend + самовосстановление. h2 — ручной фреймер поверх `x/net/http2` (без доп. зависимостей); `connect-ip-go` вкопан | ✅ **device-verified на Wi-Fi и LTE** (`warp=on`, реальный трафик на `h3` и `h2`); на сетях, режущих входящий UDP:443, `h3`-handshake виснет — там `network: h2` (TCP:443) |
|
||||
|
||||
Подробные отчёты — в [`SPECS/002-…`](SPECS/002-XHTTP_CLIENT_TRANSPORT/IMPLEMENTATION_REPORT.md), [`SPECS/003-…`](SPECS/003-AWG2_CLIENT_ENDPOINT/IMPLEMENTATION_REPORT.md) и [`SPECS/009-…`](SPECS/009-WIRESOCK_MASQUERADE_PROFILES/IMPLEMENTATION_REPORT.md). Полный справочник конфига — **[docs-lx/lx-config.ru.md](docs-lx/lx-config.ru.md)**.
|
||||
|
||||
> **Не поддерживается (слой Reality, отложено):** post-quantum Reality (`pqv` / ML-DSA-65) и `spiderX` из Xray. Это Xray-специфичные фичи Reality, которых нет в sing-box, а Reality — upstream-слой TLS, который мы держим нетронутым (это не одна из наших фич). Классический X25519 Reality работает; сервер, который **требует** post-quantum Reality, не подключится. Это ограничение sing-box — правильнее решать в upstream (получим на ребейзе).
|
||||
|
||||
---
|
||||
|
||||
## Сборка
|
||||
|
||||
Сборка идёт через отдельный **`Makefile.lx`** (upstream `Makefile` не трогаем):
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules https://github.com/Leadaxe/sing-box-lx
|
||||
make -f Makefile.lx lx-build
|
||||
# → бинарь ./sing-box с версией вида 1.13.13-lx.1
|
||||
```
|
||||
|
||||
> `--recurse-submodules` обязателен для `with_awg`: рантайм AmneziaWG подключён submodule'ом `submodules/wireguard-go` → [Leadaxe/wireguard-go-awg2-lx](https://github.com/Leadaxe/wireguard-go-awg2-lx).
|
||||
|
||||
Под капотом — стандартный `go build` с набором тегов (единственный источник истины — `make -f Makefile.lx lx-print-tags`):
|
||||
|
||||
```
|
||||
with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_clash_api,with_naive_outbound,with_purego,badlinkname,tfogo_checklinkname0,with_xhttp,with_awg
|
||||
```
|
||||
|
||||
Это клиентский feature-set upstream **минус** серверные/нерелевантные теги — `with_acme` (серверный выпуск сертов), `with_tailscale`, `with_ccm`/`with_ocm` (AI-прокси) — **плюс** `with_purego` (CGO-free кросс-сборка, чтобы `with_naive_outbound`/cronet собирался при `CGO=0` на любом desktop-таргете, кроме Windows 7 / 32-бит legacy-сборки, где naive выкинут — у `cronet-go` нет windows/386) и наши фичи `with_xhttp` / `with_awg`. Всё остальное — ровно как upstream.
|
||||
|
||||
Проверка конфигов:
|
||||
|
||||
```bash
|
||||
./sing-box check -c lx-test/config/xhttp_reality.json
|
||||
./sing-box check -c lx-test/config/awg2_basic.json
|
||||
```
|
||||
|
||||
> `lx-test/config/` — наши примеры (upstream `test/` — отдельный Go-модуль, его не используем).
|
||||
|
||||
**Android (`libbox.aar`).** `make lib_install && make lib_android` собирает gomobile-AAR — `libbox.aar` (SDK 23) + `libbox-legacy.aar` (SDK 21) — с зашитыми `with_xhttp`/`with_awg` (и без `tailscale`), для встраивания в Android-приложение-потребитель (нужны NDK r28 + OpenJDK 17). `Libbox.version()` отдаёт `…-lx.N`.
|
||||
|
||||
---
|
||||
|
||||
## Конфигурация фич
|
||||
|
||||
> Полные таблицы полей, дефолты и `awg-quick`→JSON маппинг — **[docs-lx/lx-config.ru.md](docs-lx/lx-config.ru.md)**. Здесь — кратко.
|
||||
|
||||
### XHTTP (outbound transport)
|
||||
|
||||
```jsonc
|
||||
"transport": {
|
||||
"type": "xhttp",
|
||||
"host": "example.com",
|
||||
"path": "/xhttp",
|
||||
"mode": "auto" // auto | packet-up | stream-up | stream-one
|
||||
}
|
||||
```
|
||||
|
||||
### AmneziaWG 2.0 (endpoint)
|
||||
|
||||
Поля AWG промотированы прямо в `WireGuardEndpointOptions`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "wireguard",
|
||||
// … стандартные поля wireguard (private_key, address, peers, …) …
|
||||
"jc": 10, "jmin": 50, "jmax": 100,
|
||||
"s1": 20, "s2": 20, "s3": 60, "s4": 60,
|
||||
"h1": 1, "h2": 2, "h3": 3, "h4": 4,
|
||||
"i1": "<b 0x...><r 12>", "i2": "", "i3": "", "i4": "", "i5": "" // 2.0 CPS
|
||||
}
|
||||
```
|
||||
|
||||
> `I1–I5` — это конфиг (не согласуется по сети), значения должны **совпадать на клиенте и сервере**, регистрозависимы.
|
||||
|
||||
**Сахар-маскировка (`id`/`ip`/`ib`).** Вместо ручного `i1` задаёшь домен, протокол и
|
||||
браузер — ядро само собирает `I1`-приманку (стиль WireSock). Удобно для упрощения
|
||||
коннекта к **Cloudflare WARP**:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "wireguard",
|
||||
// … стандартные поля wireguard …
|
||||
"id": "www.google.com", "ip": "quic", "ib": "chrome" // quic: id идёт как SNI в ClientHello
|
||||
// или: "ip": "dns", "id": "www.google.com" // dns/sip: id идёт как QNAME/host
|
||||
}
|
||||
```
|
||||
|
||||
`ip` ∈ `quic|dns|stun|sip`; `id` обязателен только для `quic` (SNI); для `dns`/`sip` опционален (без него генерится псевдо-имя), `stun` игнорирует. Где задан — идёт на провод (SNI / QNAME / host)
|
||||
и опционален для `sip` (без него генерится псевдо-host) и `stun`; `ib` ∈ `chrome|firefox|curl`
|
||||
(только quic, эффект минимальный — без JA3-fingerprint). Взаимоисключается с явным `i1`.
|
||||
|
||||
Для **`quic`** ядро генерит out-of-order фрагментированный QUIC Initial (RFC 9001) — реальный
|
||||
ClientHello, нарезанный на CRYPTO-фреймы в перемешанном порядке, так что line-rate DPI парсит
|
||||
мусор и пропускает. Раскладка рандомизируется на каждый вызов (нет межюзерной сигнатуры), и
|
||||
`ip=quic` теперь шлёт **два** независимых Initial (i1+i2) — поток читается как развивающаяся
|
||||
QUIC-сессия. Это **единственный профиль, device-проверенный на реальном LTE/WARP DPI** (~330 мс).
|
||||
`dns`/`stun`/`sip` реализованы как корректные клиент-инициированные запросы, но режутся как класс
|
||||
протокола к WARP-edge (raw DNS/STUN/SIP к дата-центровому IP сам по себе аномален) — сохранены
|
||||
для других провайдеров, чей DPI проверяет лишь корректность пакета. См.
|
||||
[docs-lx/lx-config.ru.md](docs-lx/lx-config.ru.md) и [примеры SPECS/009](SPECS/009-WIRESOCK_MASQUERADE_PROFILES/EXAMPLES.md).
|
||||
|
||||
### MASQUE (outbound — Cloudflare WARP)
|
||||
|
||||
Outbound `masque` туннелирует целые IP-пакеты через **CONNECT-IP (RFC 9484)**, HTTP/3 или HTTP/2,
|
||||
к **Cloudflare WARP**. Не путать с AWG-сахаром *masquerade* `id/ip/ib` выше — разные фичи, одно слово.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"type": "masque",
|
||||
"tag": "warp",
|
||||
"server": "162.159.198.2",
|
||||
"server_port": 443,
|
||||
"profile": "cloudflare", // cloudflare (WARP) | standard (RFC 9484)
|
||||
"network": "h3", // ТРАНСПОРТ: h3 (QUIC) | h2 (HTTP/2). НЕ tcp/udp — это network_list
|
||||
"sni": "www.microsoft.com", // domain-fronting; endpoint аутентифицируется пиннингом public key, не по SNI
|
||||
"private_key": "<base64 DER EC>",
|
||||
"public_key": "<base64 DER PKIX>",
|
||||
"ip": "172.16.0.2/32", "ipv6": "2606:4700:110:...::/128"
|
||||
}
|
||||
```
|
||||
|
||||
Ключевой материал (`private_key`/`public_key`/`ip`/`ipv6`) берётся готовым из конфига — регистрацию
|
||||
устройства в WARP делает клиент. На сетях, режущих входящий UDP:443, `h3`-handshake виснет —
|
||||
переключите узел на `network: h2` (TCP:443). Полный справочник —
|
||||
[docs-lx/lx-config.ru.md §4](docs-lx/lx-config.ru.md) и [SPECS/021](SPECS/021-MASQUE_CONNECT_IP_OUTBOUND/CONFIG.md).
|
||||
|
||||
---
|
||||
|
||||
## Модель сопровождения
|
||||
|
||||
```
|
||||
upstream tag (vX.Y.Z)
|
||||
│
|
||||
└─► ветка lx = upstream + N атомарных // lx-коммитов
|
||||
├─ FORK_BOOTSTRAP (Makefile.lx, CI, версия)
|
||||
├─ XHTTP client transport
|
||||
├─ AWG2 client endpoint
|
||||
└─ … (новые фичи — такими же атомарными // lx-коммитами)
|
||||
```
|
||||
|
||||
- **Только ребейз, никогда merge.** На новый upstream-тег ветка `lx` ребейзится поверх него.
|
||||
- Каждая фича — атомарный коммит(ы), помеченный `// lx`. Новые файлы конфликтов не дают; швы в upstream-файлах малы и переносятся вручную.
|
||||
- Разработка ведётся по **Spec Kit** (`SPECS/NNN-T-S-NAME/`: SPEC → PLAN → TASKS → IMPLEMENTATION_REPORT).
|
||||
|
||||
### Remotes
|
||||
|
||||
```bash
|
||||
origin git@github.com:Leadaxe/sing-box-lx.git # ветка по умолчанию: lx
|
||||
upstream https://github.com/SagerNet/sing-box.git
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Структура lx-специфики
|
||||
|
||||
| Путь | Назначение |
|
||||
|------|------------|
|
||||
| `Makefile.lx` | сборка с lx-тегами и версией `-lx` |
|
||||
| `.github/workflows/lx-ci.yml` | CI: матрица фич (baseline/xhttp/awg/full) + negative-check + кросс-платформа + android AAR |
|
||||
| `.github/workflows/lx-release.yml` | релиз на `v*-lx.*`: desktop ×6 + `libbox.aar` → GitHub Release |
|
||||
| `SPECS/` | Spec Kit (конституция, задачи, отчёты) |
|
||||
| `lx-test/config/` | примеры конфигов для `sing-box check` |
|
||||
| `transport/v2rayxhttp/` | XHTTP-клиент (новый пакет) |
|
||||
| `transport/wireguard/device_awg.go` | AWG IpcSet-параметры (за `with_awg`) |
|
||||
| `submodules/wireguard-go` | submodule: merged-форк AmneziaWG-рантайма ([Leadaxe/wireguard-go-awg2-lx](https://github.com/Leadaxe/wireguard-go-awg2-lx)) |
|
||||
| `option/v2ray_xhttp.go`, `option/wireguard_awg.go` | опции фич |
|
||||
| `include/v2rayxhttp.go` | регистрация транспорта за build-tag |
|
||||
|
||||
Поиск всех правок upstream-файлов: `grep -rn "// lx"`.
|
||||
|
||||
---
|
||||
|
||||
## Потребитель
|
||||
|
||||
Ядро собирается для десктоп-лаунчера **singbox-launcher** (бандлит `bin/sing-box`). На Android потребитель встраивает **`libbox.aar`** (gomobile) вместо бинаря — конфиг-JSON тот же. Маппинг `type=xhttp` и AWG-полей в визарде — задачи на стороне потребителя, не здесь.
|
||||
|
||||
---
|
||||
|
||||
## Ссылки
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Upstream | [SagerNet/sing-box](https://github.com/SagerNet/sing-box) · [документация](https://sing-box.sagernet.org/) |
|
||||
| Этот форк | [Leadaxe/sing-box-lx](https://github.com/Leadaxe/sing-box-lx) |
|
||||
| AmneziaWG-рантайм | [Leadaxe/wireguard-go-awg2-lx](https://github.com/Leadaxe/wireguard-go-awg2-lx) — sagernet-база + обфускация (3-way merge) |
|
||||
| AmneziaWG upstream | [amnezia-vpn/amneziawg-go](https://github.com/amnezia-vpn/amneziawg-go) · [docs.amnezia.org](https://docs.amnezia.org/documentation/amnezia-wg/) |
|
||||
| XHTTP (исток) | [XTLS/Xray-core](https://github.com/XTLS/Xray-core) — `transport/internet/splithttp` |
|
||||
| Конфиг фич | [docs-lx/lx-config.ru.md](docs-lx/lx-config.ru.md) |
|
||||
| Spec Kit | [SPECS/](SPECS/) — [README](SPECS/README.md) · [CONSTITUTION](SPECS/CONSTITUTION.md) · [IMPLEMENTATION_PROMPT](SPECS/IMPLEMENTATION_PROMPT.md) |
|
||||
|
||||
---
|
||||
|
||||
## Лицензия
|
||||
|
||||
Наследует лицензию upstream sing-box (**GPL-3.0**). Все правки помечены `// lx` и распространяются под той же лицензией. Это неофициальный форк, не аффилирован с SagerNet.
|
||||
> Файл оставлен как указатель, чтобы у репозитория был один основной русский
|
||||
> README (`README.md`), а не два конкурирующих.
|
||||
|
||||
@@ -3,7 +3,33 @@
|
||||
| Поле | Значение |
|
||||
|------|----------|
|
||||
| Тип | B (bug) |
|
||||
| Статус | C (complete) |
|
||||
| Статус | C (complete) — guard **снят** (см. баннер ниже) |
|
||||
|
||||
> ## ⛔️ Guard снят (2026-07-26) — первопричина к shater не относится
|
||||
> **Оба guard'а (Start-guard в `protocol/wireguard/endpoint.go` и
|
||||
> selector-guard в `protocol/group/awg_selector_guard.go`) удалены**, вместе с
|
||||
> их adapter-хуками (`OutboundManager.ConsumersOf`, `AmneziaWGSuspendable`).
|
||||
> Апстрим снял их коммитом `5fa3a0a17`; сюда снятие приехало отдельно.
|
||||
>
|
||||
> **Почему.** Зависание было **Android-специфичным** (`Libbox.newService` не
|
||||
> возвращал управление). Android для shater не платформа и ей не станет —
|
||||
> мы собираем роутерный бинарь под OpenWrt/aarch64. При этом лекарство для
|
||||
> самой AWG-за-detour связки у нас уже есть: reserved-clear gate в
|
||||
> `ClientBind` (`d971eb85e` + пин сабмодуля `7d15f33`), без которого AWG не
|
||||
> поднимался вообще ни за каким detour'ом. Мы носили и лекарство, и запрет
|
||||
> на его применение.
|
||||
>
|
||||
> **Чем это было плохо на практике.** Guard отказывал **молча**: не ошибкой,
|
||||
> а `started=false`, после чего каждый дозвон падал с «WireGuard is not ready
|
||||
> yet». Конфигурация «AmneziaWG за WireGuard-хопом» выглядела не как
|
||||
> отклонённая, а как «нода почему-то не работает».
|
||||
>
|
||||
> **Регрессия:** `protocol/wireguard/awg_over_wireguard_start_lx_test.go`
|
||||
> (`with_gvisor && with_awg`) — AWG-эндпоинт с `detour` на outbound типа
|
||||
> `wireguard` доходит до PostStart и поднимает `started`. До снятия guard'а
|
||||
> тест краснел.
|
||||
>
|
||||
> **Осталось:** сквозной прогон на железе (AWG поверх реального WG-хопа).
|
||||
|
||||
Отклонять (по образцу ядрового запрета «empty direct detour») конфигурацию, где
|
||||
AmneziaWG-endpoint (источник с AWG-полями) имеет `detour` на **любой
|
||||
|
||||
@@ -157,7 +157,9 @@ if need == 0: стоп // все слоты живы, не
|
||||
|
||||
## Ошибка дайла
|
||||
|
||||
Слоты/пул **не трогаем**. По одной ошибке дайла причина неизвестна (мёртвая нода / упавший сайт назначения / своя сеть пропала — неразличимы). Состав пула меняет **только дотест** (честный health-check через `url`). Соединение просто фейлится для этого запроса.
|
||||
Слоты/пул **не трогаем** — инвариант сохранён: по одной ошибке дайла причина неизвестна (мёртвая нода / упавший сайт назначения / своя сеть пропала — неразличимы), состав пула меняет **только дотест** (честный health-check через `url`).
|
||||
|
||||
> **Обновление (план «живой пул», §5.B / health board):** поведение «соединение просто фейлится» заменено. Дайл-провал теперь пишет `MarkFailed` в health board и дайл ретраится следующим кандидатом (≤3 членов, в пределах дедлайна коннекта) — коннект юзера выживает, пока в группе есть живая нода. Слоты при этом по-прежнему физически не двигаются: мёртвый жилец остаётся в своём слоте, но вердикт board (`dead`, TTL) делает его невыбираемым на следующем pick — селекция уходит с мёртвого слота, не дожидаясь дотеста. Sticky, replace-in-slot и never-shrink не затронуты.
|
||||
|
||||
---
|
||||
|
||||
@@ -248,7 +250,7 @@ PoolSlot {
|
||||
1. `balancer`-объект; `mode` снаружи как индикатор. Липкость — плоское `balancer.sticky_hash []string` (не вложенный объект — механизм один, выбирать нечего). Дефолт (омит или `[]`)→`["process","domain"]` (липкость из коробки); выключение через sentinel **`["none"]`**. *(rc.15: изначально планировали `[]`→выкл через nil-vs-`[]`, но `badjson.UnmarshallExcludedContext` ре-маршалит структуру и схлопывает `[]`→nil — различить на проде нельзя, подтверждено живым прогоном. `["none"]` переживает round-trip.)*
|
||||
2. `pool_tolerance` — **наше** поле; апстрим `tolerance` затирается на 50, для round_robin не используется (варн).
|
||||
3. `pool < 0` → ошибка; `pool==0`/опущено → дефолт 3; `round_robin` без `balancer` → дефолты.
|
||||
4. Дайл-ошибка слоты не трогает (причина неизвестна).
|
||||
4. Дайл-ошибка слоты не трогает (причина неизвестна). *(План «живой пул» §5.B: дайл-провал теперь `MarkFailed` в board + ретрай следующим кандидатом; слоты по-прежнему не двигаются — см. «Ошибка дайла».)*
|
||||
5. Пул не пустеет — замена только при наличии живого кандидата.
|
||||
6. **Слоты фиксированы; ноды текут сквозь; delay-ранг — отдельное вычисление для выявления худшей, не перестановка слотов.**
|
||||
7. **sticky slot-hash: `slot[hash(key) % pool]` (`pool` фиксирован) → строгий ноль реконнектов для живого узла, 0 памяти.** Единственный механизм. Заменяет ОБА механизма rc.11. Модуль достаточен, т.к. число слотов не меняется — преимущество jump-hash/rendezvous (плавный ресайз) здесь не нужно.
|
||||
@@ -273,7 +275,7 @@ PoolSlot {
|
||||
- **Слоты фиксированы:** вылет ноды из середины не двигает другие слоты; победитель занимает слот вытесненного.
|
||||
- **slot-hash:** один ключ → стабильный слот при неизменном `pool`; **живой узел в своём слоте держит ВСЕ свои ключи** при замене жильцов в других слотах (ноль реконнектов); замена в слоте `k` трогает только ключи `→ k`; ключ `""` → фиксированный слот.
|
||||
- **Замена 1:1:** нет живых → мёртвая держит слот; `min(pool, nodes)`.
|
||||
- **Дайл-ошибка** не меняет состав пула.
|
||||
- **Дайл-ошибка** не меняет состав пула (но с планом «живой пул» §5.B демотит слот через вердикт board и ретраится — см. «Ошибка дайла»).
|
||||
- **Валидация:** `pool<1`, `balancer`+wrong-mode, неизвестный `sticky_hash`-компонент → ошибки; `tolerance`+round_robin → варн.
|
||||
- **Дефолт sticky_hash:** `nil` (поле опущено) → `["process","domain"]` (липкость есть); `[]` → липкости нет (round_robin по counter); различение nil-vs-`[]` после unmarshal.
|
||||
- **`least_test` дефолт** — без изменений.
|
||||
|
||||
+10
-2
@@ -19,11 +19,19 @@ type ClashServer interface {
|
||||
AddModeUpdateHook(hook *observable.Subscriber[struct{}])
|
||||
}
|
||||
|
||||
// lx:begin health-board
|
||||
// Health board (plan §5.A): a history entry now records both the last success and
|
||||
// the last failure instead of being deleted on failure. `Time` is renamed to
|
||||
// `LastOK`; its JSON tag stays "time" so the Clash API history payload is
|
||||
// unchanged, and `LastFail` is omitted when zero for the same reason.
|
||||
type URLTestHistory struct {
|
||||
Time time.Time `json:"time"`
|
||||
Delay uint16 `json:"delay"`
|
||||
LastOK time.Time `json:"time"`
|
||||
Delay uint16 `json:"delay"`
|
||||
LastFail time.Time `json:"last_fail,omitzero"`
|
||||
}
|
||||
|
||||
// lx:end health-board
|
||||
|
||||
type V2RayServer interface {
|
||||
LifecycleService
|
||||
StatsService() ConnectionTracker
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
// lx:begin l3-honest-drop
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun/gtcpip/header"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// judgeFlowRouter answers PreMatch with a canned verdict; JudgeFlow reads
|
||||
// nothing else off the Router.
|
||||
type judgeFlowRouter struct {
|
||||
Router
|
||||
result PreMatchResult
|
||||
}
|
||||
|
||||
func (r *judgeFlowRouter) PreMatch(InboundContext, []byte) PreMatchResult { return r.result }
|
||||
|
||||
// judgeFlowPort is the tun.Port half of a FlowOutbound. inet4 is what
|
||||
// PortAddresses reports for IPv4 — the one field the two ICMP consumers in
|
||||
// sing-tun disagree about (see the comment on
|
||||
// TestJudgeFlowICMPToBoundPortStaysAFlow).
|
||||
type judgeFlowPort struct {
|
||||
Outbound
|
||||
inet4 netip.Addr
|
||||
}
|
||||
|
||||
func (o *judgeFlowPort) Tag() string { return "wg-out" }
|
||||
func (o *judgeFlowPort) Type() string { return "wireguard" }
|
||||
func (o *judgeFlowPort) PortAddresses() (netip.Addr, netip.Addr) {
|
||||
return o.inet4, netip.Addr{}
|
||||
}
|
||||
func (o *judgeFlowPort) PortMTU() uint32 { return 1420 }
|
||||
func (o *judgeFlowPort) AttachReturn(tun.Return) error { return nil }
|
||||
func (o *judgeFlowPort) DetachReturn(tun.Return) error { return nil }
|
||||
func (o *judgeFlowPort) WritePackets(packets [][]byte) error { return nil }
|
||||
|
||||
// judgeFlowNonPort is a FlowOutbound-shaped result that is NOT a tun.Port — the
|
||||
// interface drift the second line of defense in JudgeFlow exists for.
|
||||
type judgeFlowNonPort struct {
|
||||
Outbound
|
||||
}
|
||||
|
||||
func (o *judgeFlowNonPort) Tag() string { return "drifted" }
|
||||
func (o *judgeFlowNonPort) Type() string { return "drifted" }
|
||||
|
||||
func judgeFlow(t *testing.T, protocol uint8, result PreMatchResult) tun.FlowVerdict {
|
||||
t.Helper()
|
||||
return JudgeFlow(
|
||||
&judgeFlowRouter{result: result},
|
||||
"l3-in", "tun", protocol,
|
||||
netip.MustParseAddrPort("192.168.1.2:1234"),
|
||||
netip.MustParseAddrPort("1.1.1.1:1234"),
|
||||
nil,
|
||||
)
|
||||
}
|
||||
|
||||
const (
|
||||
judgeFlowICMP = uint8(header.ICMPv4ProtocolNumber)
|
||||
judgeFlowTCP = uint8(header.TCPProtocolNumber)
|
||||
)
|
||||
|
||||
// TestJudgeFlowICMPToBoundPortStaysAFlow is the guard on the ONE fix that must
|
||||
// not be made here.
|
||||
//
|
||||
// sing-tun has two ICMP consumers with different requirements on the port:
|
||||
//
|
||||
// - ForwardDispatcher.createFlow (flow_dispatch.go) needs only a VALID port
|
||||
// address — it NATs the echo identifier and rewrites the source to that
|
||||
// address. This is the path every unfragmented LAN ping takes, and it is
|
||||
// what makes ping-through-WireGuard/AWG work at all.
|
||||
// - ICMPForwarder.installFlow (stack_gvisor_icmp.go) additionally requires the
|
||||
// address to be UNSPECIFIED, because it writes the packet to the port
|
||||
// unmodified. A WireGuard endpoint reports its concrete interface address
|
||||
// (transport/wireguard/port.go), so installFlow declines and HandlePacket
|
||||
// falls through to forging the echo reply.
|
||||
//
|
||||
// The tempting fix — "for ICMP, refuse ActionFlow when PortAddresses() is not
|
||||
// unspecified, so the verdict becomes a drop and the forgery is unreachable" —
|
||||
// is applied HERE, in the one function both consumers share, with byte-identical
|
||||
// arguments from either. It would therefore kill the working path too: every
|
||||
// ping through WireGuard/AWG, fragmented or not, would drop, and l3_tunnel would
|
||||
// carry nothing but `direct`. Keep this test failing loudly if anyone tries.
|
||||
func TestJudgeFlowICMPToBoundPortStaysAFlow(t *testing.T) {
|
||||
t.Parallel()
|
||||
port := &judgeFlowPort{inet4: netip.MustParseAddr("10.2.0.2")}
|
||||
verdict := judgeFlow(t, judgeFlowICMP, PreMatchResult{Action: PreMatchFlow, Outbound: port})
|
||||
require.Equal(t, tun.ActionFlow, verdict.Action,
|
||||
"ICMP to a WireGuard/AWG endpoint must stay a flow: the forward dispatcher NATs it by echo identifier and this is the whole point of l3_tunnel")
|
||||
require.Same(t, tun.Port(port), verdict.Port)
|
||||
}
|
||||
|
||||
// The `direct` shape: an unspecified port address. Both consumers accept it.
|
||||
func TestJudgeFlowICMPToUnspecifiedPortStaysAFlow(t *testing.T) {
|
||||
t.Parallel()
|
||||
port := &judgeFlowPort{inet4: netip.IPv4Unspecified()}
|
||||
verdict := judgeFlow(t, judgeFlowICMP, PreMatchResult{Action: PreMatchFlow, Outbound: port})
|
||||
require.Equal(t, tun.ActionFlow, verdict.Action)
|
||||
require.Same(t, tun.Port(port), verdict.Port)
|
||||
}
|
||||
|
||||
// PreMatchDrop is the honest verdict and must arrive as ActionDrop: it is the
|
||||
// only value (besides Reject) that stops ICMPForwarder.HandlePacket before the
|
||||
// Echo -> EchoReply rewrite.
|
||||
func TestJudgeFlowICMPDropReachesTheStackAsDrop(t *testing.T) {
|
||||
t.Parallel()
|
||||
verdict := judgeFlow(t, judgeFlowICMP, PreMatchResult{Action: PreMatchDrop})
|
||||
require.Equal(t, tun.ActionDrop, verdict.Action)
|
||||
}
|
||||
|
||||
// The second line of defense: a PreMatchFlow whose outbound is not a tun.Port
|
||||
// must not degrade ICMP to ActionAccept, because Accept is the forged reply.
|
||||
func TestJudgeFlowICMPNonPortOutboundDrops(t *testing.T) {
|
||||
t.Parallel()
|
||||
verdict := judgeFlow(t, judgeFlowICMP, PreMatchResult{Action: PreMatchFlow, Outbound: &judgeFlowNonPort{}})
|
||||
require.Equal(t, tun.ActionDrop, verdict.Action,
|
||||
"FlowOutbound and tun.Port are distinct interfaces; a drift between them must not silently re-enable the echo forger")
|
||||
}
|
||||
|
||||
func TestJudgeFlowTCPNonPortOutboundAccepts(t *testing.T) {
|
||||
t.Parallel()
|
||||
verdict := judgeFlow(t, judgeFlowTCP, PreMatchResult{Action: PreMatchFlow, Outbound: &judgeFlowNonPort{}})
|
||||
require.Equal(t, tun.ActionAccept, verdict.Action,
|
||||
"for TCP, falling back to Accept is upstream behaviour and must stay untouched")
|
||||
}
|
||||
|
||||
// TCP keeps every mapping it had, including the Continue -> Accept default that
|
||||
// is a forgery only for ICMP.
|
||||
func TestJudgeFlowTCPContinueStaysAccept(t *testing.T) {
|
||||
t.Parallel()
|
||||
verdict := judgeFlow(t, judgeFlowTCP, PreMatchResult{Action: PreMatchContinue})
|
||||
require.Equal(t, tun.ActionAccept, verdict.Action)
|
||||
}
|
||||
|
||||
func TestJudgeFlowTCPBypassStaysBypass(t *testing.T) {
|
||||
t.Parallel()
|
||||
verdict := judgeFlow(t, judgeFlowTCP, PreMatchResult{Action: PreMatchBypass})
|
||||
require.Equal(t, tun.ActionBypass, verdict.Action)
|
||||
}
|
||||
|
||||
// lx:end l3-honest-drop
|
||||
@@ -45,30 +45,8 @@ type OutboundManager interface {
|
||||
Default() Outbound
|
||||
Remove(tag string) error
|
||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, outboundType string, options any) error
|
||||
// lx:begin awg
|
||||
// ConsumersOf returns the tags of outbounds that depend on (detour through)
|
||||
// the given tag — the reverse of Dependencies(). Used by the selector guard to
|
||||
// walk up to AmneziaWG consumers when a group switches to a WireGuard member.
|
||||
ConsumersOf(tag string) []string
|
||||
// lx:end awg
|
||||
}
|
||||
|
||||
// lx:begin awg
|
||||
// AmneziaWGSuspendable is implemented by an AmneziaWG endpoint so the selector
|
||||
// guard can suspend it (bring its device down) when a group it detours through
|
||||
// switches to a WireGuard member — AmneziaWG inside a WireGuard tunnel hangs the
|
||||
// kernel on Android. The marker lives in adapter so protocol/group can act on it
|
||||
// without importing protocol/wireguard.
|
||||
type AmneziaWGSuspendable interface {
|
||||
// IsAmneziaWG reports whether this endpoint runs AmneziaWG (has AWG params).
|
||||
IsAmneziaWG() bool
|
||||
// SuspendAmneziaWG brings the device down so no junk handshake is sent. It is
|
||||
// idempotent and safe to call on a not-yet-started or already-suspended endpoint.
|
||||
SuspendAmneziaWG()
|
||||
}
|
||||
|
||||
// lx:end awg
|
||||
|
||||
// lx:begin idle-suspend
|
||||
// IdleSuspendable is implemented by a WG/AWG endpoint so the router's idle tick
|
||||
// (SPEC 020) can suspend it when it is idle and unreachable, without importing
|
||||
|
||||
@@ -208,21 +208,6 @@ func (m *Manager) Outbound(tag string) (adapter.Outbound, bool) {
|
||||
return m.endpoint.Get(tag)
|
||||
}
|
||||
|
||||
// lx:begin awg
|
||||
// ConsumersOf returns a copy of the tags that detour through tag (reverse of
|
||||
// Dependencies()), built from the dependByTag ledger populated at Create time.
|
||||
func (m *Manager) ConsumersOf(tag string) []string {
|
||||
m.access.RLock()
|
||||
defer m.access.RUnlock()
|
||||
consumers := m.dependByTag[tag]
|
||||
if len(consumers) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append([]string(nil), consumers...)
|
||||
}
|
||||
|
||||
// lx:end awg
|
||||
|
||||
func (m *Manager) Default() adapter.Outbound {
|
||||
m.access.RLock()
|
||||
defer m.access.RUnlock()
|
||||
|
||||
@@ -75,7 +75,18 @@ func JudgeFlow(router Router, inbound string, inboundType string, network uint8,
|
||||
case PreMatchFlow:
|
||||
port, isPort := result.Outbound.(tun.Port)
|
||||
if !isPort {
|
||||
// lx:begin l3-honest-drop
|
||||
// Second line of defense behind route.(*Router).preMatchFlow: a
|
||||
// PreMatchFlow result already implies the outbound is an
|
||||
// adapter.FlowOutbound, but FlowOutbound and tun.Port are distinct
|
||||
// interfaces, and a drift between them must not degrade ICMP to
|
||||
// ActionAccept — the TUN stack would then forge the echo reply
|
||||
// itself instead of admitting the tunnel cannot carry the packet.
|
||||
if networkName == N.NetworkICMP {
|
||||
return tun.FlowVerdict{Action: tun.ActionDrop}
|
||||
}
|
||||
return tun.FlowVerdict{Action: tun.ActionAccept}
|
||||
// lx:end l3-honest-drop
|
||||
}
|
||||
verdict := tun.FlowVerdict{Action: tun.ActionFlow, Port: port, UDPTimeout: result.UDPTimeout, NewTracker: result.NewTracker}
|
||||
if result.Destination.IsValid() {
|
||||
|
||||
+37
-17
@@ -1,6 +1,6 @@
|
||||
#!/bin/sh
|
||||
# ci/build-feed-apk.sh — build the signed **apk** feed for ONE arch (the 25.12
|
||||
# lane — additive next to ci/build-feed.sh, which stays the opkg/24.10 lane).
|
||||
# ci/build-feed-apk.sh — build the signed **apk** feed for ONE arch (25.12+;
|
||||
# the only packaging lane shater has — see docs-shater/DECISIONS.md D22).
|
||||
#
|
||||
# Usage: ci/build-feed-apk.sh <ARCH> <SDK_URL> <OUTDIR>
|
||||
# e.g. ci/build-feed-apk.sh aarch64_cortex-a53 \
|
||||
@@ -10,14 +10,14 @@
|
||||
# This is the per-arch entrypoint the Gitea workflow's `build-apk` job calls.
|
||||
# It runs on the CI RUNNER and:
|
||||
# 1. asserts the prebuilt shaterd binary for this arch was already staged by
|
||||
# scripts/build-shaterd.sh (same artifact-order contract as the opkg lane);
|
||||
# 2. drives a plain `debian:bookworm` container (workspace shared via
|
||||
# `--volumes-from`, same trick as ci/build-feed.sh) that downloads the
|
||||
# ImmortalWrt 25.12 apk-SDK tarball and runs ci/sdk-build-apk.sh in it:
|
||||
# compile the 4 packages as .apk, then `apk mkndx --sign` the per-arch
|
||||
# `packages.adb` index. Unlike the usign lane (index signed on the runner),
|
||||
# apk indexing NEEDS the SDK's host `apk` tool, so index+sign happen inside
|
||||
# the container.
|
||||
# scripts/build-shaterd.sh (the artifact-order contract);
|
||||
# 2. drives a plain `debian:bookworm` container (the job's workspace volume is
|
||||
# shared into it with `--volumes-from $(hostname)`; a bare `-v $PWD:...`
|
||||
# points at a host path that does not exist under act_runner's DinD) that
|
||||
# downloads the ImmortalWrt 25.12 apk-SDK tarball and runs
|
||||
# ci/sdk-build-apk.sh in it: compile the 4 packages as .apk, then
|
||||
# `apk mkndx --sign` the per-arch `packages.adb` index. Indexing NEEDS the
|
||||
# SDK's host `apk` tool, so index+sign happen inside the container.
|
||||
#
|
||||
# Why the ImmortalWrt SDK (not openwrt/sdk images): the 25.12 fleet runs
|
||||
# BananaWRT 25.12-mtk-vendor = ImmortalWrt 25.12 base (target mediatek/filogic,
|
||||
@@ -25,9 +25,9 @@
|
||||
# mediatek-filogic 25.12 tag — hence the official SDK tarball.
|
||||
#
|
||||
# Env:
|
||||
# KEY_APK EC (prime256v1) PRIVATE key PEM (Gitea repo secret — the apk analog
|
||||
# of KEY_BUILD). If set, packages.adb carries an embedded signature
|
||||
# verifiable by dist/shater-apk.pem (routers: /etc/apk/keys/).
|
||||
# KEY_APK EC (prime256v1) PRIVATE key PEM (Gitea repo secret). If set,
|
||||
# packages.adb carries an embedded signature verifiable by
|
||||
# dist/shater-apk.pem (routers: /etc/apk/keys/).
|
||||
# If unset, an UNSIGNED index is produced (warning; not shippable —
|
||||
# apk signatures are effectively mandatory).
|
||||
set -eu
|
||||
@@ -55,6 +55,15 @@ fi
|
||||
|
||||
chmod +x "$REPO"/ci/*.sh 2>/dev/null || true
|
||||
|
||||
# --- 0.4) package version from the git tag ------------------------------------
|
||||
# The workflow puts these in the job env via `ci/version.sh --env >>
|
||||
# $GITHUB_ENV`; recompute here when run standalone. Passed into the container
|
||||
# below and re-exported to the unprivileged build user in ci/sdk-build-apk.sh.
|
||||
if [ -z "${SHATER_PKG_VERSION:-}" ] || [ -z "${SHATER_PKG_RELEASE:-}" ]; then
|
||||
eval "$(sh "$REPO/ci/version.sh" --env)"
|
||||
fi
|
||||
echo "[apk-feed] package version: ${SHATER_PKG_VERSION}-r${SHATER_PKG_RELEASE}"
|
||||
|
||||
# --- 0.5) runner-side caches --------------------------------------------------
|
||||
# All under $REPO/.cache so (a) actions/cache in the workflow can persist them
|
||||
# between runs and (b) the nested container sees them via --volumes-from.
|
||||
@@ -63,11 +72,20 @@ chmod +x "$REPO"/ci/*.sh 2>/dev/null || true
|
||||
# SDK; PKG_HASH still verifies every file, so stale = re-downloaded.
|
||||
# apt/ debian:bookworm .deb archives for the host-deps install.
|
||||
# The nested container runs the build as an unprivileged user -> must be writable
|
||||
# (same reason as the chmod 0777 "$OUT" in ci/build-feed.sh).
|
||||
# (same reason as the chmod 0777 "$OUT" above).
|
||||
CACHE="$REPO/.cache"
|
||||
mkdir -p "$CACHE/sdk" "$CACHE/dl" "$CACHE/apt"
|
||||
chmod -R a+rwX "$CACHE/dl" "$CACHE/apt" 2>/dev/null || true
|
||||
|
||||
# feeds/ git checkouts (actions/cache key: feeds-apk-<release>) — symlinked
|
||||
# over the SDK's feeds dir inside the container (ci/sdk-build-apk.sh) so
|
||||
# `scripts/feeds update -a` fetches deltas instead of re-cloning the
|
||||
# ImmortalWrt feeds every run. Top-level chmod only: contents are created and
|
||||
# owned by the container's uid-1000 build user (restore preserves ownership).
|
||||
FEEDS_CACHE="$CACHE/feeds/apk"
|
||||
mkdir -p "$FEEDS_CACHE"
|
||||
chmod a+rwX "$CACHE" "$CACHE/feeds" "$FEEDS_CACHE" 2>/dev/null || true
|
||||
|
||||
# Fetch the SDK tarball ON THE RUNNER (restored cache -> own Gitea release-asset
|
||||
# mirror -> upstream with stall-kill + retries) instead of the old bare
|
||||
# `wget` inside the container, which hung whole runs when
|
||||
@@ -77,14 +95,16 @@ sh "$REPO/ci/fetch-sdk.sh" "$SDK_URL" "$SDK_TAR"
|
||||
|
||||
# --- 1) SDK build + index + sign inside a debian container -------------------
|
||||
# `--volumes-from $(hostname)` shares THIS job container's workspace volume into
|
||||
# the nested container (see ci/build-feed.sh for why a bare -v does not work on
|
||||
# the act_runner DinD setup).
|
||||
# the nested container: a bare `-v $PWD:...` points at a host path that does not
|
||||
# exist under the act_runner DinD setup.
|
||||
echo "[apk-feed] SDK build arch=$ARCH (ImmortalWrt 25.12 apk-SDK)"
|
||||
docker pull -q debian:bookworm
|
||||
docker run --rm --volumes-from "$(hostname)" \
|
||||
-e ARCH="$ARCH" -e REPO="$REPO" -e OUT="$OUT" -e SDK_URL="$SDK_URL" \
|
||||
-e SDK_TAR="$SDK_TAR" -e DL_DIR="$CACHE/dl" -e APT_CACHE="$CACHE/apt" \
|
||||
-e KEY_APK="${KEY_APK:-}" \
|
||||
-e FEEDS_CACHE="$FEEDS_CACHE" -e KEY_APK="${KEY_APK:-}" \
|
||||
-e SHATER_PKG_VERSION="$SHATER_PKG_VERSION" \
|
||||
-e SHATER_PKG_RELEASE="$SHATER_PKG_RELEASE" \
|
||||
debian:bookworm bash "$REPO/ci/sdk-build-apk.sh"
|
||||
|
||||
# --- 2) sanity: the per-arch apk repo dir must be complete -------------------
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/bin/sh
|
||||
# ci/build-feed.sh — build the signed opkg feed for ONE arch.
|
||||
#
|
||||
# Usage: ci/build-feed.sh <ARCH> <SDK_DOCKER_TAG> <OUTDIR>
|
||||
# e.g. ci/build-feed.sh x86_64 x86_64-24.10.4 out/x86_64
|
||||
# ci/build-feed.sh aarch64_cortex-a53 mediatek-filogic-24.10.4 out/aarch64_cortex-a53
|
||||
#
|
||||
# This is the reusable per-arch entrypoint the Gitea workflow calls. It runs on
|
||||
# the CI RUNNER and:
|
||||
# 1. asserts the prebuilt shaterd binary for this arch was already staged by
|
||||
# scripts/build-shaterd.sh (into openwrt/shaterd/files/) — proving artifact
|
||||
# order: SPA+shaterd build BEFORE the SDK package build;
|
||||
# 2. drives the arch-matched `openwrt/sdk` docker image to compile all 4
|
||||
# packages (ci/sdk-build.sh) and collect their .ipk into OUTDIR;
|
||||
# 3. builds + usign-signs the opkg `Packages` index over OUTDIR
|
||||
# (ci/install-usign.sh + ci/make-index.sh; signs iff $KEY_BUILD is set).
|
||||
#
|
||||
# Env:
|
||||
# KEY_BUILD usign SECRET key (Gitea repo secret). If set, the feed index is
|
||||
# signed and verifiable by dist/shater-feed.pub (fp 5ac4b177689cb8e0).
|
||||
# If unset, an UNSIGNED feed is produced (make-index warns).
|
||||
set -eu
|
||||
|
||||
ARCH="${1:?arch required (x86_64 | aarch64_cortex-a53)}"
|
||||
SDK_TAG="${2:?sdk docker tag required (e.g. x86_64-24.10.4)}"
|
||||
OUT="${3:?output dir required}"
|
||||
|
||||
REPO="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
mkdir -p "$OUT"; OUT="$(cd "$OUT" && pwd)"
|
||||
# $OUT is created here as ROOT on the runner, but the nested `openwrt/sdk`
|
||||
# container runs as the unprivileged `buildbot` (uid 1000) — so it must be able
|
||||
# to write the collected .ipk into $OUT. World-writable is set HERE (a chmod
|
||||
# from inside the container, as buildbot, cannot fix a root-owned dir).
|
||||
chmod 0777 "$OUT"
|
||||
|
||||
# --- 0) the prebuilt shaterd binary must already be staged for this arch ------
|
||||
case "$ARCH" in
|
||||
x86_64) sfx=amd64 ;;
|
||||
aarch64_cortex-a53) sfx=arm64 ;;
|
||||
*) echo "[feed] ERROR: unsupported ARCH '$ARCH'"; exit 2 ;;
|
||||
esac
|
||||
if [ ! -f "$REPO/openwrt/shaterd/files/shaterd-$sfx.upx" ]; then
|
||||
echo "[feed] ERROR: openwrt/shaterd/files/shaterd-$sfx.upx not staged."
|
||||
echo " Run scripts/build-shaterd.sh BEFORE ci/build-feed.sh." >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
chmod +x "$REPO"/ci/*.sh 2>/dev/null || true
|
||||
|
||||
# --- 0.5) persistent dl/ (package source tarballs) ----------------------------
|
||||
# Workspace dir restored/saved by actions/cache in the workflow and shared into
|
||||
# the nested SDK container via --volumes-from; becomes CONFIG_DOWNLOAD_FOLDER
|
||||
# there (ci/sdk-build.sh). PKG_HASH still verifies every file, so a stale cache
|
||||
# can never produce a wrong build. Must be writable by the container's
|
||||
# unprivileged buildbot user (same reason as the $OUT chmod above).
|
||||
DL_DIR="$REPO/.cache/dl"
|
||||
mkdir -p "$DL_DIR"
|
||||
chmod -R a+rwX "$DL_DIR" 2>/dev/null || true
|
||||
|
||||
# --- 1) SDK package build (4 packages) in the arch-matched SDK image ----------
|
||||
# We drive the `openwrt/sdk` docker image directly (not openwrt/gh-action-sdk):
|
||||
# on a self-hosted Gitea act_runner the marketplace action fetch can be
|
||||
# unavailable, and we need a CLEAN single-feed layout. `--volumes-from
|
||||
# $(hostname)` shares THIS job container's workspace volume into the nested SDK
|
||||
# container — a bare `-v $PWD:...` points at a host path that does not exist
|
||||
# under the act_runner DinD setup. (Requires the job to run inside a container,
|
||||
# which Gitea Actions does by default.)
|
||||
echo "[feed] SDK build arch=$ARCH image=openwrt/sdk:$SDK_TAG"
|
||||
docker pull "openwrt/sdk:$SDK_TAG"
|
||||
docker run --rm --volumes-from "$(hostname)" \
|
||||
-e ARCH="$ARCH" -e REPO="$REPO" -e OUT="$OUT" -e DL_DIR="$DL_DIR" \
|
||||
"openwrt/sdk:$SDK_TAG" \
|
||||
sh "$REPO/ci/sdk-build.sh"
|
||||
|
||||
# --- 2) index + sign the per-arch feed (usign, KEY_BUILD passed through) -------
|
||||
sh "$REPO/ci/install-usign.sh"
|
||||
KEY_BUILD="${KEY_BUILD:-}" bash "$REPO/ci/make-index.sh" "$OUT"
|
||||
|
||||
echo "[feed] done arch=$ARCH -> $OUT"
|
||||
ls -l "$OUT"
|
||||
+7
-10
@@ -2,24 +2,21 @@
|
||||
# ci/gen-apk-key.sh — generate the Shater **apk** feed signing keypair (25.12 lane).
|
||||
#
|
||||
# apk (OpenWrt/ImmortalWrt 25.12+) verifies package indexes with EC keys
|
||||
# (prime256v1 PEM), NOT usign — the existing usign identity
|
||||
# (dist/shater-feed.pub, fp 5ac4b177689cb8e0) keeps signing the opkg/24.10 feed
|
||||
# and is NOT touched by this script. This generates a SEPARATE, second identity:
|
||||
# (prime256v1 PEM). This is the ONLY feed identity shater has since the opkg
|
||||
# lane was removed (D22) — the old usign key is history, not a second lane.
|
||||
#
|
||||
# dist/shater-apk.key EC PRIVATE key. NEVER commit (dist/ is gitignored).
|
||||
# Paste its full PEM contents into the Gitea repo secret
|
||||
# KEY_APK (the apk analog of the usign secret KEY_BUILD).
|
||||
# Then delete the local file (or keep it in a password
|
||||
# manager as the offline backup — losing it means every
|
||||
# deployed router must re-trust a new key).
|
||||
# dist/shater-apk.pem PUBLIC key. Commit it next to shater-feed.pub:
|
||||
# KEY_APK. Then delete the local file (or keep it in a
|
||||
# password manager as the offline backup — losing it
|
||||
# means every deployed router must re-trust a new key).
|
||||
# dist/shater-apk.pem PUBLIC key. Commit it:
|
||||
# git add -f dist/shater-apk.pem
|
||||
# (-f because /dist/ is gitignored). Routers install it
|
||||
# as /etc/apk/keys/shater-apk.pem.
|
||||
#
|
||||
# Run ONCE. Refuses to overwrite: regenerating the key invalidates the trust of
|
||||
# every router that already installed shater-apk.pem (same rule as D7 for the
|
||||
# usign key).
|
||||
# every router that already installed shater-apk.pem (see D22).
|
||||
set -eu
|
||||
|
||||
REPO="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Make `usign` available on the CI runner so ci/make-index.sh can sign the opkg
|
||||
# feed index. The OpenWrt SDK ships usign, but the index/signing step runs on the
|
||||
# bare runner (outside the SDK container), so we build the tiny standalone tool
|
||||
# from source (no libubox — it is intentionally dependency-free so it can
|
||||
# bootstrap a build system). No-op if usign is already on PATH.
|
||||
#
|
||||
# Ported unchanged from Shater v0.1 (ci/install-usign.sh): usign is
|
||||
# format-agnostic and the signing story is identical for the v0.2 4-package feed.
|
||||
#
|
||||
# CI cache: a previously-built binary is reused from $USIGN_CACHE (default:
|
||||
# <repo>/.cache/tools — a workspace dir the workflow persists via actions/cache),
|
||||
# skipping the apt + cmake + clone + build (~1 min). After a fresh build the
|
||||
# binary is copied there so the NEXT run hits the cache. usign is a tiny static
|
||||
# helper with no versioned protocol — a stale cached binary cannot mis-sign.
|
||||
set -eu
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
TOOLS="${USIGN_CACHE:-$REPO_ROOT/.cache/tools}"
|
||||
|
||||
# place <binary> — install onto PATH (system-wide if we can, else ~/bin)
|
||||
place() {
|
||||
local SUDO=""; [ "$(id -u)" = 0 ] || SUDO="sudo"
|
||||
if $SUDO install -m0755 "$1" /usr/local/bin/usign 2>/dev/null; then
|
||||
:
|
||||
else
|
||||
mkdir -p "$HOME/bin"
|
||||
install -m0755 "$1" "$HOME/bin/usign"
|
||||
echo "$HOME/bin" >> "${GITHUB_PATH:-/dev/null}"
|
||||
export PATH="$HOME/bin:$PATH"
|
||||
fi
|
||||
}
|
||||
|
||||
if command -v usign >/dev/null 2>&1; then
|
||||
echo "[usign] already present: $(command -v usign)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ -x "$TOOLS/usign" ]; then
|
||||
place "$TOOLS/usign"
|
||||
echo "[usign] restored from cache: $(command -v usign || echo "$HOME/bin/usign")"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
SUDO=""; [ "$(id -u)" = 0 ] || SUDO="sudo"
|
||||
if ! command -v cmake >/dev/null 2>&1 || ! command -v cc >/dev/null 2>&1; then
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq cmake gcc git
|
||||
fi
|
||||
|
||||
tmp="$(mktemp -d)"
|
||||
# Canonical source; fall back to the GitHub mirror if git.openwrt.org is flaky.
|
||||
git clone --depth 1 https://git.openwrt.org/project/usign.git "$tmp/usign" \
|
||||
|| git clone --depth 1 https://github.com/openwrt/usign.git "$tmp/usign"
|
||||
( cd "$tmp/usign" && cmake -DCMAKE_BUILD_TYPE=Release . >/dev/null && make >/dev/null )
|
||||
|
||||
place "$tmp/usign/usign"
|
||||
# seed the cache for the next run (best-effort)
|
||||
mkdir -p "$TOOLS" 2>/dev/null && install -m0755 "$tmp/usign/usign" "$TOOLS/usign" 2>/dev/null || true
|
||||
echo "[usign] built: $(command -v usign || echo "$HOME/bin/usign")"
|
||||
@@ -1,39 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Build the opkg feed index (Packages + Packages.gz) with SHA256 for a dir of
|
||||
# .ipk files, then optionally usign-sign it if $KEY_BUILD (the Gitea repo secret)
|
||||
# is set and usign is present. Arg $1 = feed dir.
|
||||
#
|
||||
# Ported from Shater v0.1 (ci/make-index.sh), unchanged. It is package-count and
|
||||
# package-name agnostic: it indexes whatever .ipk are in the dir, so it serves
|
||||
# BOTH the per-arch feed built by ci/build-feed.sh AND the combined release feed
|
||||
# assembled in the release job (shaterd + byedpi per-arch, shater-core +
|
||||
# luci-app-shater = _all). opkg filters by Architecture at install time, so one
|
||||
# combined URL serves every device.
|
||||
#
|
||||
# Feed format: opkg `src/gz` (.ipk + text Packages index, usign signature).
|
||||
# OpenWrt 24.10 (our SDK) still uses opkg; apk arrives at 25.12. The committed
|
||||
# trust anchor dist/shater-feed.pub is a usign (Ed25519) key, matching this.
|
||||
set -e
|
||||
OUT="${1:?feed dir required}"; cd "$OUT"
|
||||
: > Packages
|
||||
for ipk in *.ipk; do
|
||||
[ -e "$ipk" ] || continue
|
||||
ctrl=$(tar -xzOf "$ipk" ./control.tar.gz | tar -xzO ./control)
|
||||
sz=$(wc -c < "$ipk"); sha=$(sha256sum "$ipk" | cut -d' ' -f1)
|
||||
printf '%s\n' "$ctrl" | sed '/^[[:space:]]*$/d' >> Packages
|
||||
printf 'Filename: %s\nSize: %s\nSHA256sum: %s\n\n' "$ipk" "$sz" "$sha" >> Packages
|
||||
done
|
||||
gzip -kf Packages
|
||||
|
||||
if [ -n "${KEY_BUILD:-}" ]; then
|
||||
# Signing was requested — a missing/broken signer must FAIL the build, not
|
||||
# silently ship an unsigned feed that routers with check_signature on reject.
|
||||
command -v usign >/dev/null 2>&1 || { echo "[index] ERROR: KEY_BUILD set but usign not found" >&2; exit 1; }
|
||||
umask 077; printf '%s\n' "$KEY_BUILD" > /tmp/usign.sec
|
||||
usign -S -m Packages -s /tmp/usign.sec || { rm -f /tmp/usign.sec; echo "[index] ERROR: usign signing failed" >&2; exit 1; }
|
||||
rm -f /tmp/usign.sec
|
||||
echo "[index] signed -> Packages.sig ($(head -1 Packages.sig))"
|
||||
else
|
||||
echo "[index] no KEY_BUILD -> UNSIGNED feed (opkg needs check_signature off, or set the secret)"
|
||||
fi
|
||||
echo "[index] contents:"; ls -l
|
||||
+264
-6
@@ -10,7 +10,6 @@
|
||||
# the target fleet (BananaWRT 25.12-mtk-vendor = ImmortalWrt 25.12 base, its
|
||||
# distfeeds even point at downloads.immortalwrt.org/releases/25.12-SNAPSHOT) is
|
||||
# ImmortalWrt — so we extract the official ImmortalWrt SDK tarball ourselves.
|
||||
# Same --volumes-from workspace-sharing pattern as ci/sdk-build.sh (opkg lane).
|
||||
#
|
||||
# The OpenWrt buildsystem refuses to run as root, so the SDK build itself runs
|
||||
# as an unprivileged `build` user created here.
|
||||
@@ -28,11 +27,16 @@ SDK_URL="${SDK_URL:?SDK_URL env required}"
|
||||
|
||||
echo "[apk-sdk] arch=$ARCH repo=$REPO out=$OUT"
|
||||
echo "[apk-sdk] sdk=$SDK_URL"
|
||||
# Package version derived from the git tag by ci/version.sh (bug B4). Forwarded
|
||||
# to the unprivileged build user on the `su` line at the bottom of this file;
|
||||
# openwrt/{shaterd,shater-core,luci-app-shater}/Makefile pick it up from the
|
||||
# environment. byedpi keeps upstream ByeDPI's own version (see its Makefile).
|
||||
echo "[apk-sdk] package version: ${SHATER_PKG_VERSION:-<unset -> Makefile fallback>}-r${SHATER_PKG_RELEASE:-?}"
|
||||
test -f "$REPO/openwrt/shaterd/Makefile" || {
|
||||
echo "[apk-sdk] ERROR: feed not mounted ($REPO/openwrt/shaterd/Makefile missing)"; ls -la "$REPO" || true; exit 9; }
|
||||
|
||||
# The prebuilt shaterd artifact must already be staged for this arch (same
|
||||
# contract as the opkg lane — scripts/build-shaterd.sh runs first).
|
||||
# The prebuilt shaterd artifact must already be staged for this arch
|
||||
# (artifact-order contract — scripts/build-shaterd.sh runs first).
|
||||
case "$ARCH" in
|
||||
x86_64) sfx=amd64 ;;
|
||||
aarch64_cortex-a53) sfx=arm64 ;;
|
||||
@@ -108,15 +112,126 @@ export HOME=/home/build
|
||||
cd "$SDKDIR"
|
||||
|
||||
# Register this repo's openwrt/ as a src-link feed named `shater` (absolute
|
||||
# path required) — identical to the opkg lane (ci/sdk-build.sh).
|
||||
# path required).
|
||||
cp -f feeds.conf.default feeds.conf
|
||||
grep -q '^src-link shater ' feeds.conf || echo "src-link shater $REPO/openwrt" >> feeds.conf
|
||||
|
||||
# Persistent feeds checkouts: $FEEDS_CACHE (workspace dir, actions/cache-
|
||||
# persisted, visible via --volumes-from) replaces the fresh SDK's empty feeds/
|
||||
# dir, so `feeds update` git-fetches deltas instead of re-cloning the
|
||||
# ImmortalWrt feeds every run. Update always checks out feeds.conf's pinned
|
||||
# revisions; on any failure with cached checkouts the cache is wiped and the
|
||||
# update retried with fresh clones — a stale cache can never wedge the build.
|
||||
if [ -n "${FEEDS_CACHE:-}" ] && mkdir -p "$FEEDS_CACHE" 2>/dev/null; then
|
||||
rm -rf feeds
|
||||
ln -s "$FEEDS_CACHE" feeds
|
||||
echo "[apk-sdk] feeds/ -> $FEEDS_CACHE (persistent cache)"
|
||||
fi
|
||||
echo "[apk-sdk] feeds update -a"
|
||||
./scripts/feeds update -a
|
||||
if ! ./scripts/feeds update -a; then
|
||||
[ -L feeds ] || { echo "[apk-sdk] ERROR: feeds update failed"; exit 8; }
|
||||
echo "[apk-sdk] WARNING: feeds update failed on cached checkouts — wiping cache, cloning fresh"
|
||||
find "$FEEDS_CACHE" -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true
|
||||
./scripts/feeds update -a
|
||||
fi
|
||||
echo "[apk-sdk] feeds install (prefer shater feed)"
|
||||
./scripts/feeds install -p shater shaterd shater-core byedpi luci-app-shater
|
||||
|
||||
# --- strip the SDK's generated per-package `default m` blocks ----------------
|
||||
# Run 60 settled the question that runs 58 and 59 left open. Writing an explicit
|
||||
# `# CONFIG_PACKAGE_kmod-x is not set` for all 1126 of them and re-running
|
||||
# defconfig deselected exactly nothing: the count came back 1078, unchanged.
|
||||
# Meanwhile the very same explicit form DID stick for CONFIG_ALL/ALL_KMODS/
|
||||
# ALL_NONSHARED. The difference is prompts. kconfig only honours a user value for
|
||||
# a symbol that has one (sym_calc_value ignores S_DEF_USER for a promptless
|
||||
# symbol and falls back to its `default`), and the ALL* symbols carry prompts in
|
||||
# the SDK's own Config.in while these generated blocks are bare:
|
||||
#
|
||||
# config PACKAGE_kmod-mlx5-core
|
||||
# tristate
|
||||
# default m
|
||||
#
|
||||
# So no value we write into .config can ever turn them off — the fix has to
|
||||
# remove the `default m` itself. That is what this does: drop every generated
|
||||
# `config PACKAGE_*` block from the SDK's Config-build.in before the first
|
||||
# defconfig. Nothing is lost by it — these blocks only replay which packages the
|
||||
# BUILDBOT happened to build; the packages themselves are still declared, with
|
||||
# prompts, by the package tree (tmp/.config-package.in), which is what makes our
|
||||
# four selectable and what `select` acts on. KERNEL_*/LIBC/TOOLCHAIN blocks are
|
||||
# left untouched, so the SDK still reproduces its own toolchain settings.
|
||||
CB=$(find . -maxdepth 2 -name 'Config-build.in' -print -quit 2>/dev/null || true)
|
||||
if [ -n "$CB" ] && command -v perl >/dev/null 2>&1; then
|
||||
pkg_before=$(grep -c '^config PACKAGE_' "$CB" || true)
|
||||
# Paragraph-wise delete: a block is `config PACKAGE_x`, its indented body, and
|
||||
# the blank line that ends it. Anchored per-line (/m) so nothing else matches.
|
||||
perl -0777 -pi -e 's/^config PACKAGE_\S+\n(?:[ \t]+\S[^\n]*\n)+\n//gm' "$CB"
|
||||
pkg_after=$(grep -c '^config PACKAGE_' "$CB" || true)
|
||||
echo "[apk-sdk] $CB: stripped $((pkg_before - pkg_after)) generated PACKAGE default blocks ($pkg_before -> $pkg_after)"
|
||||
else
|
||||
echo "[apk-sdk] WARNING: no Config-build.in found (or no perl) — per-package"
|
||||
echo "[apk-sdk] 'default m' blocks stay; the kmod tripwire will catch it"
|
||||
fi
|
||||
|
||||
# --- .config: turn OFF the SDK's mass-select defaults ------------------------
|
||||
# Symptom (v0.2.2, and still v0.2.3 run 58): the SDK ran `apk mkpkg` on ~1100
|
||||
# kmod-* packages — mlx5, amdgpu, ata, isdn, none of which we ship — and died
|
||||
# with `Disk quota exceeded` on the runner's 64 GB ZFS quota. Our kmod deps pull
|
||||
# in `package/kernel/linux/compile`, which packs every module marked =m.
|
||||
#
|
||||
# Why they are =m has nothing to do with anything we write here. An OpenWrt SDK
|
||||
# carries its OWN top-level Config.in (target/sdk/files/Config.in), and it reads:
|
||||
#
|
||||
# config ALL_NONSHARED
|
||||
# bool "Select all target specific packages by default"
|
||||
# default ALL
|
||||
# config ALL_KMODS
|
||||
# bool "Select all kernel module packages by default"
|
||||
# default ALL
|
||||
# config ALL
|
||||
# bool "Select all userspace packages by default"
|
||||
# default y <-- y, not n, and ONLY inside the SDK
|
||||
#
|
||||
# In the main tree those three default to n; the SDK flips ALL to y so that
|
||||
# `make world` in a bare SDK builds something useful. So `make defconfig` on ANY
|
||||
# .config — empty or not — selects the entire kernel. This is stock OpenWrt, not
|
||||
# an ImmortalWrt quirk: openwrt/openwrt's target/sdk/files/Config.in is identical.
|
||||
# (It also means the reference we copied, Slava-Shchipunov/awg-openwrt, builds
|
||||
# every kmod too — it just never hits a disk quota on GitHub's runners.)
|
||||
#
|
||||
# Fix: state all three explicitly. They carry prompts in the SDK's Config.in, so
|
||||
# they are user-settable and an explicit value beats the `default`. Note the FORM:
|
||||
# kconfig writes a false bool as `# CONFIG_X is not set` and `CONFIG_X=n` is not
|
||||
# reliably honoured, so `is not set` is the only form used here. All three are set
|
||||
# rather than just the root `ALL`, so this keeps working whichever symbol a future
|
||||
# SDK makes the root of the chain.
|
||||
# Stash anything the SDK shipped (see below — today there is nothing) and start
|
||||
# from a known-empty file, so what we build here is exactly what we intended.
|
||||
if [ -s .config ]; then mv -f .config .config.sdk; fi
|
||||
: > .config
|
||||
for s in ALL ALL_KMODS ALL_NONSHARED; do
|
||||
echo "# CONFIG_$s is not set" >> .config
|
||||
done
|
||||
|
||||
# About that stash: an SDK tarball ships NO top-level .config (run 58 logged
|
||||
# `grep: .config: No such file or directory` — the only `.config` inside the
|
||||
# tarball is the prebuilt KERNEL's, under the linux dir). This is also why the
|
||||
# first version of this fix was aimed at the wrong thing: there was never a
|
||||
# buildbot .config here to append to. Nothing needs carrying over from it either,
|
||||
# because
|
||||
# target/sdk/Makefile bakes the buildbot's non-package settings — every
|
||||
# CONFIG_KERNEL_* included — into the SDK's generated Config-build.in as kconfig
|
||||
# `default`s (target/sdk/convert-config.pl). defconfig therefore reproduces the
|
||||
# exact toolchain/kernel settings the SDK was built with, on its own; an earlier
|
||||
# attempt to copy those lines by hand was redundant and is gone.
|
||||
# Should a future SDK start shipping a .config, this keeps the two things that
|
||||
# would then be worth honouring — the target identity and the package format —
|
||||
# and still lets the lines above override the mass-select.
|
||||
if [ -s .config.sdk ]; then
|
||||
echo "[apk-sdk] SDK shipped a .config — carrying over target identity + format:"
|
||||
grep -E '^CONFIG_TARGET_[a-z0-9_]+=y$|^CONFIG_TARGET_(BOARD|SUBTARGET|ARCH_PACKAGES)=|^CONFIG_USE_APK=' \
|
||||
.config.sdk | tee -a .config | sed 's/^/[apk-sdk] /' || true
|
||||
fi
|
||||
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
echo "CONFIG_PACKAGE_$p=m" >> .config
|
||||
done
|
||||
@@ -135,11 +250,135 @@ fi
|
||||
echo "[apk-sdk] defconfig"
|
||||
make defconfig >/dev/null
|
||||
|
||||
# --- second pass: deselect the kernel, keep only what our packages select -----
|
||||
# Turning ALL/ALL_KMODS/ALL_NONSHARED off (above) provably worked — run 59 shows
|
||||
# all three as `is not set` after defconfig — and changed the kmod count by
|
||||
# exactly zero, 1078 both times. The kmods are not selected through ALL_KMODS at
|
||||
# all. They are selected one by one, and here is where from:
|
||||
#
|
||||
# target/sdk/Makefile:
|
||||
# ./convert-config.pl $(TOPDIR)/.config > $(SDK_BUILD_DIR)/Config-build.in
|
||||
#
|
||||
# The SDK's Config-build.in is GENERATED from the buildbot's .config — a config
|
||||
# in which ALL_KMODS=y had already expanded into a `CONFIG_PACKAGE_kmod-*=m` line
|
||||
# per module. convert-config.pl turns every `CONFIG_X=<val>` line into a kconfig
|
||||
# symbol carrying an unconditional `default <val>`; its `next if
|
||||
# /^(# )?CONFIG_PACKAGE/` filter sits in the `else` branch, which a line with an
|
||||
# `=` in it never reaches. So the SDK ships, verbatim, 1078 blocks of:
|
||||
#
|
||||
# config PACKAGE_kmod-mlx5-core
|
||||
# tristate
|
||||
# default m
|
||||
#
|
||||
# Nothing there consults ALL_KMODS, which is why switching it off was inert.
|
||||
#
|
||||
# Fix: give those symbols an explicit user value. We cannot do it before the
|
||||
# first defconfig — the list of names only exists once kconfig has expanded the
|
||||
# tree — so this is a second pass: rewrite every selected kmod to `is not set`
|
||||
# and re-run defconfig. Two kconfig rules make the result exactly what we want,
|
||||
# and both are already demonstrated in our own logs:
|
||||
# * an explicit value in .config beats a `default` (this is precisely why the
|
||||
# `# CONFIG_ALL* is not set` lines survived defconfig in run 59), so the
|
||||
# ~1078 kmods we do not need stay off;
|
||||
# * `select` is a reverse dependency, OR-ed into the symbol's value AFTER the
|
||||
# user value in sym_calc_value(), so it cannot be overridden by an explicit
|
||||
# `n`. shater-core's `DEPENDS:=+kmod-nft-tproxy +kmod-nft-socket` becomes
|
||||
# `select PACKAGE_kmod-nft-tproxy` (scripts/package-metadata.pl: a `+` flag
|
||||
# sets `$m = "select"`, and it re-emits the dependency's own depends too, so
|
||||
# transitive kmods follow). Those come back on their own.
|
||||
# Net effect: we build the handful of kmods our packages actually pull in.
|
||||
#
|
||||
# Rejected alternatives:
|
||||
# * limiting what `package/kernel/linux/compile` packs — that target has no
|
||||
# such knob; it iterates the selected set, so the selection IS the knob;
|
||||
# * `package/kernel/linux/clean` + a targeted build — the kernel package would
|
||||
# simply be rebuilt in full as a dependency of shater-core, same cost;
|
||||
# * copying OpenWrt's own feed CI (openwrt/gh-action-sdk) — it does nothing
|
||||
# about this; it just runs `make defconfig` and builds. Its one disk-related
|
||||
# setting, CONFIG_AUTOREMOVE=y, is already the SDK's default;
|
||||
# * editing the SDK's generated Config-build.in to strip the offending blocks —
|
||||
# it would work, but it means parsing a generated kconfig file by hand and a
|
||||
# format change would corrupt it silently. The two-pass approach uses only
|
||||
# kconfig's documented semantics and leaves the evidence in .config.
|
||||
kmods_all=$(grep -c '^CONFIG_PACKAGE_kmod-[^=]*=[my]$' .config || true)
|
||||
if [ "$kmods_all" -gt 0 ]; then
|
||||
echo "[apk-sdk] deselecting $kmods_all kmod packages, then defconfig again"
|
||||
sed -i -E 's/^CONFIG_(PACKAGE_kmod-[^=]*)=[my]$/# CONFIG_\1 is not set/' .config
|
||||
make defconfig >/dev/null
|
||||
fi
|
||||
|
||||
# --- post-defconfig sanity + disk-cost readout -------------------------------
|
||||
# A failed run leaves a ~27 MB log; digging the cause out of it is miserable, so
|
||||
# print the handful of numbers that decide whether this run survives the
|
||||
# runner's disk quota BEFORE anything is compiled.
|
||||
kmods=$(grep -c '^CONFIG_PACKAGE_kmod.*=m' .config || true)
|
||||
echo "[apk-sdk] target: board=$(sed -n 's/^CONFIG_TARGET_BOARD=//p' .config)" \
|
||||
"subtarget=$(sed -n 's/^CONFIG_TARGET_SUBTARGET=//p' .config)" \
|
||||
"arch_packages=$(sed -n 's/^CONFIG_TARGET_ARCH_PACKAGES=//p' .config)"
|
||||
echo "[apk-sdk] kmod packages selected (=m): $kmods"
|
||||
# Proof the mass-select stayed off: these three must come back out of defconfig
|
||||
# as `is not set`. If any reads `=y`, the SDK's `default ALL`/`default y` won and
|
||||
# the kmod count above will be in the four digits.
|
||||
echo "[apk-sdk] mass-select symbols after defconfig:"
|
||||
grep -E '^(# )?CONFIG_ALL(_KMODS|_NONSHARED)?[ =]' .config | sed 's/^/[apk-sdk] /' || true
|
||||
# After the second pass the only kmods left are the ones shater-core's
|
||||
# `DEPENDS:=+kmod-nft-tproxy +kmod-nft-socket` turns into kconfig `select`s, plus
|
||||
# whatever those select in turn — a handful. Worth printing verbatim while the
|
||||
# list is short. A count of 0 is NOT fatal: those kmods ship in the router's own
|
||||
# base feed, so apk resolves them there; but it would mean the selects did not
|
||||
# fire, and that is something we want to see in the log rather than guess at.
|
||||
if [ "$kmods" -le 30 ]; then
|
||||
grep '^CONFIG_PACKAGE_kmod.*=m' .config | sed 's/^/[apk-sdk] /' || true
|
||||
fi
|
||||
# The two cache knobs are written before the first defconfig and have to survive
|
||||
# both of them — losing DOWNLOAD_FOLDER silently costs us the dl/ cache, and
|
||||
# losing LOCALMIRROR brings back the sourceware.org stalls. Cheap to just look.
|
||||
echo "[apk-sdk] cache settings after defconfig:"
|
||||
grep -E '^CONFIG_(LOCALMIRROR|DOWNLOAD_FOLDER)=' .config | sed 's/^/[apk-sdk] /' || true
|
||||
echo "[apk-sdk] our packages after defconfig:"
|
||||
grep -E '^CONFIG_PACKAGE_(shaterd|shater-core|byedpi|luci-app-shater)=' .config \
|
||||
| sed 's/^/[apk-sdk] /' || true
|
||||
|
||||
# Each of our 4 must have SURVIVED defconfig. If kconfig dropped one, it is
|
||||
# because a symbol it `select`s (a DEPENDS entry) does not exist in the installed
|
||||
# feeds — with the old append-everything .config that was masked by the SDK
|
||||
# pre-selecting half the distro. `make package/<p>/compile` would then die with a
|
||||
# cryptic "No rule to make target", far from the real cause.
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
grep -q "^CONFIG_PACKAGE_$p=m" .config || {
|
||||
echo "[apk-sdk] ERROR: $p is NOT selected after defconfig."
|
||||
echo " kconfig dropped it -> one of its DEPENDS is missing from the"
|
||||
echo " installed feeds (check the 'feeds install' step above)."; exit 10; }
|
||||
done
|
||||
|
||||
# Only our two nft kmods (+ whatever they themselves depend on) have any business
|
||||
# being selected here — a dozen at the very most. A count in the hundreds means an
|
||||
# ALL_KMODS-style mass-select crept back in, and the run would spend ~40 min
|
||||
# packing the kernel before dying on `Disk quota exceeded`. Fail now instead.
|
||||
[ "$kmods" -le 200 ] || {
|
||||
echo "[apk-sdk] ERROR: $kmods kmod packages selected — that is the whole kernel."
|
||||
echo " Aborting before this fills the runner's disk. Two causes are"
|
||||
echo " possible, and the lines below tell them apart:"
|
||||
echo " (a) the mass-select is back on -> a CONFIG_ALL* line reads =y;"
|
||||
echo " (b) the second pass did not take -> ALL* are 'is not set' but the"
|
||||
echo " kmods returned anyway, i.e. the per-kmod 'default m' from the"
|
||||
echo " SDK's generated Config-build.in outlived our explicit 'n'."
|
||||
grep -E '^(# )?CONFIG_ALL(_KMODS|_NONSHARED)?[ =]' .config | sed 's/^/ /' || true
|
||||
echo " first few kmods still selected:"
|
||||
grep -m5 '^CONFIG_PACKAGE_kmod.*=m' .config | sed 's/^/ /' || true
|
||||
exit 11; }
|
||||
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
echo "[apk-sdk] === build $p ==="
|
||||
make "package/$p/compile" V=s -j"$(nproc)"
|
||||
done
|
||||
|
||||
# What the build actually cost on disk. The runner's 64 GB ZFS quota is the
|
||||
# binding constraint on this lane, so record it while the tree still exists.
|
||||
echo "[apk-sdk] disk usage after compile:"
|
||||
du -sh build_dir staging_dir bin 2>/dev/null || true
|
||||
df -h /home/build || true
|
||||
|
||||
# A 25.12 apk-SDK must emit .apk — finding only .ipk means a wrong SDK was fed in.
|
||||
anyapk=$(find bin -type f -name '*.apk' | wc -l)
|
||||
[ "$anyapk" -gt 0 ] || {
|
||||
@@ -157,6 +396,25 @@ done
|
||||
[ "$found" -ge 4 ] || { echo "[apk-sdk] ERROR: expected >=4 of OUR .apk, collected $found"; echo "[apk-sdk] (all .apk under bin/:)"; find bin -type f -name '*.apk' | head -20; exit 6; }
|
||||
echo "[apk-sdk] collected $found of our .apk"
|
||||
|
||||
# --- assert the tag-derived version actually reached the packages -------------
|
||||
# B4's failure mode is a wrong-but-plausible version shipping silently, so the
|
||||
# env -> make hand-off is verified, not trusted: each of our three tag-versioned
|
||||
# packages must be named `<name>-<ver>-r<rel>.apk`. byedpi is excluded on purpose
|
||||
# (it carries upstream ByeDPI's own version). This runs BEFORE `apk mkndx`, so a
|
||||
# stale version can never even reach the index.
|
||||
if [ -n "${SHATER_PKG_VERSION:-}" ] && [ -n "${SHATER_PKG_RELEASE:-}" ]; then
|
||||
want="${SHATER_PKG_VERSION}-r${SHATER_PKG_RELEASE}"
|
||||
for p in shaterd shater-core luci-app-shater; do
|
||||
[ -f "$OUT/${p}-${want}.apk" ] || {
|
||||
echo "[apk-sdk] ERROR: $p was not built as version '$want'."
|
||||
echo " SHATER_PKG_VERSION/SHATER_PKG_RELEASE did not reach the package"
|
||||
echo " Makefile — the build would have shipped a stale version (bug B4)."
|
||||
echo "[apk-sdk] collected:"; ls -1 "$OUT" | sed 's/^/ /'
|
||||
exit 12; }
|
||||
done
|
||||
echo "[apk-sdk] version check OK — our 3 packages are $want"
|
||||
fi
|
||||
|
||||
# --- index + sign: exactly how the OpenWrt 25.12 buildsystem does it ---------
|
||||
# apk mkndx --root T --keys-dir T [--sign key] --allow-untrusted \
|
||||
# --output packages.adb *.apk
|
||||
@@ -188,7 +446,7 @@ INNER
|
||||
chmod 0644 /home/build/inner.sh
|
||||
|
||||
su build -s /bin/bash -c \
|
||||
"ARCH='$ARCH' REPO='$REPO' OUT='$OUT' SDKDIR='$SDKDIR' KEYFILE='${KEYFILE:-}' DL_DIR='${DL_DIR:-}' bash /home/build/inner.sh"
|
||||
"ARCH='$ARCH' REPO='$REPO' OUT='$OUT' SDKDIR='$SDKDIR' KEYFILE='${KEYFILE:-}' DL_DIR='${DL_DIR:-}' FEEDS_CACHE='${FEEDS_CACHE:-}' SHATER_PKG_VERSION='${SHATER_PKG_VERSION:-}' SHATER_PKG_RELEASE='${SHATER_PKG_RELEASE:-}' bash /home/build/inner.sh"
|
||||
|
||||
chmod -R a+rwX "$OUT" 2>/dev/null || true
|
||||
echo "[apk-sdk] OK arch=$ARCH — apk feed dir:"
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Runs INSIDE an `openwrt/sdk:<target>-<ver>` container (CWD = SDK root
|
||||
# /builder). The job's workspace is shared into this container via
|
||||
# `docker run --volumes-from`, so the repo is visible at $REPO and output goes
|
||||
# to $OUT (a dir under the repo, hence also visible to the runner afterwards).
|
||||
#
|
||||
# Unlike Shater v0.1 (which compiled ONLY xrayctl in the SDK and hand-packed the
|
||||
# pure-data packages with tar), v0.2 builds ALL FOUR packages the canonical way,
|
||||
# via the SDK feed + `make package/<p>/compile`:
|
||||
#
|
||||
# shaterd prebuilt binary — Build/Compile only VALIDATES that
|
||||
# openwrt/shaterd/files/shaterd-<amd64|arm64>.upx was staged
|
||||
# by scripts/build-shaterd.sh on the runner BEFORE this ran.
|
||||
# (arch-specific .ipk: RSTRIP/STRIP disabled — packed ELF.)
|
||||
# shater-core PKGARCH=all data glue (procd init, sysctl, uci-defaults).
|
||||
# luci-app-shater PKGARCH=all LuCI thin launcher — its Makefile does
|
||||
# `include $(TOPDIR)/feeds/luci/luci.mk`, so the `luci` feed
|
||||
# MUST be updated first (that is what creates feeds/luci/luci.mk).
|
||||
# byedpi arch-specific C — the SDK cross-compiles ciadpi from the
|
||||
# upstream tarball (needs network for PKG_SOURCE_URL).
|
||||
#
|
||||
# Env (required): ARCH, REPO, OUT.
|
||||
set -eu
|
||||
ARCH="${ARCH:?ARCH env required}"
|
||||
REPO="${REPO:?REPO env required}"
|
||||
OUT="${OUT:?OUT env required}"
|
||||
mkdir -p "$OUT"
|
||||
|
||||
echo "[sdk] arch=$ARCH repo=$REPO out=$OUT"
|
||||
test -f "$REPO/openwrt/shaterd/Makefile" || {
|
||||
echo "[sdk] ERROR: feed not mounted ($REPO/openwrt/shaterd/Makefile missing)"; ls -la "$REPO" || true; exit 9; }
|
||||
|
||||
# The prebuilt shaterd artifact must already be staged for this arch.
|
||||
case "$ARCH" in
|
||||
x86_64) sfx=amd64 ;;
|
||||
aarch64_cortex-a53) sfx=arm64 ;;
|
||||
*) echo "[sdk] ERROR: unsupported ARCH '$ARCH'"; exit 2 ;;
|
||||
esac
|
||||
test -f "$REPO/openwrt/shaterd/files/shaterd-$sfx.upx" || {
|
||||
echo "[sdk] ERROR: openwrt/shaterd/files/shaterd-$sfx.upx not staged."
|
||||
echo " scripts/build-shaterd.sh must run on the runner before the SDK build."; exit 3; }
|
||||
|
||||
# --- register this repo's openwrt/ as a src-link feed named `shater` ---------
|
||||
# src-link REQUIRES an absolute path; $REPO/openwrt is exactly a feed root (it
|
||||
# contains the 4 package dirs and nothing else that looks like a package).
|
||||
cp -f feeds.conf.default feeds.conf
|
||||
grep -q '^src-link shater ' feeds.conf || echo "src-link shater $REPO/openwrt" >> feeds.conf
|
||||
|
||||
# Update metadata for ALL feeds: our `shater` feed + the SDK defaults (base,
|
||||
# luci, packages, routing, telephony). We need `luci` for feeds/luci/luci.mk and
|
||||
# `base`/`packages` for the runtime deps (kmod-nft-tproxy, kmod-nft-socket,
|
||||
# ip-full, rpcd, luci-base) to resolve.
|
||||
echo "[sdk] feeds update -a"
|
||||
./scripts/feeds update -a
|
||||
|
||||
echo "[sdk] feeds install (prefer shater feed)"
|
||||
./scripts/feeds install -p shater shaterd shater-core byedpi luci-app-shater
|
||||
|
||||
# Select our packages, then defconfig. `make package/<p>/compile` builds the
|
||||
# explicit target regardless, but selecting first makes deps visible to defconfig.
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
echo "CONFIG_PACKAGE_$p=m" >> .config
|
||||
done
|
||||
# Route source downloads through OpenWrt's fast CDN mirror FIRST — sourceware.org
|
||||
# (elfutils) and other upstreams intermittently stall mid-transfer, and curl's
|
||||
# --connect-timeout doesn't cover a stalled stream, so the SDK download hangs the
|
||||
# build. LOCALMIRROR is tried before each package's own PKG_SOURCE_URL. (lx CI)
|
||||
echo 'CONFIG_LOCALMIRROR="https://sources.cdn.openwrt.org"' >> .config
|
||||
# Persistent dl/ across runs: $DL_DIR is a workspace dir the runner restores via
|
||||
# actions/cache (see ci/build-feed.sh). Correctness-safe: the buildroot verifies
|
||||
# PKG_HASH on every file already in dl/ and re-downloads on mismatch, so a stale
|
||||
# cache can never leak a wrong source into the build.
|
||||
if [ -n "${DL_DIR:-}" ]; then
|
||||
echo "CONFIG_DOWNLOAD_FOLDER=\"$DL_DIR\"" >> .config
|
||||
fi
|
||||
echo "[sdk] defconfig"
|
||||
make defconfig >/dev/null
|
||||
|
||||
# --- compile the 4 packages --------------------------------------------------
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
echo "[sdk] === build $p ==="
|
||||
make "package/$p/compile" V=s -j"$(nproc)"
|
||||
done
|
||||
|
||||
# --- collect ONLY our 4 packages' .ipk (per-arch shaterd/byedpi + _all core/luci)
|
||||
# NOT `find bin -name '*.ipk'`: the openwrt/sdk image ships HUNDREDS of prebuilt
|
||||
# kmod/base .ipk under bin/, which a blanket copy would pull into the feed and
|
||||
# get signed under OUR key. Match each package's own `<name>_<ver>_<arch>.ipk`.
|
||||
found=0
|
||||
for p in shaterd shater-core byedpi luci-app-shater; do
|
||||
for ipk in $(find bin -type f -name "${p}_*.ipk"); do
|
||||
cp -f "$ipk" "$OUT/"; found=$((found+1))
|
||||
done
|
||||
done
|
||||
[ "$found" -ge 4 ] || { echo "[sdk] ERROR: expected >=4 of OUR .ipk, collected $found"; echo "[sdk] (all .ipk under bin/:)"; find bin -type f -name '*.ipk' | head -20; exit 4; }
|
||||
chmod -R a+rwX "$OUT" 2>/dev/null || true
|
||||
echo "[sdk] OK arch=$ARCH — collected $found of our .ipk:"
|
||||
ls -l "$OUT"
|
||||
Executable
+131
@@ -0,0 +1,131 @@
|
||||
#!/bin/sh
|
||||
# ci/version.sh — the SINGLE source of truth for "what version is this build?".
|
||||
#
|
||||
# WHY THIS EXISTS (bug B4)
|
||||
# -----------------------
|
||||
# PKG_VERSION/PKG_RELEASE used to be hand-written literals in the four package
|
||||
# Makefiles, and nobody remembered to bump them: v0.2.2 … v0.2.6 all shipped as
|
||||
# `shaterd 0.2.0-r3` with DIFFERENT binaries inside (v0.2.6's ELF is 5 491 616 B
|
||||
# vs r2's 5 488 336 B). Since apk offers an upgrade only when the feed's version
|
||||
# string differs from the installed one, `apk update` saw nothing new and the
|
||||
# routers could not be updated through the normal path at all.
|
||||
#
|
||||
# So the version is now DERIVED, in CI, from the git tag, and the package
|
||||
# Makefiles only carry a fallback for manual/offline builds.
|
||||
#
|
||||
# THE SCHEME
|
||||
# ----------
|
||||
# tag push `vX.Y.Z` -> PKG_VERSION=X.Y.Z PKG_RELEASE=1
|
||||
# any other build -> PKG_VERSION=X.Y.Z of the NEAREST reachable tag,
|
||||
# (workflow_dispatch, PKG_RELEASE=<commits since that tag> + 1
|
||||
# rolling `latest`)
|
||||
# no tag / no git at all -> PKG_VERSION=0.0.0 PKG_RELEASE=1 (+ warning)
|
||||
#
|
||||
# apk compares `<upstream>-r<rel>` as: the dotted upstream part first
|
||||
# (numerically, component by component), the `r<rel>` only as a tie-break.
|
||||
# Verified against the real tool, not from memory —
|
||||
# apk-tools 3.0.3 (`apk version -t`) and apk-tools 2.14.6:
|
||||
# 0.2.6-r1 > 0.2.0-r3 0.2.6-r12 > 0.2.6-r1
|
||||
# 0.2.7-r1 > 0.2.6-r12 0.0.0-r1 < 0.2.0-r3
|
||||
# That is exactly the ordering this scheme needs:
|
||||
# * a release always outranks every rolling build that preceded it
|
||||
# (0.2.7-r1 > 0.2.6-rN for any N — the dotted part decides), and
|
||||
# * rolling builds between two releases grow monotonically (r2 < r10 < r11),
|
||||
# so a rolling build can never look newer than the next release, and the
|
||||
# `latest` feed still moves forward on every dispatch.
|
||||
#
|
||||
# +1 on the commit count (rather than the raw count) only avoids `-r0` and makes
|
||||
# a dispatch build of the tagged commit itself identical to the release build of
|
||||
# that same commit — which is the truth: same tree, same binary.
|
||||
#
|
||||
# `byedpi` is deliberately NOT versioned from our tag — see openwrt/byedpi/Makefile.
|
||||
#
|
||||
# USAGE
|
||||
# ci/version.sh # or --env: eval-able / $GITHUB_ENV-able lines
|
||||
# ci/version.sh --pkg-version # X.Y.Z
|
||||
# ci/version.sh --pkg-release # R
|
||||
# ci/version.sh --binary # vX.Y.Z-rR[-g<sha>] for constant.Version
|
||||
#
|
||||
# Env:
|
||||
# SHATER_REF / GITHUB_REF when it is `refs/tags/<tag>` that tag wins and no
|
||||
# git history is needed (the tag-push path is exact
|
||||
# even on a shallow checkout).
|
||||
set -eu
|
||||
|
||||
REPO="$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
|
||||
TAG=""
|
||||
EXACT=0
|
||||
N=0
|
||||
SHA=""
|
||||
|
||||
# --- 1) an explicit tag ref is authoritative (and needs no git) --------------
|
||||
REF="${SHATER_REF:-${GITHUB_REF:-}}"
|
||||
case "$REF" in
|
||||
refs/tags/*) TAG="${REF#refs/tags/}"; EXACT=1 ;;
|
||||
esac
|
||||
|
||||
# --- 2) otherwise ask git for the nearest reachable release tag --------------
|
||||
# `--match 'v[0-9]*'` keeps non-release tags (latest, sdk-cache, apk-latest-*,
|
||||
# musl-toolchain-cache) out. This repo is a sing-box FORK and therefore also
|
||||
# carries upstream's v1.x tags — `git describe` picks the CLOSEST tag by commit
|
||||
# distance, so our own v0.2.x (a handful of commits back) always wins over
|
||||
# upstream's v1.x (thousands of commits back). The tag it picked is logged
|
||||
# below, so a surprise is visible in the CI log rather than silently shipped.
|
||||
if [ "$EXACT" -eq 0 ]; then
|
||||
if D="$(git -C "$REPO" describe --tags --long --match 'v[0-9]*' 2>/dev/null)"; then
|
||||
# `v0.2.6-1-g02c266188` -> TAG=v0.2.6 N=1 SHA=g02c266188.
|
||||
# `%` strips the SHORTEST matching suffix, so a tag that itself contains a
|
||||
# dash (`v0.2.0-healthplan`) survives intact.
|
||||
TAG="${D%-*-g*}"
|
||||
REST="${D#"$TAG"-}"
|
||||
N="${REST%%-*}"
|
||||
SHA="${REST#*-}"
|
||||
if [ "$N" -eq 0 ]; then EXACT=1; fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- 3) tag -> numeric PKG_VERSION ------------------------------------------
|
||||
# Keep the leading dotted-numeric run only: `v0.2.0-healthplan` -> `0.2.0`.
|
||||
VER=""
|
||||
if [ -n "$TAG" ]; then
|
||||
VER="$(printf '%s' "${TAG#v}" | sed -n 's/^\([0-9][0-9.]*\).*/\1/p' | sed 's/\.*$//')"
|
||||
fi
|
||||
|
||||
if [ -z "$VER" ]; then
|
||||
# No release tag anywhere (shallow clone with no tags, a tarball export, a
|
||||
# fresh fork). 0.0.0 is BELOW every version we have ever published, so such a
|
||||
# build can never masquerade as an upgrade on a real router; the commit count
|
||||
# still makes successive dev builds distinguishable.
|
||||
VER="0.0.0"
|
||||
EXACT=0
|
||||
N="$(git -C "$REPO" rev-list --count HEAD 2>/dev/null || echo 0)"
|
||||
SHA="$(git -C "$REPO" rev-parse --short HEAD 2>/dev/null || echo '')"
|
||||
[ -z "$SHA" ] || SHA="g$SHA"
|
||||
echo "[version] WARNING: no reachable vX.Y.Z tag (and/or no git) -> $VER" >&2
|
||||
fi
|
||||
|
||||
# --- 4) PKG_RELEASE + the string stamped into the binary --------------------
|
||||
if [ "$EXACT" -eq 1 ]; then
|
||||
REL=1
|
||||
FULL="v${VER}-r${REL}"
|
||||
else
|
||||
REL=$((N + 1))
|
||||
FULL="v${VER}-r${REL}${SHA:+-$SHA}"
|
||||
fi
|
||||
|
||||
echo "[version] tag='${TAG:-none}' commits_since=$N exact=$EXACT -> ${VER}-r${REL} (binary: $FULL)" >&2
|
||||
|
||||
case "${1:---env}" in
|
||||
--env|"")
|
||||
printf 'SHATER_PKG_VERSION=%s\n' "$VER"
|
||||
printf 'SHATER_PKG_RELEASE=%s\n' "$REL"
|
||||
printf 'SHATER_VERSION=%s\n' "$FULL"
|
||||
;;
|
||||
--pkg-version) printf '%s\n' "$VER" ;;
|
||||
--pkg-release) printf '%s\n' "$REL" ;;
|
||||
--binary|--version) printf '%s\n' "$FULL" ;;
|
||||
*)
|
||||
echo "usage: $0 [--env|--pkg-version|--pkg-release|--binary]" >&2
|
||||
exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,35 @@
|
||||
//go:build darwin
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// udpSocketDFSet reports whether the socket has "don't fragment" forced on
|
||||
// (control.DisableUDPFragment sets IP_DONTFRAG=1 on darwin).
|
||||
func udpSocketDFSet(t *testing.T, sysConn syscall.Conn) bool {
|
||||
t.Helper()
|
||||
rawConn, err := sysConn.SyscallConn()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
value int
|
||||
sockErr error
|
||||
ctrlErr error
|
||||
)
|
||||
ctrlErr = rawConn.Control(func(fd uintptr) {
|
||||
value, sockErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_DONTFRAG)
|
||||
})
|
||||
if ctrlErr != nil {
|
||||
t.Fatal(ctrlErr)
|
||||
}
|
||||
if sockErr != nil {
|
||||
t.Fatal(sockErr)
|
||||
}
|
||||
return value != 0
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//go:build linux
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// udpSocketDFSet reports whether the socket has "don't fragment" forced on
|
||||
// (control.DisableUDPFragment sets IP_MTU_DISCOVER=IP_PMTUDISC_DO on linux,
|
||||
// the same flag the user-visible failure was traced to on android).
|
||||
func udpSocketDFSet(t *testing.T, sysConn syscall.Conn) bool {
|
||||
t.Helper()
|
||||
rawConn, err := sysConn.SyscallConn()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
value int
|
||||
sockErr error
|
||||
ctrlErr error
|
||||
)
|
||||
ctrlErr = rawConn.Control(func(fd uintptr) {
|
||||
value, sockErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_MTU_DISCOVER)
|
||||
})
|
||||
if ctrlErr != nil {
|
||||
t.Fatal(ctrlErr)
|
||||
}
|
||||
if sockErr != nil {
|
||||
t.Fatal(sockErr)
|
||||
}
|
||||
return value == unix.IP_PMTUDISC_DO
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !darwin && !linux && !windows
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func udpSocketDFSet(t *testing.T, _ syscall.Conn) bool {
|
||||
t.Helper()
|
||||
t.Skip("DF socket-flag introspection implemented for darwin, linux and windows only")
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//go:build windows
|
||||
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// IP_MTU_DISCOVER on windows (ws2ipdef.h); control.DisableUDPFragment sets it to
|
||||
// IP_PMTUDISC_DO, the same "don't fragment" state the linux helper checks.
|
||||
const (
|
||||
windowsIPMTUDiscover = 71
|
||||
windowsPMTUDiscDo = 1
|
||||
)
|
||||
|
||||
// udpSocketDFSet reports whether the socket has "don't fragment" forced on.
|
||||
// shater addition: upstream ships linux + darwin only, so the whole suite
|
||||
// skipped on the dev host — where it is the one platform we can actually run it
|
||||
// on before the router build.
|
||||
func udpSocketDFSet(t *testing.T, sysConn syscall.Conn) bool {
|
||||
t.Helper()
|
||||
rawConn, err := sysConn.SyscallConn()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var (
|
||||
value int
|
||||
sockErr error
|
||||
)
|
||||
ctrlErr := rawConn.Control(func(fd uintptr) {
|
||||
value, sockErr = windows.GetsockoptInt(windows.Handle(fd), windows.IPPROTO_IP, windowsIPMTUDiscover)
|
||||
})
|
||||
if ctrlErr != nil {
|
||||
t.Fatal(ctrlErr)
|
||||
}
|
||||
if sockErr != nil {
|
||||
t.Skip("IP_MTU_DISCOVER is not readable on this host: ", sockErr)
|
||||
}
|
||||
return value == windowsPMTUDiscDo
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// lx: regression tests for the udp_fragment / UDPFragmentDefault
|
||||
// plumbing. The WireGuard endpoint (and MASQUE outbound) rely on
|
||||
// UDPFragmentDefault=true reaching the real UDP socket as "DF clear": with DF
|
||||
// set, an outer datagram larger than the path MTU is silently dropped instead
|
||||
// of fragmented, which blackholes nested tunnels (AWG-over-AWG, MASQUE-over-AWG)
|
||||
// and AWG s4 transport junk. These tests assert the socket flag itself, on both
|
||||
// paths a WireGuard bind can take: the dialer (ClientBind, detour case) and the
|
||||
// listener control (StdNetBind via WireGuardControl, no-detour case).
|
||||
package dialer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
func dialUDPForDF(t *testing.T, options option.DialerOptions) syscall.Conn {
|
||||
t.Helper()
|
||||
d, err := NewDefault(context.Background(), options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn, err := d.DialContext(context.Background(), N.NetworkUDP, M.ParseSocksaddr("127.0.0.1:9"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
sysConn, isSysConn := conn.(syscall.Conn)
|
||||
if !isSysConn {
|
||||
t.Fatalf("dialed UDP conn %T does not expose SyscallConn", conn)
|
||||
}
|
||||
return sysConn
|
||||
}
|
||||
|
||||
func listenUDPForDF(t *testing.T, options option.DialerOptions) syscall.Conn {
|
||||
t.Helper()
|
||||
d, err := NewDefault(context.Background(), options)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// WireGuardControl() is the listener control conn.StdNetBind installs on the
|
||||
// socket a no-detour WireGuard endpoint sends its outer datagrams from — the
|
||||
// exact socket the DF default decides the fate of.
|
||||
listenConfig := net.ListenConfig{Control: d.WireGuardControl()}
|
||||
packetConn, err := listenConfig.ListenPacket(context.Background(), "udp4", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = packetConn.Close() })
|
||||
sysConn, isSysConn := packetConn.(syscall.Conn)
|
||||
if !isSysConn {
|
||||
t.Fatalf("listened UDP conn %T does not expose SyscallConn", packetConn)
|
||||
}
|
||||
return sysConn
|
||||
}
|
||||
|
||||
// Upstream default: no UDPFragmentDefault, no udp_fragment → DF is set on both
|
||||
// the dial and listener paths. Pins the baseline the endpoint fix opts out of.
|
||||
func TestUDPFragmentDFByDefault_LX(t *testing.T) {
|
||||
if !udpSocketDFSet(t, dialUDPForDF(t, option.DialerOptions{})) {
|
||||
t.Fatal("default dialer must set DF on dialed UDP sockets")
|
||||
}
|
||||
if !udpSocketDFSet(t, listenUDPForDF(t, option.DialerOptions{})) {
|
||||
t.Fatal("default dialer must set DF on listener-control UDP sockets")
|
||||
}
|
||||
}
|
||||
|
||||
// UDPFragmentDefault=true (what the WireGuard endpoint and MASQUE outbound now
|
||||
// set) → DF clear on both paths, so oversize outer datagrams fragment instead
|
||||
// of vanishing.
|
||||
func TestUDPFragmentDefaultClearsDF_LX(t *testing.T) {
|
||||
options := option.DialerOptions{UDPFragmentDefault: true}
|
||||
if udpSocketDFSet(t, dialUDPForDF(t, options)) {
|
||||
t.Fatal("UDPFragmentDefault=true must leave DF clear on dialed UDP sockets")
|
||||
}
|
||||
if udpSocketDFSet(t, listenUDPForDF(t, options)) {
|
||||
t.Fatal("UDPFragmentDefault=true must leave DF clear on listener-control UDP sockets")
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit user config always wins over the protocol default, in both
|
||||
// directions.
|
||||
func TestUDPFragmentExplicitOverride_LX(t *testing.T) {
|
||||
fragmentOff := false
|
||||
options := option.DialerOptions{UDPFragment: &fragmentOff, UDPFragmentDefault: true}
|
||||
if !udpSocketDFSet(t, dialUDPForDF(t, options)) {
|
||||
t.Fatal("udp_fragment=false must set DF even when the protocol default allows fragmentation")
|
||||
}
|
||||
fragmentOn := true
|
||||
options = option.DialerOptions{UDPFragment: &fragmentOn}
|
||||
if udpSocketDFSet(t, dialUDPForDF(t, options)) {
|
||||
t.Fatal("udp_fragment=true must leave DF clear even without a protocol default")
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,21 @@ func requireRoot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// requireTCPDump skips when tcpdump is not installed.
|
||||
//
|
||||
// The same honesty this package's callers demand of a health reading: a missing
|
||||
// INSTRUMENT is "not checked", never "broken". Without it every test in this
|
||||
// file fails on `cmd.Start()` — sixteen red results that say nothing about the
|
||||
// code and hide any real failure among them — on a machine where the only thing
|
||||
// wrong is that a capture tool is absent. requireRoot has always drawn that line
|
||||
// for privileges; this draws it for the tool.
|
||||
func requireTCPDump(t *testing.T) {
|
||||
t.Helper()
|
||||
if _, err := exec.LookPath("tcpdump"); err != nil {
|
||||
t.Skip("integration test requires tcpdump on PATH; install it to run this suite")
|
||||
}
|
||||
}
|
||||
|
||||
func tcpdumpObserver(t *testing.T, iface string, port uint16, needle string, do func(), wait time.Duration) bool {
|
||||
t.Helper()
|
||||
return tcpdumpObserverMulti(t, iface, port, []string{needle}, do, wait)[needle]
|
||||
@@ -36,6 +51,9 @@ func tcpdumpObserver(t *testing.T, iface string, port uint16, needle string, do
|
||||
// the wire.
|
||||
func tcpdumpObserverMulti(t *testing.T, iface string, port uint16, needles []string, do func(), wait time.Duration) map[string]bool {
|
||||
t.Helper()
|
||||
// Every capture in this file funnels through here, so one guard covers the
|
||||
// whole suite and no future test can forget it.
|
||||
requireTCPDump(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), wait)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "tcpdump", "-i", iface, "-n", "-A", "-l",
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// lx:begin health-board
|
||||
|
||||
package urltest
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
)
|
||||
|
||||
// captureEvictions swaps the eviction notice sink for the duration of a test and
|
||||
// returns a func that reads back everything reported.
|
||||
func captureEvictions(t *testing.T) func() []string {
|
||||
t.Helper()
|
||||
var (
|
||||
mu sync.Mutex
|
||||
msgs []string
|
||||
)
|
||||
orig := boardEvictionLog
|
||||
boardEvictionLog = func(m string) {
|
||||
mu.Lock()
|
||||
msgs = append(msgs, m)
|
||||
mu.Unlock()
|
||||
}
|
||||
t.Cleanup(func() { boardEvictionLog = orig })
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), msgs...)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBoardHoldsAGenerationWithoutEvicting is the "what it holds" half of the
|
||||
// bound. A live generation on this box is ~1200 tags (≈380 nodes plus their
|
||||
// per-group egress copies and chain hops); the board must carry that — and a
|
||||
// second generation's worth of overlap during a subscription rename — with no
|
||||
// eviction at all, or the ceiling would be silently degrading real health data.
|
||||
func TestBoardHoldsAGenerationWithoutEvicting(t *testing.T) {
|
||||
read := captureEvictions(t)
|
||||
s := NewHistoryStorage()
|
||||
|
||||
const generation = 1200
|
||||
for gen := 0; gen < 2; gen++ {
|
||||
for i := 0; i < generation; i++ {
|
||||
s.StoreURLTestHistory("gen"+strconv.Itoa(gen)+"-node-"+strconv.Itoa(i),
|
||||
&adapter.URLTestHistory{LastOK: time.Now(), Delay: 20})
|
||||
}
|
||||
}
|
||||
if got := s.Evicted(); got != 0 {
|
||||
t.Fatalf("two full generations (%d tags) evicted %d entries; the board must hold them",
|
||||
2*generation, got)
|
||||
}
|
||||
if msgs := read(); len(msgs) != 0 {
|
||||
t.Fatalf("unexpected eviction notices: %v", msgs)
|
||||
}
|
||||
// Everything is still readable.
|
||||
if s.LoadURLTestHistory("gen0-node-0") == nil {
|
||||
t.Fatalf("the first tag of the first generation was lost without an eviction")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBoardEvictsOldestAndSaysSo is the "what happens when it overflows" half.
|
||||
// Overflow must (a) actually bound the map, (b) drop the LEAST RECENTLY MEASURED
|
||||
// tags — on this box, exactly the ones no config names any more — and (c) be
|
||||
// audible: a silent eviction is a health board quietly forgetting nodes it is
|
||||
// still being asked about.
|
||||
func TestBoardEvictsOldestAndSaysSo(t *testing.T) {
|
||||
read := captureEvictions(t)
|
||||
s := NewHistoryStorage()
|
||||
|
||||
base := time.Now().Add(-24 * time.Hour)
|
||||
// Stale generation first: measured a day ago, nothing since.
|
||||
const stale = 1500
|
||||
for i := 0; i < stale; i++ {
|
||||
s.StoreURLTestHistory("stale-"+strconv.Itoa(i),
|
||||
&adapter.URLTestHistory{LastOK: base.Add(time.Duration(i) * time.Millisecond), Delay: 30})
|
||||
}
|
||||
if s.Evicted() != 0 {
|
||||
t.Fatalf("evicted before the ceiling was reached")
|
||||
}
|
||||
// Now push past the ceiling with fresh measurements.
|
||||
for i := 0; i <= maxBoardEntries; i++ {
|
||||
s.StoreURLTestHistory("fresh-"+strconv.Itoa(i),
|
||||
&adapter.URLTestHistory{LastOK: time.Now(), Delay: 15})
|
||||
}
|
||||
|
||||
if got := s.Evicted(); got == 0 {
|
||||
t.Fatalf("board grew past %d entries without evicting anything — it is still unbounded", maxBoardEntries)
|
||||
}
|
||||
s.access.RLock()
|
||||
size := len(s.delayHistory)
|
||||
s.access.RUnlock()
|
||||
if size > maxBoardEntries {
|
||||
t.Fatalf("board holds %d entries, above the %d ceiling", size, maxBoardEntries)
|
||||
}
|
||||
|
||||
// The day-old generation is what went, not the fresh one.
|
||||
if s.LoadURLTestHistory("stale-0") != nil {
|
||||
t.Fatalf("the oldest observation survived while newer ones were dropped")
|
||||
}
|
||||
if s.LoadURLTestHistory("fresh-"+strconv.Itoa(maxBoardEntries)) == nil {
|
||||
t.Fatalf("the newest measurement was evicted")
|
||||
}
|
||||
|
||||
msgs := read()
|
||||
if len(msgs) == 0 {
|
||||
t.Fatalf("entries were evicted with no notice — eviction must never be silent")
|
||||
}
|
||||
m := msgs[0]
|
||||
for _, want := range []string{"health board full", "evicted", "re-probed"} {
|
||||
if !strings.Contains(m, want) {
|
||||
t.Fatalf("eviction notice %q does not say %q", m, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBoardEvictionThroughMarkFailed pins the OTHER write path. MarkFailed is how
|
||||
// a dead node is recorded, and a flood of dead renamed nodes is exactly the shape
|
||||
// of the leak — so it has to prune too, not just the success path.
|
||||
func TestBoardEvictionThroughMarkFailed(t *testing.T) {
|
||||
captureEvictions(t)
|
||||
s := NewHistoryStorage()
|
||||
for i := 0; i <= maxBoardEntries; i++ {
|
||||
s.MarkFailed("dead-" + strconv.Itoa(i))
|
||||
}
|
||||
s.access.RLock()
|
||||
size := len(s.delayHistory)
|
||||
s.access.RUnlock()
|
||||
if size > maxBoardEntries {
|
||||
t.Fatalf("MarkFailed grew the board to %d, above the %d ceiling", size, maxBoardEntries)
|
||||
}
|
||||
if s.Evicted() == 0 {
|
||||
t.Fatalf("MarkFailed never prunes — the failure path is still unbounded")
|
||||
}
|
||||
}
|
||||
|
||||
// lx:end health-board
|
||||
@@ -0,0 +1,202 @@
|
||||
// lx:begin health-board
|
||||
|
||||
// Health board (plan §5.A): failure tracking and verdict computation on top of
|
||||
// HistoryStorage. Successes keep flowing through StoreURLTestHistory; failures are
|
||||
// recorded with MarkFailed instead of deleting the entry (deletion stays reserved
|
||||
// for nodes removed from the configuration), and consumers classify a tag at read
|
||||
// time with Verdict. One store, one truth: whoever learns about a death — the
|
||||
// group's own checker, the observatory, or a failed user dial — marks it here.
|
||||
|
||||
package urltest
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
)
|
||||
|
||||
// --- board capacity ---------------------------------------------------------
|
||||
//
|
||||
// The board is the one structure in the daemon whose key space is chosen by
|
||||
// somebody else. Its keys are outbound TAGS, and on this box a tag is a node
|
||||
// NAME straight out of the subscription — plus the derived per-group egress
|
||||
// copies ("group-<g>-m<i>-<node>") and per-chain hop copies the probe planner
|
||||
// creates for the same nodes. Providers rename their nodes freely, so a daily
|
||||
// subscription refresh introduces a whole new generation of keys, while the
|
||||
// store itself is pinned to the ENGINE's context (shater/engine.New) and so
|
||||
// outlives every generation and every Apply — by design, so health survives a
|
||||
// config change.
|
||||
//
|
||||
// Nothing ever removed a key. DeleteURLTestHistory exists but no shater path
|
||||
// calls it (only daemon/ and clashapi/, which this fork does not run), so the
|
||||
// map was strictly append-only for the life of the process — and the process is
|
||||
// expected to live for months.
|
||||
//
|
||||
// The arithmetic: ~380 nodes, and a config with a couple of egress-bound groups
|
||||
// plus a handful of chains puts a LIVE generation at roughly 380 base tags +
|
||||
// 2x380 group copies + ~100 chain copies ≈ 1200 keys. One new generation per day
|
||||
// is ~440k keys a year, at ~200 B per entry (map bucket + a tag string that is
|
||||
// routinely 30-50 B with flag emoji, + a 56 B URLTestHistory) ≈ 88 MB of a
|
||||
// 512 MB box — spent entirely on nodes that no longer exist.
|
||||
const (
|
||||
// maxBoardEntries is the hard ceiling. 4096 is ~3.4 live generations, so the
|
||||
// board comfortably holds the current config plus the overlap while a
|
||||
// subscription refresh swaps names, and still costs under a megabyte. A tighter
|
||||
// bound would start evicting tags the running config actually uses; a looser one
|
||||
// would stop being a bound in any useful sense.
|
||||
maxBoardEntries = 4096
|
||||
// keepBoardEntries is the prune target: drop a quarter at a time so the
|
||||
// O(n log n) selection is amortised over ~1024 inserts instead of running on
|
||||
// every probe once the board is full.
|
||||
keepBoardEntries = 3072
|
||||
)
|
||||
|
||||
// boardEvictionLog reports an eviction. A package var so tests can capture it;
|
||||
// production leaves it writing to the process log, which under procd is the same
|
||||
// syslog/logsink stream every other daemon line lands in.
|
||||
//
|
||||
// Eviction is NEVER silent. It is not free either: an evicted tag reverts to
|
||||
// "untested" and its next probe re-measures it, so a board that evicts entries
|
||||
// belonging to the LIVE config is a board whose ceiling is too low — and the only
|
||||
// way anyone finds that out is this line.
|
||||
var boardEvictionLog = func(msg string) { boardLogger().Warn(msg) }
|
||||
|
||||
// pruneLocked drops the least-recently-OBSERVED entries when the board exceeds
|
||||
// maxBoardEntries. "Least recently observed" is max(LastOK, LastFail): the entry
|
||||
// nothing has measured for the longest is, on this box, precisely a tag that no
|
||||
// longer exists in any config — a renamed node, a removed group copy, a retired
|
||||
// chain hop. Caller holds access.
|
||||
func (s *HistoryStorage) pruneLocked() {
|
||||
if len(s.delayHistory) <= maxBoardEntries {
|
||||
return
|
||||
}
|
||||
type kv struct {
|
||||
tag string
|
||||
seen time.Time
|
||||
}
|
||||
all := make([]kv, 0, len(s.delayHistory))
|
||||
for tag, h := range s.delayHistory {
|
||||
seen := h.LastOK
|
||||
if h.LastFail.After(seen) {
|
||||
seen = h.LastFail
|
||||
}
|
||||
all = append(all, kv{tag, seen})
|
||||
}
|
||||
sort.Slice(all, func(i, j int) bool { return all[i].seen.Before(all[j].seen) })
|
||||
drop := len(all) - keepBoardEntries
|
||||
var oldest time.Time
|
||||
for i := 0; i < drop; i++ {
|
||||
if i == 0 {
|
||||
oldest = all[i].seen
|
||||
}
|
||||
delete(s.delayHistory, all[i].tag)
|
||||
}
|
||||
s.evicted += uint64(drop)
|
||||
|
||||
msg := "urltest: health board full (" + strconv.Itoa(maxBoardEntries) + " tags) — evicted " +
|
||||
strconv.Itoa(drop) + " least-recently-measured entries (" + strconv.FormatUint(s.evicted, 10) +
|
||||
" total since start); they revert to untested and will be re-probed"
|
||||
if !oldest.IsZero() {
|
||||
msg += "; oldest observation was " + time.Since(oldest).Truncate(time.Second).String() + " ago"
|
||||
}
|
||||
boardEvictionLog(msg)
|
||||
}
|
||||
|
||||
// Evicted reports how many entries the capacity bound has dropped since the store
|
||||
// was created. Nonzero means the board reached maxBoardEntries at least once.
|
||||
func (s *HistoryStorage) Evicted() uint64 {
|
||||
if s == nil {
|
||||
return 0
|
||||
}
|
||||
s.access.RLock()
|
||||
defer s.access.RUnlock()
|
||||
return s.evicted
|
||||
}
|
||||
|
||||
// boardLogger is the process-wide fallback logger for eviction notices. The store
|
||||
// is built from a plain constructor with no logger in sight (box.New, the daemon,
|
||||
// shater/engine all call NewHistoryStorage()), so rather than change that
|
||||
// signature everywhere the notice goes to the standard logger — which on the
|
||||
// router is the daemon's own stderr, i.e. the same sink logsink owns.
|
||||
var (
|
||||
boardLogOnce sync.Once
|
||||
boardLog log.ContextLogger
|
||||
)
|
||||
|
||||
func boardLogger() log.ContextLogger {
|
||||
boardLogOnce.Do(func() { boardLog = log.StdLogger() })
|
||||
return boardLog
|
||||
}
|
||||
|
||||
// HealthVerdict classifies a stored history entry at read time.
|
||||
type HealthVerdict int
|
||||
|
||||
const (
|
||||
// VerdictUntested means nothing fresh enough is known either way: no entry,
|
||||
// or every observation is older than the caller's TTL.
|
||||
VerdictUntested HealthVerdict = iota
|
||||
// VerdictAlive means the newest fresh observation is a success.
|
||||
VerdictAlive
|
||||
// VerdictDead means the newest fresh observation is a failure.
|
||||
VerdictDead
|
||||
)
|
||||
|
||||
func (v HealthVerdict) String() string {
|
||||
switch v {
|
||||
case VerdictAlive:
|
||||
return "alive"
|
||||
case VerdictDead:
|
||||
return "dead"
|
||||
default:
|
||||
return "untested"
|
||||
}
|
||||
}
|
||||
|
||||
// MarkFailed records a failed probe or dial for tag: LastFail is set to now while
|
||||
// LastOK/Delay of an existing entry are preserved, so a node that once worked keeps
|
||||
// its last known latency for display. The entry is never deleted here — a marked
|
||||
// tag stays distinguishable from "never measured" (plan §2 Д5).
|
||||
func (s *HistoryStorage) MarkFailed(tag string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.access.Lock()
|
||||
updated := &adapter.URLTestHistory{LastFail: time.Now()}
|
||||
if previous := s.delayHistory[tag]; previous != nil {
|
||||
updated.LastOK = previous.LastOK
|
||||
updated.Delay = previous.Delay
|
||||
}
|
||||
s.delayHistory[tag] = updated
|
||||
s.pruneLocked()
|
||||
s.notifyUpdated()
|
||||
s.access.Unlock()
|
||||
}
|
||||
|
||||
// Verdict classifies tag against the wall clock: alive when the last success is
|
||||
// newer than the last failure and younger than ttl, dead when the last failure is
|
||||
// newer than the last success and younger than ttl, untested otherwise.
|
||||
func (s *HistoryStorage) Verdict(tag string, ttl time.Duration) HealthVerdict {
|
||||
return s.VerdictAt(tag, ttl, time.Now())
|
||||
}
|
||||
|
||||
// VerdictAt is Verdict against an explicit clock, for deterministic tests.
|
||||
func (s *HistoryStorage) VerdictAt(tag string, ttl time.Duration, now time.Time) HealthVerdict {
|
||||
history := s.LoadURLTestHistory(tag)
|
||||
if history == nil {
|
||||
return VerdictUntested
|
||||
}
|
||||
switch {
|
||||
case history.LastOK.After(history.LastFail) && now.Sub(history.LastOK) < ttl:
|
||||
return VerdictAlive
|
||||
case history.LastFail.After(history.LastOK) && now.Sub(history.LastFail) < ttl:
|
||||
return VerdictDead
|
||||
default:
|
||||
return VerdictUntested
|
||||
}
|
||||
}
|
||||
|
||||
// lx:end health-board
|
||||
@@ -0,0 +1,61 @@
|
||||
package urltest
|
||||
|
||||
// lx: health board §5.C — the reachability half of "should this be probed".
|
||||
//
|
||||
// # Two different reasons not to probe, and why they cannot be one flag
|
||||
//
|
||||
// A group's OWN probing schedule is stood down for two unrelated reasons, and
|
||||
// conflating them breaks one of the two:
|
||||
//
|
||||
// - NOT USED — no enabled routing rule reaches this group, so probing it
|
||||
// measures a path nothing travels. That is a property of the CONFIG, it is
|
||||
// decided once when the config is generated, and it travels in the config
|
||||
// itself (option.URLTestOutboundOptions.SelfCheck). It cannot change while
|
||||
// the box runs, because the rules cannot change while the box runs.
|
||||
//
|
||||
// - NOT REACHABLE RIGHT NOW — the group is a hop of a chain and a hop in
|
||||
// FRONT of it is currently dead. Every member of this group dials through
|
||||
// that hop, so every probe would fail inside it: the measurement would be
|
||||
// about the broken hop, and would be recorded against this one. That is a
|
||||
// property of the WORLD, it changes minute by minute, and it must be
|
||||
// re-asked every time rather than baked into the config — a hop that comes
|
||||
// back must resume probing on its own, with no reapply and nobody pressing
|
||||
// anything.
|
||||
//
|
||||
// ProbeGate is the second one. It is deliberately a QUESTION asked at the
|
||||
// moment of probing and never a stored answer: there is no flag to set, so
|
||||
// there is no flag to forget to clear.
|
||||
//
|
||||
// The gate governs the group's own SCHEDULE only — the warm-up sweep and the
|
||||
// ticker. An explicit check (a human, an API call) is a deliberate request and
|
||||
// is never refused, exactly as with SelfCheck.
|
||||
type ProbeGate interface {
|
||||
// ProbeAllowed reports whether the outbound tagged tag may run its own
|
||||
// scheduled probe right now.
|
||||
//
|
||||
// Implementations MUST answer true when they do not know: a gate that
|
||||
// refuses on missing information would silence probing precisely when the
|
||||
// system has the least idea what is going on, and nothing would ever
|
||||
// measure its way out of that. A nil ProbeGate means "no gate" and every
|
||||
// probe proceeds.
|
||||
ProbeAllowed(tag string) bool
|
||||
|
||||
// ProbeWhenIdle reports whether the outbound tagged tag must keep measuring
|
||||
// even when no traffic is passing through it.
|
||||
//
|
||||
// A urltest group normally probes only while it is in use: Touch arms the
|
||||
// ticker on a dial, and the idle timeout stops it again. That is right for a
|
||||
// group whose readings matter only while somebody is dialling it, and wrong
|
||||
// for one the routing config REACHES: a rule that matches rarely — a narrow
|
||||
// domain list, say — is in force the whole time, so the health of its target
|
||||
// is a live question the whole time. Letting it go quiet means the panel
|
||||
// reports "untested" about a rule that is armed, and the first real request
|
||||
// pays a cold probe instead of picking an already-known-good member.
|
||||
//
|
||||
// Unlike ProbeAllowed, the safe answer here is FALSE when nothing is known.
|
||||
// This one ADDS work, and a gate that claimed it on missing information would
|
||||
// keep every group in the process probing forever — not a default anybody
|
||||
// asked for. Absent gate, unknown tag, nothing configured yet: false, and the
|
||||
// idle timeout behaves exactly as it always has.
|
||||
ProbeWhenIdle(tag string) bool
|
||||
}
|
||||
@@ -21,6 +21,10 @@ type HistoryStorage struct {
|
||||
access sync.RWMutex
|
||||
delayHistory map[string]*adapter.URLTestHistory
|
||||
updateHooks []*observable.Subscriber[struct{}]
|
||||
// evicted counts entries dropped by the capacity bound (board_lx.go). The map
|
||||
// is keyed by outbound tags chosen by a subscription provider, so it needs a
|
||||
// ceiling; see the comment on maxBoardEntries.
|
||||
evicted uint64
|
||||
}
|
||||
|
||||
func NewHistoryStorage() *HistoryStorage {
|
||||
@@ -59,7 +63,23 @@ func (s *HistoryStorage) DeleteURLTestHistory(tag string) {
|
||||
|
||||
func (s *HistoryStorage) StoreURLTestHistory(tag string, history *adapter.URLTestHistory) {
|
||||
s.access.Lock()
|
||||
// lx:begin health-board
|
||||
// Health board (plan §5.A): overwriting an entry with a fresh success must not
|
||||
// erase the recorded failure — Verdict compares LastOK against LastFail, so
|
||||
// dropping LastFail here would forge an eternal "alive". Callers only ever set
|
||||
// LastOK/Delay on success; a caller that deliberately sets LastFail wins.
|
||||
if history.LastFail.IsZero() {
|
||||
if previous := s.delayHistory[tag]; previous != nil {
|
||||
history.LastFail = previous.LastFail
|
||||
}
|
||||
}
|
||||
// lx:end health-board
|
||||
s.delayHistory[tag] = history
|
||||
// lx:begin health-board — the map is keyed by provider-chosen tags and the
|
||||
// store outlives every engine generation, so it must bound itself here: no
|
||||
// shater path ever calls DeleteURLTestHistory. See maxBoardEntries.
|
||||
s.pruneLocked()
|
||||
// lx:end health-board
|
||||
s.notifyUpdated()
|
||||
s.access.Unlock()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// lx:begin health-board
|
||||
|
||||
package urltest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
)
|
||||
|
||||
// TestVerdictTable drives VerdictAt through every classification the health board
|
||||
// must produce (plan §5.A): the newest FRESH observation decides, and anything
|
||||
// older than the TTL decays to untested.
|
||||
func TestVerdictTable(t *testing.T) {
|
||||
const ttl = 10 * time.Minute
|
||||
now := time.Now()
|
||||
at := func(ago time.Duration) time.Time { return now.Add(-ago) }
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
history *adapter.URLTestHistory // nil = no entry stored
|
||||
want HealthVerdict
|
||||
}{
|
||||
{
|
||||
name: "fresh success is alive",
|
||||
history: &adapter.URLTestHistory{LastOK: at(time.Minute), Delay: 42},
|
||||
want: VerdictAlive,
|
||||
},
|
||||
{
|
||||
name: "fresh failure is dead",
|
||||
history: &adapter.URLTestHistory{LastFail: at(time.Minute)},
|
||||
want: VerdictDead,
|
||||
},
|
||||
{
|
||||
name: "stale success (older than TTL) decays to untested",
|
||||
history: &adapter.URLTestHistory{LastOK: at(ttl + time.Minute), Delay: 42},
|
||||
want: VerdictUntested,
|
||||
},
|
||||
{
|
||||
name: "failure after success is dead",
|
||||
history: &adapter.URLTestHistory{
|
||||
LastOK: at(2 * time.Minute),
|
||||
Delay: 42,
|
||||
LastFail: at(time.Minute),
|
||||
},
|
||||
want: VerdictDead,
|
||||
},
|
||||
{
|
||||
name: "success after failure is alive",
|
||||
history: &adapter.URLTestHistory{
|
||||
LastOK: at(time.Minute),
|
||||
Delay: 42,
|
||||
LastFail: at(2 * time.Minute),
|
||||
},
|
||||
want: VerdictAlive,
|
||||
},
|
||||
{
|
||||
name: "no entry is untested",
|
||||
history: nil,
|
||||
want: VerdictUntested,
|
||||
},
|
||||
{
|
||||
name: "empty entry (both timestamps zero) is untested",
|
||||
history: &adapter.URLTestHistory{},
|
||||
want: VerdictUntested,
|
||||
},
|
||||
{
|
||||
name: "stale failure (older than TTL) decays to untested",
|
||||
history: &adapter.URLTestHistory{
|
||||
LastOK: at(2 * ttl),
|
||||
Delay: 42,
|
||||
LastFail: at(ttl + time.Minute),
|
||||
},
|
||||
want: VerdictUntested,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
storage := NewHistoryStorage()
|
||||
const tag = "node"
|
||||
if tc.history != nil {
|
||||
storage.delayHistory[tag] = tc.history
|
||||
}
|
||||
if got := storage.VerdictAt(tag, ttl, now); got != tc.want {
|
||||
t.Fatalf("VerdictAt(%+v) = %v, want %v", tc.history, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarkFailedPreservesSuccess verifies MarkFailed records the failure without
|
||||
// deleting the entry or losing the last known success/latency (plan §2 Д5).
|
||||
func TestMarkFailedPreservesSuccess(t *testing.T) {
|
||||
storage := NewHistoryStorage()
|
||||
const tag = "node"
|
||||
lastOK := time.Now().Add(-time.Minute)
|
||||
storage.StoreURLTestHistory(tag, &adapter.URLTestHistory{LastOK: lastOK, Delay: 42})
|
||||
|
||||
storage.MarkFailed(tag)
|
||||
|
||||
history := storage.LoadURLTestHistory(tag)
|
||||
if history == nil {
|
||||
t.Fatal("MarkFailed deleted the entry; it must only set LastFail")
|
||||
}
|
||||
if !history.LastOK.Equal(lastOK) || history.Delay != 42 {
|
||||
t.Fatalf("MarkFailed lost the last success: got %+v", history)
|
||||
}
|
||||
if history.LastFail.IsZero() || !history.LastFail.After(lastOK) {
|
||||
t.Fatalf("MarkFailed did not record a fresh failure: got %+v", history)
|
||||
}
|
||||
if got := storage.Verdict(tag, 10*time.Minute); got != VerdictDead {
|
||||
t.Fatalf("Verdict after MarkFailed = %v, want %v", got, VerdictDead)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMarkFailedWithoutEntry verifies MarkFailed on a never-measured tag creates a
|
||||
// failure-only entry (dead, not untested) instead of doing nothing.
|
||||
func TestMarkFailedWithoutEntry(t *testing.T) {
|
||||
storage := NewHistoryStorage()
|
||||
const tag = "node"
|
||||
|
||||
storage.MarkFailed(tag)
|
||||
|
||||
history := storage.LoadURLTestHistory(tag)
|
||||
if history == nil {
|
||||
t.Fatal("MarkFailed on an unknown tag must create an entry")
|
||||
}
|
||||
if !history.LastOK.IsZero() || history.Delay != 0 {
|
||||
t.Fatalf("MarkFailed invented a success: got %+v", history)
|
||||
}
|
||||
if got := storage.Verdict(tag, 10*time.Minute); got != VerdictDead {
|
||||
t.Fatalf("Verdict = %v, want %v", got, VerdictDead)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStorePreservesLastFail verifies a success overwrite keeps the previously
|
||||
// recorded failure timestamp, so Verdict can still order the two observations.
|
||||
func TestStorePreservesLastFail(t *testing.T) {
|
||||
storage := NewHistoryStorage()
|
||||
const tag = "node"
|
||||
|
||||
storage.MarkFailed(tag)
|
||||
failedAt := storage.LoadURLTestHistory(tag).LastFail
|
||||
|
||||
// A strictly later success: with the wall clock, LastOK could land on the SAME
|
||||
// tick as LastFail (Windows clock granularity) and read as untested (ties are
|
||||
// deliberately not alive — the ordering is strict).
|
||||
storage.StoreURLTestHistory(tag, &adapter.URLTestHistory{LastOK: failedAt.Add(time.Second), Delay: 7})
|
||||
|
||||
history := storage.LoadURLTestHistory(tag)
|
||||
if !history.LastFail.Equal(failedAt) {
|
||||
t.Fatalf("StoreURLTestHistory dropped LastFail: got %+v, want LastFail=%v", history, failedAt)
|
||||
}
|
||||
if got := storage.Verdict(tag, 10*time.Minute); got != VerdictAlive {
|
||||
t.Fatalf("Verdict after success-over-failure = %v, want %v", got, VerdictAlive)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNilStorageVerdict guards the nil-receiver contract shared with
|
||||
// LoadURLTestHistory: reads on a nil store degrade to untested, never panic.
|
||||
func TestNilStorageVerdict(t *testing.T) {
|
||||
var storage *HistoryStorage
|
||||
if got := storage.Verdict("node", time.Minute); got != VerdictUntested {
|
||||
t.Fatalf("nil storage Verdict = %v, want %v", got, VerdictUntested)
|
||||
}
|
||||
storage.MarkFailed("node") // must be a no-op, not a panic
|
||||
}
|
||||
|
||||
// lx:end health-board
|
||||
@@ -2,6 +2,9 @@ package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
// lx:begin sec-oomgate
|
||||
"sync"
|
||||
// lx:end sec-oomgate
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
@@ -19,6 +22,10 @@ type ManagedService struct {
|
||||
handler ManagedHandler
|
||||
debug bool
|
||||
oomReporter oomkiller.OOMReporter
|
||||
// lx:begin sec-oomgate
|
||||
oomReportMu sync.Mutex
|
||||
oomReportLast time.Time
|
||||
// lx:end sec-oomgate
|
||||
}
|
||||
|
||||
type ManagedServiceOptions struct {
|
||||
@@ -90,6 +97,18 @@ func (s *ManagedService) TriggerOOMReport(ctx context.Context, _ *emptypb.Empty)
|
||||
if s.oomReporter == nil {
|
||||
return nil, status.Error(codes.Unavailable, "OOM reporter not available")
|
||||
}
|
||||
// lx:begin sec-oomgate
|
||||
// Rate-limit operator-triggered reports to at most one per minute: each write
|
||||
// dumps process state + the config snapshot (secrets) to disk, so an
|
||||
// authenticated client must not be able to spin it in a tight loop.
|
||||
s.oomReportMu.Lock()
|
||||
if !s.oomReportLast.IsZero() && time.Since(s.oomReportLast) < time.Minute {
|
||||
s.oomReportMu.Unlock()
|
||||
return nil, status.Error(codes.ResourceExhausted, "OOM report rate-limited (max 1/min)")
|
||||
}
|
||||
s.oomReportLast = time.Now()
|
||||
s.oomReportMu.Unlock()
|
||||
// lx:end sec-oomgate
|
||||
return &emptypb.Empty{}, s.oomReporter.WriteReport(memory.Total())
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -2,6 +2,9 @@ package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
// lx:begin sec-consttime
|
||||
"crypto/subtle"
|
||||
// lx:end sec-consttime
|
||||
"strings"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
@@ -59,8 +62,11 @@ func authenticate(ctx context.Context, secret string) error {
|
||||
return status.Error(codes.Unauthenticated, "missing authorization")
|
||||
}
|
||||
token, isBearer := strings.CutPrefix(values[0], "Bearer ")
|
||||
if !isBearer || token != secret {
|
||||
// lx:begin sec-consttime
|
||||
// Constant-time compare: a plain != leaks the secret via response timing.
|
||||
if !isBearer || subtle.ConstantTimeCompare([]byte(token), []byte(secret)) != 1 {
|
||||
return status.Error(codes.Unauthenticated, "invalid authorization")
|
||||
}
|
||||
// lx:end sec-consttime
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -489,7 +489,7 @@ func (s *StartedService) readGroups() *Groups {
|
||||
item.Tag = itemTag
|
||||
item.Type = itemOutbound.Type()
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(itemOutbound)); history != nil {
|
||||
item.UrlTestTime = history.Time.Unix()
|
||||
item.UrlTestTime = history.LastOK.Unix() // lx: health board §5.A — Time renamed to LastOK
|
||||
item.UrlTestDelay = int32(history.Delay)
|
||||
}
|
||||
g.Items = append(g.Items, &item)
|
||||
@@ -620,8 +620,8 @@ func (s *StartedService) URLTest(ctx context.Context, request *URLTestRequest) (
|
||||
historyStorage.DeleteURLTestHistory(outboundTag)
|
||||
} else {
|
||||
historyStorage.StoreURLTestHistory(outboundTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: t,
|
||||
LastOK: time.Now(), // lx: health board §5.A — Time renamed to LastOK
|
||||
Delay: t,
|
||||
})
|
||||
}
|
||||
return nil, nil
|
||||
@@ -1063,7 +1063,7 @@ func (s *StartedService) SubscribeOutbounds(_ *emptypb.Empty, server grpc.Server
|
||||
Type: ob.Type(),
|
||||
}
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(ob)); history != nil {
|
||||
item.UrlTestTime = history.Time.Unix()
|
||||
item.UrlTestTime = history.LastOK.Unix() // lx: health board §5.A — Time renamed to LastOK
|
||||
item.UrlTestDelay = int32(history.Delay)
|
||||
}
|
||||
list.Outbounds = append(list.Outbounds, item)
|
||||
@@ -1074,7 +1074,7 @@ func (s *StartedService) SubscribeOutbounds(_ *emptypb.Empty, server grpc.Server
|
||||
Type: ep.Type(),
|
||||
}
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(ep)); history != nil {
|
||||
item.UrlTestTime = history.Time.Unix()
|
||||
item.UrlTestTime = history.LastOK.Unix() // lx: health board §5.A — Time renamed to LastOK
|
||||
item.UrlTestDelay = int32(history.Delay)
|
||||
}
|
||||
list.Outbounds = append(list.Outbounds, item)
|
||||
|
||||
@@ -86,8 +86,8 @@ func (s *StartedService) URLTestOutbound(ctx context.Context, request *URLTestOu
|
||||
return &URLTestOutboundResponse{Error: err.Error()}, nil
|
||||
}
|
||||
boxService.urlTestHistoryStorage.StoreURLTestHistory(realTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: delay,
|
||||
LastOK: time.Now(),
|
||||
Delay: delay,
|
||||
})
|
||||
return &URLTestOutboundResponse{Delay: uint32(delay)}, nil
|
||||
}
|
||||
@@ -168,7 +168,7 @@ func (s *StartedService) GetOutbounds(ctx context.Context, empty *emptypb.Empty)
|
||||
appendItem := func(detour adapter.Outbound) {
|
||||
item := &GroupItem{Tag: detour.Tag(), Type: detour.Type()}
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(detour)); history != nil {
|
||||
item.UrlTestTime = history.Time.Unix()
|
||||
item.UrlTestTime = history.LastOK.Unix()
|
||||
item.UrlTestDelay = int32(history.Delay)
|
||||
}
|
||||
list.Outbounds = append(list.Outbounds, item)
|
||||
|
||||
@@ -131,7 +131,9 @@ func (s *StartedService) StartTailscaleSSHSession(
|
||||
continue
|
||||
}
|
||||
go ssh.DiscardRequests(reqs)
|
||||
go s.forwardSSHAgentChannel(channel)
|
||||
// lx:begin sec-sshagent
|
||||
go s.forwardSSHAgentChannel(sessionCtx, channel)
|
||||
// lx:end sec-sshagent
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -313,7 +315,8 @@ func (s *StartedService) StartTailscaleSSHSession(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StartedService) forwardSSHAgentChannel(channel ssh.Channel) {
|
||||
// lx:begin sec-sshagent
|
||||
func (s *StartedService) forwardSSHAgentChannel(ctx context.Context, channel ssh.Channel) {
|
||||
defer channel.Close()
|
||||
fd, err := s.handler.ConnectSSHAgent()
|
||||
if err != nil {
|
||||
@@ -326,15 +329,33 @@ func (s *StartedService) forwardSSHAgentChannel(channel ssh.Channel) {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// The ssh-agent conn stays blocked in Read while idle, so io.Copy(channel,
|
||||
// conn) never returns on its own — without this it leaks a goroutine + the
|
||||
// agent fd for every closed session. Cancelling on either copy finishing (or
|
||||
// on the session ctx) closes both ends, unblocking the peer copy. Both Close
|
||||
// calls are idempotent with the deferred ones above.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
conn.Close()
|
||||
channel.Close()
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
io.Copy(conn, channel)
|
||||
cancel()
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
io.Copy(channel, conn)
|
||||
cancel()
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// lx:end sec-sshagent
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 419 KiB |
Vendored
-2
@@ -1,2 +0,0 @@
|
||||
untrusted comment: shater feed signing key
|
||||
RWRaxLF3aJy44JbcxSFujtrFFEQ8lIsnTkd1K5TdjIhdlC2c0wa0fv4V
|
||||
@@ -126,6 +126,12 @@ func (t *HTTP3Transport) newTransport() *http3.Transport {
|
||||
conn.Close()
|
||||
return nil, dialErr
|
||||
}
|
||||
// quic-go does not take ownership of the packet conn passed to
|
||||
// DialEarly: when the connection ends it only stops reading.
|
||||
go func() {
|
||||
<-quicConn.Context().Done()
|
||||
conn.Close()
|
||||
}()
|
||||
return quicConn, nil
|
||||
},
|
||||
TLSClientConfig: t.tlsConfig,
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
package quic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/quic-go"
|
||||
"github.com/sagernet/quic-go/http3"
|
||||
sbTLS "github.com/sagernet/sing-box/common/tls"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/dns"
|
||||
"github.com/sagernet/sing-box/dns/transport"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
|
||||
mDNS "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
var _ N.Dialer = (*trackingDialer)(nil)
|
||||
|
||||
// These tests pin down who owns the UDP socket handed to quic-go.
|
||||
//
|
||||
// quic-go's Dial/DialEarly take a net.PacketConn but do NOT take ownership of
|
||||
// it: quic.setupTransport() builds a Transport with createdConn=false, and
|
||||
// Transport.Close() then only calls conn.SetReadDeadline(time.Now()) instead of
|
||||
// conn.Close(). So every QUIC connection torn down here — idle timeout, a
|
||||
// retryable error, an engine reload calling Reset() — used to strand the UDP
|
||||
// socket that carried it for the rest of the process's life. On a router that
|
||||
// resolves through DoQ/DoH3 for months that is an unbounded fd leak.
|
||||
//
|
||||
// Both tests reconnect once and assert the socket from the FIRST connection is
|
||||
// actually closed. Without the `<-conn.Context().Done() -> rawConn.Close()`
|
||||
// watchdogs in quic.go / http3.go they fail on that assertion.
|
||||
|
||||
type trackedConn struct {
|
||||
net.Conn
|
||||
closeOnce sync.Once
|
||||
closed chan struct{}
|
||||
}
|
||||
|
||||
func (c *trackedConn) Close() error {
|
||||
c.closeOnce.Do(func() { close(c.closed) })
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// trackingDialer hands out real UDP sockets and remembers every one of them.
|
||||
type trackingDialer struct {
|
||||
access sync.Mutex
|
||||
conns []*trackedConn
|
||||
}
|
||||
|
||||
func (d *trackingDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||
conn, err := (&net.Dialer{}).DialContext(ctx, network, destination.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tracked := &trackedConn{Conn: conn, closed: make(chan struct{})}
|
||||
d.access.Lock()
|
||||
d.conns = append(d.conns, tracked)
|
||||
d.access.Unlock()
|
||||
return tracked, nil
|
||||
}
|
||||
|
||||
func (d *trackingDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||
return net.ListenUDP("udp", nil)
|
||||
}
|
||||
|
||||
func (d *trackingDialer) count() int {
|
||||
d.access.Lock()
|
||||
defer d.access.Unlock()
|
||||
return len(d.conns)
|
||||
}
|
||||
|
||||
func (d *trackingDialer) at(index int) *trackedConn {
|
||||
d.access.Lock()
|
||||
defer d.access.Unlock()
|
||||
return d.conns[index]
|
||||
}
|
||||
|
||||
func (d *trackingDialer) closeAll() {
|
||||
d.access.Lock()
|
||||
defer d.access.Unlock()
|
||||
for _, conn := range d.conns {
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func requireClosed(t *testing.T, conn *trackedConn, what string) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-conn.closed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s: the UDP socket of the retired QUIC connection was never closed — quic-go does not own it, we must", what)
|
||||
}
|
||||
}
|
||||
|
||||
func requireDialed(t *testing.T, dialer *trackingDialer, want int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if dialer.count() >= want {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("expected at least %d dial(s), got %d", want, dialer.count())
|
||||
}
|
||||
|
||||
func testServerTLSConfig(t *testing.T, nextProtos []string) *tls.Config {
|
||||
t.Helper()
|
||||
certificate, err := sbTLS.GenerateKeyPair(nil, nil, nil, "localhost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &tls.Config{
|
||||
Certificates: []tls.Certificate{*certificate},
|
||||
NextProtos: nextProtos,
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
}
|
||||
|
||||
func testClientTLSConfig(t *testing.T, nextProtos []string) sbTLS.Config {
|
||||
t.Helper()
|
||||
config, err := sbTLS.NewClient(context.Background(), logger.NOP(), "localhost", option.OutboundTLSOptions{
|
||||
Enabled: true,
|
||||
Insecure: true,
|
||||
ServerName: "localhost",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config.SetNextProtos(nextProtos)
|
||||
return config
|
||||
}
|
||||
|
||||
// startDoQServer serves a minimal DoQ responder and returns its address.
|
||||
func startDoQServer(t *testing.T) M.Socksaddr {
|
||||
t.Helper()
|
||||
listener, err := quic.ListenAddr("127.0.0.1:0", testServerTLSConfig(t, []string{"doq"}), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
listener.Close()
|
||||
})
|
||||
go func() {
|
||||
for {
|
||||
conn, acceptErr := listener.Accept(ctx)
|
||||
if acceptErr != nil {
|
||||
return
|
||||
}
|
||||
go func(conn *quic.Conn) {
|
||||
for {
|
||||
stream, streamErr := conn.AcceptStream(ctx)
|
||||
if streamErr != nil {
|
||||
return
|
||||
}
|
||||
go func(stream *quic.Stream) {
|
||||
defer stream.Close()
|
||||
request, readErr := transport.ReadMessage(stream)
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
response := new(mDNS.Msg)
|
||||
response.SetReply(request)
|
||||
transport.WriteMessage(stream, 0, response)
|
||||
}(stream)
|
||||
}
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return M.ParseSocksaddr(listener.Addr().String())
|
||||
}
|
||||
|
||||
func testQuery() *mDNS.Msg {
|
||||
message := new(mDNS.Msg)
|
||||
message.SetQuestion("example.com.", mDNS.TypeA)
|
||||
return message
|
||||
}
|
||||
|
||||
func TestQUICTransportClosesPacketConnOnReconnect(t *testing.T) {
|
||||
t.Parallel()
|
||||
serverAddr := startDoQServer(t)
|
||||
dialer := &trackingDialer{}
|
||||
t.Cleanup(dialer.closeAll)
|
||||
|
||||
dnsTransport := &Transport{
|
||||
TransportAdapter: dns.NewTransportAdapter(C.DNSTypeQUIC, "test-doq", nil),
|
||||
dialer: dialer,
|
||||
serverAddr: serverAddr,
|
||||
tlsConfig: testClientTLSConfig(t, []string{"doq"}),
|
||||
connection: transport.NewConnPool(transport.ConnPoolOptions[*quic.Conn]{
|
||||
Mode: transport.ConnPoolSingle,
|
||||
IsAlive: func(conn *quic.Conn) bool {
|
||||
return conn != nil && !common.Done(conn.Context())
|
||||
},
|
||||
Close: func(conn *quic.Conn, _ error) {
|
||||
conn.CloseWithError(0, "")
|
||||
},
|
||||
}),
|
||||
}
|
||||
t.Cleanup(func() { dnsTransport.Close() })
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if _, err := dnsTransport.Exchange(ctx, testQuery()); err != nil {
|
||||
t.Fatal("first exchange: ", err)
|
||||
}
|
||||
requireDialed(t, dialer, 1)
|
||||
first := dialer.at(0)
|
||||
|
||||
// Retire the connection the way a retryable error or an engine reload does.
|
||||
dnsTransport.Reset()
|
||||
requireClosed(t, first, "Reset()")
|
||||
|
||||
// The reconnect must still work, on a fresh socket.
|
||||
if _, err := dnsTransport.Exchange(ctx, testQuery()); err != nil {
|
||||
t.Fatal("second exchange: ", err)
|
||||
}
|
||||
requireDialed(t, dialer, 2)
|
||||
second := dialer.at(1)
|
||||
if second == first {
|
||||
t.Fatal("expected a new UDP socket for the reconnect")
|
||||
}
|
||||
|
||||
if err := dnsTransport.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireClosed(t, second, "Close()")
|
||||
}
|
||||
|
||||
func TestHTTP3TransportClosesPacketConnOnReconnect(t *testing.T) {
|
||||
t.Parallel()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/dns-query", func(writer http.ResponseWriter, request *http.Request) {
|
||||
message, err := readRequestMessage(request)
|
||||
if err != nil {
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
response := new(mDNS.Msg)
|
||||
response.SetReply(message)
|
||||
rawResponse, err := response.Pack()
|
||||
if err != nil {
|
||||
writer.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writer.Header().Set("Content-Type", transport.MimeType)
|
||||
writer.Write(rawResponse)
|
||||
})
|
||||
listener, err := quic.ListenAddrEarly("127.0.0.1:0", testServerTLSConfig(t, []string{http3.NextProtoH3}), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &http3.Server{Handler: mux}
|
||||
go server.ServeListener(listener)
|
||||
t.Cleanup(func() {
|
||||
server.Close()
|
||||
listener.Close()
|
||||
})
|
||||
serverAddr := M.ParseSocksaddr(listener.Addr().String())
|
||||
|
||||
dialer := &trackingDialer{}
|
||||
t.Cleanup(dialer.closeAll)
|
||||
|
||||
stdConfig := &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
ServerName: "localhost",
|
||||
NextProtos: []string{http3.NextProtoH3},
|
||||
MinVersion: tls.VersionTLS13,
|
||||
}
|
||||
dnsTransport := &HTTP3Transport{
|
||||
TransportAdapter: dns.NewTransportAdapter(C.DNSTypeHTTP3, "test-doh3", nil),
|
||||
logger: logger.NOP(),
|
||||
dialer: dialer,
|
||||
destination: &url.URL{Scheme: "https", Host: "localhost", Path: "/dns-query"},
|
||||
headers: http.Header{},
|
||||
serverAddr: serverAddr,
|
||||
tlsConfig: stdConfig,
|
||||
}
|
||||
dnsTransport.transport = dnsTransport.newTransport()
|
||||
t.Cleanup(func() { dnsTransport.Close() })
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if _, err = dnsTransport.Exchange(ctx, testQuery()); err != nil {
|
||||
t.Fatal("first exchange: ", err)
|
||||
}
|
||||
requireDialed(t, dialer, 1)
|
||||
first := dialer.at(0)
|
||||
|
||||
dnsTransport.Reset()
|
||||
requireClosed(t, first, "Reset()")
|
||||
|
||||
if _, err = dnsTransport.Exchange(ctx, testQuery()); err != nil {
|
||||
t.Fatal("second exchange: ", err)
|
||||
}
|
||||
requireDialed(t, dialer, 2)
|
||||
second := dialer.at(1)
|
||||
if second == first {
|
||||
t.Fatal("expected a new UDP socket for the reconnect")
|
||||
}
|
||||
|
||||
if err = dnsTransport.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requireClosed(t, second, "Close()")
|
||||
}
|
||||
|
||||
func readRequestMessage(request *http.Request) (*mDNS.Msg, error) {
|
||||
defer request.Body.Close()
|
||||
rawMessage := make([]byte, 4096)
|
||||
n, err := readFull(request.Body, rawMessage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var message mDNS.Msg
|
||||
err = message.Unpack(rawMessage[:n])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func readFull(reader interface{ Read([]byte) (int, error) }, buffer []byte) (int, error) {
|
||||
var total int
|
||||
for total < len(buffer) {
|
||||
n, err := reader.Read(buffer[total:])
|
||||
total += n
|
||||
if err != nil {
|
||||
if total > 0 {
|
||||
return total, nil
|
||||
}
|
||||
return total, err
|
||||
}
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/quic-go"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
@@ -117,6 +118,12 @@ func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg,
|
||||
rawConn.Close()
|
||||
return nil, E.Cause(err, "establish QUIC connection")
|
||||
}
|
||||
// quic-go does not take ownership of the packet conn passed to
|
||||
// DialEarly: when the connection ends it only stops reading.
|
||||
go func() {
|
||||
<-earlyConnection.Context().Done()
|
||||
rawConn.Close()
|
||||
}()
|
||||
return earlyConnection, nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -144,6 +151,11 @@ func (t *Transport) exchange(ctx context.Context, message *mDNS.Msg, conn *quic.
|
||||
return nil, E.Cause(err, "open stream")
|
||||
}
|
||||
defer stream.CancelRead(0)
|
||||
stopWatch := context.AfterFunc(ctx, func() {
|
||||
stream.CancelRead(0)
|
||||
_ = stream.SetWriteDeadline(time.Now())
|
||||
})
|
||||
defer stopWatch()
|
||||
err = transport.WriteMessage(stream, 0, message)
|
||||
if err != nil {
|
||||
stream.Close()
|
||||
|
||||
@@ -10,6 +10,124 @@ tracks only the fork. Versions are tagged `vX.Y.Z-lx.N`; releases are built by
|
||||
`lx-release.yml`. Tags carrying an `-rc.N` / `-alpha.N` / `-beta.N` suffix publish
|
||||
as GitHub **pre-releases** and never become "Latest".
|
||||
|
||||
#### Unreleased (shater)
|
||||
|
||||
**`l3-honest-drop` — ICMP routed to an L4-only outbound is dropped, not
|
||||
forged** — ships with `shaterd` (part of the shater L3 ingress,
|
||||
`docs-shater/DECISIONS.md` D25), not as an lx release tag; recorded here because
|
||||
it edits two upstream files. Without it the TUN stack answers an unroutable echo
|
||||
ITSELF — sing-tun's `ICMPForwarder.HandlePacket` rewrites Echo→EchoReply
|
||||
whenever the flow judgment comes back Accept (`stack_gvisor_icmp.go`) — so a
|
||||
ping routed to vless/vmess/… would read as a working tunnel while the packet
|
||||
never left the router.
|
||||
|
||||
* **`route/route.go` (`PreMatch`)** — the pre-match walk was renamed to
|
||||
`preMatch` and the exported `PreMatch` became a thin FUNNEL that rewrites
|
||||
`PreMatchContinue` and `PreMatchBypass` to `PreMatchDrop` for
|
||||
`N.NetworkICMP`. An earlier version overrode `continueResult` inside
|
||||
`preMatchFlow` instead; that covered only the exits reaching that function and
|
||||
left three of the walk's own exits forging — the `prepareMatchMetadata` error
|
||||
return, the sniff bail-outs, and the `default:` arm of the rule-action switch
|
||||
(every action pre-match has no arm for: `hijack-dns`, `direct`, …). A guard on
|
||||
the single return value cannot be outgrown by a new exit. `PreMatchBypass` is
|
||||
folded in because sing-tun implements `ActionBypass` on the nfqueue plane only
|
||||
— on the TUN path it lands in the same `default:` arm as Accept, i.e. forges.
|
||||
* **`adapter/router.go` (`JudgeFlow`, the `!isPort` branch)** — ICMP returns
|
||||
`ActionDrop` where it fell through to `ActionAccept`. Second line of defense:
|
||||
`adapter.FlowOutbound` and `tun.Port` are distinct interfaces, and a drift
|
||||
between them must not quietly re-enable the forged reply.
|
||||
* **TCP/UDP behaviour is unchanged** — `PreMatchContinue` still means "take the
|
||||
ordinary connection route" for both, `PreMatchBypass` still means bypass, and
|
||||
the `!isPort` fallthrough still returns `ActionAccept` for them; pinned by
|
||||
`route/prematch_icmp_lx_test.go` and `adapter/judgeflow_icmp_lx_test.go`
|
||||
(both inside the marker), each ICMP case having an explicit TCP/UDP twin.
|
||||
* **NOT covered: a FRAGMENTED echo to a WireGuard/AWG outbound is still
|
||||
forged** — sing-tun's `ForwardDispatcher.Dispatch` returns before asking for a
|
||||
verdict at all when `parsed.fragment`, and the reassembled packet reaches
|
||||
`ICMPForwarder.HandlePacket`, whose `installFlow` demands an UNSPECIFIED port
|
||||
address that a WireGuard endpoint never has. Fixing it inside `JudgeFlow`
|
||||
is NOT possible — both consumers call it with identical arguments and the
|
||||
working path needs the concrete address. Full chain, the two viable fixes and
|
||||
the trap are in `docs-shater/DECISIONS.md` D25, "KNOWN HOLE".
|
||||
* **Rebase cost: two small marked blocks** (`lx:begin/end l3-honest-drop`, a
|
||||
wrapper function in `route/route.go` and one branch body in
|
||||
`adapter/router.go`) plus the two self-contained test files — carried across
|
||||
an upstream rebase by eye. Note that `PreMatch`'s own body now lives in
|
||||
`preMatch`, so an upstream change to the walk applies to that function.
|
||||
|
||||
**Fork-layer + control-plane rework of proxy health** — ships with `shaterd`
|
||||
(the shater router daemon), not as an lx release tag; recorded here because the
|
||||
load-bearing half lives in fork zones (`common/urltest`, `protocol/group`).
|
||||
Routing rules now always get a **live** node under every group strategy, and
|
||||
the background prober measures **only what the rules can reach**.
|
||||
|
||||
* **Health board with real verdicts (`common/urltest`).** A history entry used
|
||||
to record only success (`{Time, Delay}`) and a failed check *deleted* it, so a
|
||||
dead member was indistinguishable from a never-measured one. The entry is now
|
||||
`{LastOK, Delay, LastFail}`; a failure marks, never deletes (deletion is
|
||||
reserved for removing a node from the config). The verdict is computed on
|
||||
read — `alive` (success fresher than failure and younger than TTL), `dead`
|
||||
(failure fresher, while it is fresh), `untested` (nothing fresh) — with
|
||||
TTL = max(3 × global probe interval, 10 min), so a stale success decays to
|
||||
`untested` instead of reading as alive forever. Everyone who learns of a death
|
||||
(the group checker, the observatory, a failed user dial) writes here;
|
||||
selection, balancer slots and the panel read here. The private `engine.dead`
|
||||
overlay that only the panel could see is gone.
|
||||
|
||||
* **Selection is alive-only, and a failed dial retries (`protocol/group`).**
|
||||
least ping ranks by delay **among alive members only**, falls back to untested
|
||||
members in config order, and only then to first-by-config; round_robin /
|
||||
random / failover slot liveness is fed by board verdicts (TTL included), not
|
||||
by "a history entry exists". A failed user dial marks the member dead on the
|
||||
board and transparently re-picks — at most 3 candidates per connection, within
|
||||
the dial deadline (UDP retries only until the first send) — so the connection
|
||||
survives as long as any member is alive. A failed group check marks-fail
|
||||
instead of deleting; an immediate first check on PostStart shrinks the
|
||||
cold-start blind window to seconds. `selector` (manual pin) semantics and the
|
||||
SPEC 019 slot invariants are untouched. When a whole group dies, its rule
|
||||
blocks fail-closed — no silent fallback.
|
||||
|
||||
* **Observatory replaces the background sweep (`shater/engine`).** The probe
|
||||
plan is derived from the applied config by reachability — enabled-rule targets
|
||||
(plus `Final` and DNS detours) → groups → members / egress copies; a chain is
|
||||
probed end-to-end by dialing its exit tag through the whole hop path (the Xray
|
||||
observatory-through-`proxySettings` equivalent; chains were previously not
|
||||
probed at all), and chain group-hop members are probed through their path
|
||||
prefix. Schedule: 10 s tick, batch 24, concurrency 12, 5 s probe timeout; a
|
||||
tag refreshes on the global probe interval; a freshness gate skips tags the
|
||||
active group's own checker already measures; the cursor survives no-op
|
||||
reconciles, and the first pass after apply is immediate. Every alive↔dead
|
||||
flip is logged (info, tag + probe/dial reason) — the diagnostic trail for a
|
||||
dead chain hop and for flapping. The `GroupHealth` toggle now gates the
|
||||
observatory.
|
||||
|
||||
* **Probe URL / Interval are global-only.** The per-group `ProbeURL` /
|
||||
`ProbeInterval` overrides are deleted (model, UCI, generate, panel); probing
|
||||
is configured solely by the global Settings fields, which also drive the
|
||||
native group checker and the exit test (failover keeps its 30 s default
|
||||
interval). With one URL all delay measurements are comparable, and the "one
|
||||
node in two groups with different URLs" ambiguity disappears. Old UCI configs
|
||||
still carrying the options parse silently and drain on the next write.
|
||||
|
||||
* **Subscription nodes move out of UCI.** Each subscription's nodes are cached
|
||||
in `/etc/shater/subs/<name>.json` (atomic tmp+rename; tmpfs fallback
|
||||
`/tmp/shater-subs` when the overlay cannot take the write); UCI keeps only
|
||||
hand-added nodes and the `subscription` sections, so `sub update` rewrites its
|
||||
own cache file instead of the whole `/etc/config/shater`. Legacy `from_sub`
|
||||
nodes migrate into the cache on first read.
|
||||
|
||||
* **One manual test — the exit test, now for chains too.** The manual
|
||||
"Test all nodes" probe-all run is removed together with the sweep
|
||||
(`/api/nodes/test` returns 404). The remaining manual test is the per-target
|
||||
"Test" (delay + exit IP + country through the real path), extended from groups
|
||||
to chains via the chain exit tag.
|
||||
|
||||
* **"Unused" badge.** A group or chain reachable from no enabled routing rule is
|
||||
outside the observatory plan and reported `used:false`; the panel shows
|
||||
"unused" instead of health counters. Unreferenced nodes are deliberately never
|
||||
probed — they stay honestly `untested` until a rule references them, at which
|
||||
point the observatory covers them within seconds.
|
||||
|
||||
#### v1.14.0-lx.3
|
||||
|
||||
**Stable release** (published as "Latest", not a pre-release) — a promotion of
|
||||
|
||||
+10
-11
@@ -31,12 +31,11 @@ Do not delete it — we port proven pieces from it. What v0.1 has:
|
||||
- **`luci-app-shater`** — a custom "instrument panel" LuCI app (client-side JS +
|
||||
ucode/rpcd ubus backend): Overview with a live Signal Path, Simple/Advanced
|
||||
toggle, quick-start wizard, Nodes/Subs/Rules/DNS/Live/Profiles/Settings pages.
|
||||
- **CI + signed opkg feed** on Gitea: builds per-arch, signs the feed index with
|
||||
usign, publishes a rolling `latest` Gitea release consumable as `src/gz`. **Feed
|
||||
signing key fingerprint `5ac4b177689cb8e0`**; public key `dist/shater-feed.pub`,
|
||||
secret in the Gitea repo secret `KEY_BUILD`.
|
||||
- **CI + a signed package feed** on Gitea: builds per-arch, signs the feed index,
|
||||
publishes a rolling `latest` Gitea release the router consumes as a feed.
|
||||
(v0.1 shipped `.ipk` signed with a usign key — that lane is retired, D22.)
|
||||
- Verified end-to-end on the VM: real LAN client proxied, DNS anti-leak, honest
|
||||
fail-closed, opkg install/upgrade from the signed feed.
|
||||
fail-closed, install/upgrade from the signed feed.
|
||||
|
||||
v0.1 is engine-locked to **xray-core**; its generator, share-link parser and
|
||||
`run.json` are xray-shaped.
|
||||
@@ -91,7 +90,7 @@ We are rebasing onto a new engine and a new UI architecture. Full rationale in
|
||||
- **`shater` branch `v0.1`** = the standalone xray-based version (frozen, ported
|
||||
from).
|
||||
- Until Phase 1 merges the engine in, `main` is the docs-first overlay seed you
|
||||
are reading now (LICENSE, README, `docs-shater/`, `dist/shater-feed.pub`).
|
||||
are reading now (LICENSE, README, `docs-shater/`, the feed signing key).
|
||||
|
||||
## What to port from v0.1 (don't rewrite these ideas)
|
||||
|
||||
@@ -105,8 +104,8 @@ overlay, don't redo:
|
||||
- **Subscription fetch** (HAPP emulation, fingerprint reconcile, per-sub cache)
|
||||
and the flexible **ruleset/list** model — though sing-box has its own share-link
|
||||
parser and config schema we now target.
|
||||
- **CI feed build + usign signing + Gitea release** (adapt to the single forked
|
||||
binary; keep key `5ac4b177689cb8e0`).
|
||||
- **CI feed build + index signing + Gitea release** (adapted to the single forked
|
||||
binary; the format is apk, signed with the EC key — D22).
|
||||
- The LuCI **design system** (the "instrument panel" identity) — reused for the
|
||||
mini-dashboard and as the panel's visual language.
|
||||
|
||||
@@ -122,9 +121,9 @@ filter/stats engine wired into sing-box's DNS.
|
||||
`https://github.com/SagerNet/sing-box`).
|
||||
- **CI:** Gitea Actions (act_runner + Docker). v0.1's workflow was removed from
|
||||
`main`; new CI is added when the v0.2 build exists.
|
||||
- **Feed signing:** usign key `5ac4b177689cb8e0`; secret in repo secret
|
||||
`KEY_BUILD`; public key `dist/shater-feed.pub` (kept so existing installs keep
|
||||
verifying).
|
||||
- **Feed signing:** EC (prime256v1) key for the apk index; secret in the repo
|
||||
secret `KEY_APK`; public key `dist/shater-apk.pem`, installed on routers as
|
||||
`/etc/apk/keys/shater-apk.pem`. Never regenerate it (D22).
|
||||
- **Test VM:** OpenWrt 24.10.3 x86_64 in Docker (`docker ps --filter
|
||||
name=openwrt-vm`). SSH via the ssh-manager MCP server `local_openwrt`
|
||||
(localhost:2222, root/openwrt). LuCI at `http://127.0.0.1:8080` (root/openwrt),
|
||||
|
||||
+874
-1
@@ -64,11 +64,17 @@ sing-box is GPL-3.0; linking it makes the combined work GPL-3.0. Our own files m
|
||||
stay GPL-2.0-or-later (which permits the upgrade), but the project LICENSE is
|
||||
GPL-3.0 for clarity.
|
||||
|
||||
## D7 — Keep the v0.1 feed signing identity
|
||||
## D7 — Keep the v0.1 feed signing identity *(SUPERSEDED by D22)*
|
||||
The usign feed key `5ac4b177689cb8e0` (public key in `dist/shater-feed.pub`,
|
||||
secret in Gitea secret `KEY_BUILD`) carries over, so routers that already trust it
|
||||
keep verifying v0.2 packages. Do not regenerate it without a documented rotation.
|
||||
|
||||
> **Superseded 2026-07-25 (D22).** The opkg feed this identity signed no longer
|
||||
> exists, so there is nothing left for the key to verify. It was never rotated or
|
||||
> compromised — it is simply unused. `dist/shater-feed.pub` was deleted from the
|
||||
> tree; the reasoning, and how to resurrect the identity if it is ever needed
|
||||
> again, is in D22.
|
||||
|
||||
## D8 — Preserve, don't destroy: v0.1 lives on its branch
|
||||
The reset moved the full working xray-based project to the `v0.1` branch and
|
||||
cleaned `main`. Nothing is lost; reusable logic (reliability layer, nft/routing,
|
||||
@@ -95,6 +101,10 @@ runtime, forcing an ELF with `PT_INTERP=/lib64/ld-linux-x86-64.so.2` + `PT_DYNAM
|
||||
plane is tproxy/redirect (netplane); generate never emits a tun inbound, so
|
||||
the userspace gvisor netstack (~3.6 MB) is unreachable. If a tun inbound ever
|
||||
appears it falls back to the system stack — re-add the tag then.
|
||||
**REVERTED 2026-07-25 — that reasoning was wrong and shipped a dead feature.**
|
||||
gVisor is not only the tun stack: it is the netstack of the **WireGuard
|
||||
endpoint**, which we do emit and do declare [MVP]. See D23; the tag is back and
|
||||
is now held there by a test.
|
||||
- 2026-07-23: `with_clash_api` also dropped. The admin panel is shater's own
|
||||
web server and generate never emits a `clash_api` service; the desktop/CLI
|
||||
`LX_TAGS` keeps the tag for external dashboards.
|
||||
@@ -309,6 +319,10 @@ Three values, not two, because the leaks differ in *kind*: an ICMP echo is ephem
|
||||
user-initiated and reveals the address only to a host the user deliberately contacted,
|
||||
whereas ESP/GRE is a standing second tunnel carrying arbitrary traffic beside ours. A
|
||||
single toggle would make "I want ping to work" mean "I allow a parallel VPN bypass".
|
||||
*(Refined 2026-07-26 by D25: still true of TPROXY — but ICMP echo now has an
|
||||
opt-in data plane of its own, the dedicated L3 TUN, so the policy no longer
|
||||
speaks alone for ping; it keeps sole charge of ESP/GRE/IGMP and of the degraded
|
||||
paths.)*
|
||||
|
||||
**Fail-open degradations must be visible in the panel, not only in `logread`.** The
|
||||
audit deliberately converted many aborts into warn-and-continue (an unfetchable list,
|
||||
@@ -329,3 +343,862 @@ makes it affordable on the target hardware: measured on the testbed, StevenBlack
|
||||
2.4 MB of text became **80873 domains in a 491 KB `.srs`**, costing ~0.5 MB of a rootfs
|
||||
with ~33 MB free — so it ships in the production posture rather than being traded away
|
||||
for the 8 KB geosite ads list.
|
||||
|
||||
## D18 — Node health = a board with computed verdicts, NOT delete-on-failure + a dead-overlay
|
||||
Decided 2026-07-24 (proxy-health plan §5.A). Upstream `common/urltest` recorded
|
||||
only success (`{Time, Delay}`) and a failed check **deleted** the entry — a dead
|
||||
member was indistinguishable from a never-measured one. On top of that, deaths
|
||||
found by shater's own probing went to a private `engine.dead` overlay that only
|
||||
the panel read: selection never saw them, and an old success in history counted
|
||||
as "alive forever". Net effect, reproduced in the field: YouTube dead on a real
|
||||
device while the panel showed the group healthy.
|
||||
|
||||
**Decision: one health board, one source of truth.** The history entry becomes
|
||||
`{LastOK, Delay, LastFail}`; a failure *marks* (`MarkFailed`), never deletes —
|
||||
deletion is reserved for removing a node from the config. The verdict is a
|
||||
**method computed on read**, not a stored field: `alive` when the success is
|
||||
fresher than the failure and younger than TTL; `dead` while a fresher failure is
|
||||
itself fresh; `untested` otherwise, with TTL = max(3 × global probe interval,
|
||||
10 min). Everyone who learns of a death — the group's native checker, the
|
||||
observatory, a failed user dial — writes the same board; selection, balancer
|
||||
slots and the panel read the same board. The `engine.dead` overlay is deleted.
|
||||
- **Rejected: keep delete-on-failure and widen the overlay to selection.** Two
|
||||
stores of the same truth with undefined precedence; the overlay would need its
|
||||
own TTL/pruning and every reader would have to merge — exactly the
|
||||
divergence ("green panel, dead path") this decision exists to kill.
|
||||
- **Rejected: persist the board across reboots.** Measurements go stale faster
|
||||
than an overlay write is worth; after reboot everything is `untested` for
|
||||
seconds until the observatory's immediate first pass. In-memory, deliberately.
|
||||
- **Deferred, not rejected: Xray-style sliding-window stats / hysteresis.** The
|
||||
delay of the last success is enough to rank alive members in v1; the board
|
||||
keys and record shape leave room to widen without migration. Flapping is
|
||||
visible instead through the alive↔dead flip log (info) — the single
|
||||
diagnostic trail.
|
||||
Consequence: a stale success **decays** (alive → untested after TTL) instead of
|
||||
reading as alive forever, and a dead group blocks fail-closed — visible and
|
||||
alertable — rather than silently falling back.
|
||||
|
||||
## D19 — Background probing = an observatory driven by rule reachability, NOT a population sweep
|
||||
Decided 2026-07-24 (proxy-health plan §5.C, replaces `shater/engine/sweep.go`).
|
||||
The sweep probed the **whole population** round-robin — all nodes plus all
|
||||
per-group copies, used or not — yet chain copies were excluded entirely, so the
|
||||
one path users actually complained about ("rule → chain") was never measured.
|
||||
The manual "Test all nodes" run duplicated the same full-population walk on
|
||||
demand. On router budgets that is the wrong shape twice: work grows with the
|
||||
subscription size (~200 nodes), not with what the config uses.
|
||||
|
||||
**Decision: probe only what the rules can reach.** Following the Xray model
|
||||
(central observatory + balancers reading observations, §3 of the plan), a plan
|
||||
is built from the **applied** `option.Options` by reachability: enabled-rule
|
||||
targets (plus `Final` and DNS detours) → groups → members / egress copies; a
|
||||
chain is probed **end-to-end** by dialing its exit tag through the whole hop
|
||||
path (the Xray observatory-through-`proxySettings` equivalent); chain group-hop
|
||||
members are probed through their path prefix. Everything unreferenced stays
|
||||
`untested` and its group/chain is badged "unused" in the panel — so untested
|
||||
never looks like a health problem. A freshness gate skips tags an active
|
||||
group's own checker already measures; the cursor survives no-op reconciles
|
||||
(the sweep's release-blocker: cron reconciles must not restart the cycle);
|
||||
the manual probe-all is removed with the sweep.
|
||||
- **Rejected: keep the sweep.** Probes hundreds of unused nodes on a router
|
||||
budget and still misses chains; its "coverage" is what made per-node health
|
||||
look authoritative while the used path went unmeasured.
|
||||
- **Rejected: probe every chain hop individually.** Multiplied probe traffic
|
||||
for diagnostics that never affects selection — no choice depends on a middle
|
||||
hop's individual health. A dead middle hop makes the exit verdict honestly
|
||||
`dead`; localization is served by the verdict flip log.
|
||||
- **Rejected: auto-reroute rules when a group dies.** A dead group blocks
|
||||
fail-closed — visible and alertable. Silent rerouting would hide the outage
|
||||
and change routing semantics behind the user's back.
|
||||
Consequence: the probe budget is bounded by the config, not the subscription;
|
||||
cold start converges in seconds (immediate first pass after apply); wanting
|
||||
numbers for an unused group has one honest answer — reference it from a rule.
|
||||
|
||||
## D20 — Probe URL / Interval are global-only; per-group overrides deleted
|
||||
Decided 2026-07-24 (proxy-health plan §5.D). Groups carried optional
|
||||
`ProbeURL`/`ProbeInterval` overrides. That bred a documented ambiguity — one
|
||||
node shared by two groups with different URLs yields incomparable delays and
|
||||
needs "whose URL wins" dedup machinery (the `(dial, URL)` plan key) — and it
|
||||
breaks the D18 board: a verdict is a *(record, TTL)* pair with TTL derived from
|
||||
the probe interval, so per-group intervals would make the same record mean
|
||||
different things to different readers. Xray's observatory has exactly one
|
||||
global `probeURL`/`probeInterval`; that is the model we mapped onto (§3).
|
||||
|
||||
**Decision: only `Globals.ProbeURL`/`Globals.ProbeInterval`.** They drive the
|
||||
native group checker, the observatory and the manual exit test alike (failover
|
||||
keeps its 30 s default interval). Probe-plan dedup collapses to the dial path.
|
||||
Migration is the standard dead-option drainage: old UCI configs carrying
|
||||
`probe_url`/`probe_interval` on a group parse silently and the options vanish
|
||||
on the next render.
|
||||
- **Rejected: keep per-group overrides.** Incomparable measurements across
|
||||
groups, undefined semantics for shared members, and a per-group TTL that
|
||||
fractures the single-board verdict.
|
||||
- **Deferred: per-tier probe cadence** (rule-critical tags more often). If ever
|
||||
needed it is a field on the observatory's `ProbeJob` — a scheduling knob,
|
||||
not a return of per-group *configuration*.
|
||||
Consequence: all delay numbers are comparable (least ping ranks apples against
|
||||
apples), and group settings lose two footgun fields while Settings keeps the
|
||||
two that actually govern every check.
|
||||
|
||||
## D21 — A rule's destination is a rule-set, and nothing else
|
||||
Decided 2026-07-25 (product owner). `config rule` carried THREE ways to say
|
||||
where traffic is going: `dst_domain` (an inline domain list), `dst_ip` (an inline
|
||||
CIDR list) and `dst_ruleset` (a reference to a `config ruleset`). Three
|
||||
mechanisms meant three sets of semantics to learn and keep straight, and the
|
||||
inline ones were the worse half of the trade: they are re-parsed per rule instead
|
||||
of being compiled once into a `.srs`, they cannot be shared between rules, and
|
||||
their matcher vocabulary had drifted from the rule-set one in a way nobody could
|
||||
see (below).
|
||||
|
||||
**Decision: `dst_domain` and `dst_ip` are removed (schema v2). `dst_ruleset` is
|
||||
the only destination matcher.** `Src`, `dst_port` and `proto` are untouched —
|
||||
they are not lists of destinations and have no rule-set form.
|
||||
|
||||
- **Rejected: keep the inline lists as a shorthand.** "One obvious way" is the
|
||||
whole point; a shorthand that quietly means something different from the long
|
||||
form (see the bare-entry trap) is worse than no shorthand.
|
||||
- **Rejected: promote inline lists to rule-sets lazily at generate time.** The
|
||||
config on disk would then not say what the router does, and the panel would
|
||||
have to render a list the user cannot find or edit.
|
||||
|
||||
### The bare-entry trap, and how the migration handles it
|
||||
The two contexts already disagreed about exactly one spelling, silently:
|
||||
|
||||
| entry | in a rule (`dst_domain`) | in a rule-set (`entry`) | migrated to |
|
||||
|--------------------|--------------------------|-------------------------|--------------|
|
||||
| `example.com` | **exact host** | **host + subdomains** | `full:example.com` |
|
||||
| `full:example.com` | exact host | exact host | unchanged |
|
||||
| `suffix:example.com` / `.example.com` | host + subdomains | host + subdomains | unchanged |
|
||||
| `keyword:ads` | substring | substring | unchanged |
|
||||
| `regexp:^ads\.` | pattern | pattern *(added here)* | unchanged |
|
||||
| `geosite:x` / `geoip:x` | inert (engine field removed) | inert (unknown prefix) | unchanged |
|
||||
|
||||
`shaterd migrate` (schema v1→v2, `shater/model/migrate.go`) creates one inline
|
||||
`config ruleset` per rule that still carries a legacy list — `rule-<rule name>`
|
||||
for domains, `rule-<rule name>-ip` for addresses — moves the entries across with
|
||||
the conversion above, appends the new name to `dst_ruleset`, and deletes the old
|
||||
option. It is idempotent, it resumes an interrupted run, and it never overwrites
|
||||
a hand-written rule-set that already owns the generated name (it picks
|
||||
`rule-<name>-2`). `regexp:` support was added to inline rule-sets in the same
|
||||
change precisely so the move can be lossless.
|
||||
|
||||
`geosite:`/`geoip:` entries are copied VERBATIM rather than promoted to a
|
||||
`source=geosite` rule-set: those matchers have been inert since the engine
|
||||
dropped the route-rule geosite/geoip fields, and turning a dead matcher live
|
||||
during an upgrade would be a behaviour change, not a migration. The text is kept
|
||||
so the operator can see it and convert it deliberately.
|
||||
|
||||
**One deliberate semantic change, called out:** a rule that used BOTH lists
|
||||
matched them with AND (an engine route rule ANDs its matcher fields), which is
|
||||
almost never what "these sites and these networks" meant. The two generated
|
||||
rule-sets are ORed, because `rule_set: [a, b]` matches when either matches. Such
|
||||
a rule matches more after the migration than before; it affects only configs that
|
||||
used both fields at once.
|
||||
|
||||
That AND→OR change is about the ENGINE's TCP/UDP path, and it deliberately does
|
||||
**not** extend to the untunnelable-protocol plane (`shater/apply/untunnelable.go`,
|
||||
the ping / IPTV / VPN-passthrough policy in nftables). There, a v1
|
||||
`dst_domain + dst_ip` rule could never claim a packet that carries no domain, so
|
||||
the plan skipped it; reading the migrated form as OR would have made the address
|
||||
half suddenly decisive, and with `target=direct` that means an upgrade quietly
|
||||
sending previously-tunnelled ICMP out with the client's real source address. A
|
||||
rule whose rule-sets are known to match by NAME is therefore still skipped by that
|
||||
plan, and the skip is reported ("a routing rule matches by name … as well as by
|
||||
address"). Split the rule in two if you want the addresses decided there.
|
||||
|
||||
### The vocabulary is about ENTRIES YOU TYPE, not about every list body
|
||||
The table above is the vocabulary of an **inline** rule-set's `entry` values (and
|
||||
of the DNS-filter/device lists, which share the classifier). The other two rule-set
|
||||
sources are not other spellings of it:
|
||||
|
||||
| source | what it is | vocabulary |
|
||||
|------------------------------|----------------------------------|------------|
|
||||
| `inline` | entries you type | the table above |
|
||||
| `url` → `.srs` / `.json` | a compiled rule-set, engine-owned | the engine's, not ours |
|
||||
| `url` → anything else | a hosts / one-domain-per-line / AdBlock TEXT FILE | **none** — every line is a domain plus its subdomains |
|
||||
| `file` | a local `.srs` / `.json` | the engine's, not ours |
|
||||
|
||||
**Rejected: run text lists through the entry classifier too.** A published
|
||||
AdGuard/OISD list is full of colon-bearing tokens that are ordinary filter syntax
|
||||
(`##…:has(…)`, `$domain=`, absolute URLs); classifying them would either mis-import
|
||||
them or bury the operator under hundreds of "unrecognised prefix" warnings per
|
||||
list. The formats also disagree structurally — a hosts line carries several names,
|
||||
so the text parser works per token, while an entry is a whole line. And `regexp:`
|
||||
arriving from a third-party URL is a pattern compiled into the router's matcher and
|
||||
evaluated per query, which is a very different proposition from one the operator
|
||||
typed.
|
||||
|
||||
So the difference stands and is paid for in diagnostics instead: a text list
|
||||
containing `full:` / `suffix:` / `keyword:` / `regexp:` is reported per list, on
|
||||
every generate, naming the entries and pointing at `source=inline` where they work
|
||||
(`warnListEntryVocabulary`, `shater/generate/ruleset.go`). The check tests only
|
||||
those four markers, never the general `word:` shape, so it fires on a human's
|
||||
mistake and stays quiet on published filter syntax.
|
||||
|
||||
Consequence: one destination mechanism, one vocabulary, one place a list is
|
||||
edited; every list is compiled once and reused. The panel's rule editor drops its
|
||||
Domain(s) and IP/CIDR(s) fields; its destination control is a checkbox list of
|
||||
the rulesets that already exist, and nothing more. Creating and filling a list
|
||||
stays in the Rulesets panel — **rejected: a "create a list from here" shortcut in
|
||||
the rule editor**, because a second place to author a list is a second place for
|
||||
its semantics and its duplicate-name rules to drift, and the whole point of this
|
||||
decision was to stop having two.
|
||||
|
||||
## D22 — One packaging lane: apk. The opkg/`.ipk` lane is deleted, not disabled
|
||||
Decided 2026-07-25 (product owner). CI built and published TWO signed feeds from
|
||||
every run: opkg/usign (`.ipk` + `Packages.gz`, OpenWrt 24.10) and apk/EC (`.apk` +
|
||||
`packages.adb`, OpenWrt/ImmortalWrt 25.12). The opkg half served nobody. Checked
|
||||
on the actual hardware, not inferred:
|
||||
|
||||
| Device | Firmware | pkg arch | package manager |
|
||||
|---|---|---|---|
|
||||
| `mini_router` (BPi-R3 Mini) | ImmortalWrt 25.12.1 | `aarch64_cortex-a53` | apk-tools 3.0.5 |
|
||||
| `main_router` (BPi-R4) | OpenWrt 25.12.0 | `aarch64_cortex-a53` | apk-tools 3.0.5 — **no `opkg` binary on the system at all** |
|
||||
|
||||
**Decision: delete the opkg lane outright.** Removed: the `build` + `release`
|
||||
jobs from `.gitea/workflows/release.yml`; `ci/build-feed.sh`, `ci/sdk-build.sh`,
|
||||
`ci/make-index.sh`, `ci/install-usign.sh`; and the trust anchor
|
||||
`dist/shater-feed.pub`. The Gitea secret `KEY_BUILD` is now referenced by
|
||||
nothing and can be deleted from the repo settings. `ci/version.sh`,
|
||||
`ci/gitea-release.sh` and `ci/fetch-sdk.sh` are shared or apk-only and stay.
|
||||
|
||||
- **Rejected: keep the lane but stop triggering it** (comment it out / gate it on
|
||||
a dispatch input). Dead code in CI is worse than no code: it keeps a second SDK
|
||||
matrix, a second signing key and a second feed layout alive in everyone's head
|
||||
and in every future edit, and it silently rots because nothing runs it. The
|
||||
24.10 SDK images it pins are themselves a frozen dependency.
|
||||
- **Rejected: keep `dist/shater-feed.pub` as a historical artifact.** A committed
|
||||
trust anchor is an instruction — it invites someone to follow the old install
|
||||
path for a feed that is no longer produced. Nothing is lost by removing it:
|
||||
git history still holds the file, the SECRET half is untouched in `KEY_BUILD`,
|
||||
and a usign secret key blob contains its own public half, so the identity can
|
||||
be reconstructed if a 24.10 device ever has to be served again. Deleting the
|
||||
file is reversible; a stale trust anchor pointing at an unmaintained feed is
|
||||
the thing that quietly misleads.
|
||||
- **Not done: revoking or rotating the usign key.** There is no incident. It is
|
||||
retired, not burned (D7).
|
||||
|
||||
Consequence: one SDK, one key, one feed layout, one set of install instructions.
|
||||
It also makes the rolling release `apk-latest-<arch>` the *only* install path
|
||||
that does not require hand-editing a file per release — which is why the same
|
||||
change fixed it: publishing was an either/or (`apk-latest-<arch>` on dispatch,
|
||||
ELSE `apk-vX.Y.Z-<arch>` on a tag), so once releases moved to tag pushes the
|
||||
rolling pointer stopped being written and froze at `0.2.0` while v0.2.9/v0.2.10
|
||||
shipped — routers on the rolling URL got a successful, silent `apk update` with
|
||||
nothing new. `release-apk` now writes the rolling pointer on every run and
|
||||
asserts, by reading the published release back over the Gitea API, that it holds
|
||||
our three tag-versioned packages at exactly the version just built and no asset
|
||||
at any other version.
|
||||
|
||||
|
||||
## D23 — The router tag set is a checked contract, not a string literal
|
||||
`with_gvisor` was trimmed from the router set on 2026-07-23 (D9) as "unreachable
|
||||
code: we never emit a tun inbound". True about tun — and irrelevant, because
|
||||
gVisor is also the netstack of the **WireGuard endpoint**, which shater emits and
|
||||
FEATURES.md declares [MVP] (AmneziaWG is called *"a driving requirement"*). Every
|
||||
binary shipped between then and 2026-07-25 answered a configured WireGuard node
|
||||
with:
|
||||
|
||||
```
|
||||
create instance: initialize endpoint[0]: create WireGuard device:
|
||||
gVisor is not included in this build, rebuild with -tags with_gvisor
|
||||
```
|
||||
|
||||
`transport/wireguard/device_stack_stub.go` (`//go:build !with_gvisor`) returns
|
||||
`tun.ErrGVisorNotIncluded` from **both** device constructors, so
|
||||
`system_interface: true` is not an escape hatch either: WireGuard was 100% dead
|
||||
in the shipped artifact while the panel offered it, the parser accepted `wg://`,
|
||||
`awg://` and wg-quick `.conf` imports, and the owner had 7 WireGuard sections in
|
||||
UCI on a production router.
|
||||
|
||||
- **Decision:** `with_gvisor` is part of the router tag set and stays there for
|
||||
as long as we ship WireGuard. It costs **~2.8 MB raw / ~0.65 MB UPX per arch**
|
||||
(measured 2026-07-25, both arches; `/overlay` on the production router is
|
||||
6.9 GB with 205 MB used). A tag whose absence turns a declared feature into a
|
||||
runtime error is not "dead weight" — it is the feature.
|
||||
|
||||
### Why the bug was invisible, and what now makes it visible
|
||||
The defect was not a typo in a tag list. It was that **nothing connected the tag
|
||||
list to the feature list**, and the shipped tag combination was the one build
|
||||
configuration nothing exercised: the whole test suite compiles with the FULL
|
||||
upstream set (`with_gvisor` included), so `TestAmneziaWGEndpoint` passed happily
|
||||
while the artifact it was supposed to vouch for could not create a WireGuard
|
||||
device. Tests proved the code was right; they never proved the *build* was.
|
||||
|
||||
Three pieces now hold it together:
|
||||
|
||||
1. **One definition of the set** — `scripts/router-tags.sh` (`SHATER_ROUTER_TAGS`
|
||||
+ `SHATER_ROUTER_LDFLAGS`), sourced by `scripts/build-shaterd.sh` and by the
|
||||
checker. The tag list used to live as a literal inside the build script, i.e.
|
||||
in a file no test reads. A second copy is a second truth.
|
||||
2. **A declared-feature table** — `shater/buildtags`: every tag-gated capability
|
||||
we promise, with the exact tags it needs *to run* and why (the code anchor).
|
||||
`TestRouterTagSetCoversDeclaredFeatures` parses the shell file and fails if a
|
||||
declared feature lost a tag. It needs no build tags, no Linux, no network and
|
||||
no privileges, so it runs in every plain `go test ./...` — including on the
|
||||
Windows dev host, where nothing else can see the shipped configuration.
|
||||
3. **A construction test under the shipped tags** —
|
||||
`shater/generate.TestShippedTagSetConstructsDeclaredProtocols` drives one node
|
||||
of every declared protocol (ss/vmess/trojan/vless ws-grpc-httpupgrade-quic-
|
||||
xhttp/REALITY/uTLS-fp/hysteria2/tuic/**wg**/**awg**) through `box.New`+`Start`.
|
||||
`scripts/check-router-tags.sh` runs it **with `SHATER_ROUTER_TAGS`**, and CI
|
||||
runs that script (`.gitea/workflows/release.yml`) *before* the artifact is
|
||||
built. In a router-tag-set run nothing may be skipped: a protocol that is not
|
||||
compiled in fails the run instead of quietly disappearing from it.
|
||||
|
||||
(2) catches a trim the moment it is made and names the feature it kills; (3)
|
||||
catches what a list comparison cannot — a tag that is present but insufficient.
|
||||
Neither is a substitute for the other. A new protocol in `shater/parse` +
|
||||
`shater/generate` means a new row in `buildtags.Features` and a new probe case;
|
||||
`TestEveryTagGatedFeatureIsProbed` fails until both exist.
|
||||
|
||||
- **Rejected: "just add the tag".** The one-line fix restores WireGuard and
|
||||
leaves the mechanism that hid it fully intact — the next size-driven trim is
|
||||
equally invisible. The tag is the smallest part of this decision.
|
||||
- **Rejected: run the WHOLE test suite with the router tag set in CI.** It is the
|
||||
obvious move and it does not work: parts of the suite legitimately depend on
|
||||
upstream-only tags, and the run costs a second full compile of a 25 MB binary's
|
||||
worth of packages on every release. A focused, unprivileged construction test
|
||||
buys the same evidence for ~10 s and, unlike a full run, can be *required* to
|
||||
skip nothing.
|
||||
- **Rejected: assert the tag set against upstream's `DEFAULT_BUILD_TAGS`.** That
|
||||
makes any trim a failure, which turns the check into noise and re-litigates D9
|
||||
on every upstream rebase. The contract is with our own feature list, not with
|
||||
upstream's.
|
||||
- **Not done: dropping `with_lx_command`.** It is inert for `shaterd` — nothing
|
||||
under `shater/` imports `sing-box/daemon` or `experimental/libbox`, and
|
||||
`go list -deps ./shater/cmd/shaterd` links neither, so it costs zero bytes. It
|
||||
stays only so the router set remains a subset of the lx desktop set. Noted
|
||||
because "a tag that buys nothing" is the mirror image of this bug and should be
|
||||
removed deliberately, not silently.
|
||||
|
||||
## D24 — DNS interception is the DEFAULT (`dns_intercept=1`), not an opt-in
|
||||
Decided 2026-07-26. `Globals.DNSIntercept` shipped as opt-in (`default false`, and
|
||||
absent from both `DefaultGlobals` and the shipped `/etc/config/shater`). The result
|
||||
was an **inverted** posture, which is the reason this is a decision and not a
|
||||
preference:
|
||||
|
||||
- a client with **standard** settings — DNS = the router's address, exactly what
|
||||
DHCP hands out — sent its queries to the router. The nft `:53` divert was behind
|
||||
the flag (`netplane/nft.go`), and the rule right after it is an unconditional
|
||||
`fib daddr type local accept`, so the query was delivered locally to dnsmasq and
|
||||
forwarded to the ISP **in the clear**: no blocklists, no per-device DNS rules,
|
||||
no Block-DoH, no resolver detour, nothing;
|
||||
- a client that hard-coded `8.8.8.8` "to bypass the router" was addressing a
|
||||
non-local IP and **was** caught by the ordinary tproxy catch-all.
|
||||
|
||||
The obedient client leaked; the evader did not. Meanwhile `FEATURES.md`, `README.md`
|
||||
and D14 all promised "no DNS leaks" and "dnsmasq never sees LAN queries" — true only
|
||||
for the traffic pattern the default did not cover. `dns_intercept` appeared nowhere
|
||||
in `docs-shater/` at all.
|
||||
|
||||
**Decision: `DNSIntercept` is seeded ON in `model.DefaultGlobals`, and the shipped
|
||||
`/etc/config/shater` carries an explicit `option dns_intercept '1'`.** Nothing about
|
||||
the interception MECHANISM changed — only which side of the switch is the default.
|
||||
|
||||
**`.lan` and the private PTR zones keep working, and that is a pre-existing part of
|
||||
the mechanism, not something bolted on for this flip.** `generate/dns.go` adds a
|
||||
synthetic DNS server (`shater-local-dns`, plain UDP to `127.0.0.1:53`, detour
|
||||
`direct`, so the daemon's own loop-mark keeps it out of the divert) and PREPENDS a
|
||||
`domain_suffix` rule for `lan` + the RFC6303 private reverse zones, ahead of every
|
||||
device/filter rule. Two honest limitations: it hardcodes `lan` (a router whose
|
||||
dnsmasq domain was changed needs a `config dns_rule` for the new suffix), and it
|
||||
only exists when the model has at least one `config resolver` — with none, buildDNS
|
||||
emits no DNS plane at all and the engine falls back to its built-in `local`
|
||||
transport, which reads `/etc/resolv.conf` (127.0.0.1 → dnsmasq), so local names
|
||||
still resolve but nothing is filtered.
|
||||
|
||||
**A dead engine does NOT black out the LAN's DNS.** This was the first thing checked,
|
||||
because "intercept everything" invites the reading "engine down = no DNS anywhere",
|
||||
and that is not what happens:
|
||||
- the fail-closed **holding plane** (D17, `RenderHoldNft`) hooks `forward` ONLY.
|
||||
A query addressed to the router is INPUT-hook traffic, so dnsmasq answers it as
|
||||
it always did — unfiltered and plaintext to the ISP. Deliberate: blocking it
|
||||
would also cut the daemon's own name resolution and with it any chance of
|
||||
self-recovery;
|
||||
- with the FULL plane loaded and the engine's tproxy socket gone, the `tproxy`
|
||||
statement returns `NFT_BREAK`, which aborts its own rule; the packet continues
|
||||
down the chain into the same `fib daddr type local accept` and reaches dnsmasq.
|
||||
|
||||
So the failure mode is a DNS **fail-open** (working, unfiltered) while client
|
||||
TRAFFIC stays fail-closed — and a query aimed at an EXTERNAL resolver is dropped
|
||||
with the rest of the forwarded traffic. Operators must know this: "the tunnel is
|
||||
down" does not mean "DNS is private".
|
||||
|
||||
**Existing installs.** `/etc/config/shater` is a conffile
|
||||
(`openwrt/shater-core/Makefile`), so an upgrade never replaces it:
|
||||
- a config that never mentioned the option (all of them, before this change) now
|
||||
parses over the ON seed and **starts intercepting on the next apply**. That is the
|
||||
intended behaviour change, and the only one this decision makes;
|
||||
- an explicit `option dns_intercept '0'` keeps winning. It survives the
|
||||
`WriteUCI→ReadUCI` round-trip because `render.go` emits booleans ALWAYS —
|
||||
the trap a default-true bool has and a default-false one does not: a value
|
||||
omitted at false would come back as the seed and silently re-enable itself.
|
||||
`shater/model/dnsintercept_test.go` pins both directions, plus the shipped file.
|
||||
|
||||
**Not done: silencing the "no resolvers configured" warning by shipping a resolver.**
|
||||
With interception on and no `config resolver`, generate warns — and it is right to:
|
||||
every client query now lands in an engine that has no resolver plane, so it is
|
||||
answered by the system resolver (dnsmasq → the ISP, in the clear) with filtering and
|
||||
anti-leak inert. Shipping a `type local` resolver would make the warning disappear
|
||||
while changing nothing about where the queries go: the panel would show a configured
|
||||
resolver and the operator would believe DNS was handled. That is the inverted lie
|
||||
this project keeps deleting. The warning stays; what it needs is the accurate
|
||||
wording (it currently claims `.lan` breaks, which the fallback above disproves), not
|
||||
a workaround. Note also that a fresh install ships INERT (`enabled '0'`) and
|
||||
`Reconcile` tears down instead of generating, so the warning cannot appear before the
|
||||
operator has enabled the stack — at which point it describes their live config.
|
||||
|
||||
**OPEN, and it gates shipping this default: the synthetic local server changes how
|
||||
proxy-endpoint DOMAINS are resolved.** Found while landing D24, reproduced on Linux
|
||||
with one resolver and a node addressed by a hostname:
|
||||
|
||||
- `common/dialer/dialer.go` resolves a domain server address through
|
||||
`route.default_domain_resolver`; when that is unset it uses
|
||||
`dnsTransport.Default()` — the engine's built-in `local` transport, i.e. a
|
||||
bootstrap-DIRECT lookup — but **only while fewer than two DNS transports exist**.
|
||||
With two or more and no default, it reports the `missing-domain-resolver`
|
||||
deprecation and leaves the query transport nil, so `dns.Router.Lookup` falls back
|
||||
to `lookupWithRules`: the CLIENT DNS plane.
|
||||
- `dns_intercept` adds `shater-local-dns`, which takes a single-resolver config from
|
||||
one transport to two. So a config whose only resolver is DoH-through-the-tunnel —
|
||||
the recommended anti-leak setup — would start resolving its own node's hostname
|
||||
through that same tunnel: a bootstrap loop where there was none.
|
||||
- Evidence: the same model emits no deprecation notice with `dns_intercept=0` and
|
||||
two `missing-domain-resolver` notices with `dns_intercept=1`;
|
||||
`generate.TestDNSFilterRemoteBlocklistHTTPClient` (Linux-only) fails on exactly
|
||||
that notice and is deliberately left failing rather than relaxed.
|
||||
|
||||
The fix belongs in `generate` (`route.go:160` already sets
|
||||
`route.default_domain_resolver` from `endpointResolver()`, which is opt-in and unset
|
||||
by default): when buildDNS emits the synthetic local server and no endpoint resolver
|
||||
is configured, `default_domain_resolver` must be pointed at a bootstrap-direct
|
||||
server, which restores exactly the pre-D24 behaviour and clears the notice. Until
|
||||
that lands, an operator can get the same result by setting `endpoint_resolver` to a
|
||||
direct resolver. Note the hazard is **not** created by D24 — any config with two
|
||||
resolvers has it today; the default merely makes it universal.
|
||||
|
||||
## D25 — L3 ingress: LAN ICMP rides a dedicated TUN through the tunnel, not a policy verdict
|
||||
Decided 2026-07-26. D17 made everything TPROXY cannot divert an explicit policy
|
||||
(`Globals.Untunnelable` = block | icmp | direct) — and its premise still holds:
|
||||
kernel TPROXY delivers a packet by handing it to a listening SOCKET, and sockets
|
||||
exist for TCP and UDP only, so an ICMP echo has nothing to be handed to. But a
|
||||
policy can only choose between losing the packet and leaking it with the
|
||||
client's real source address; neither ever puts a ping THROUGH the tunnel. This
|
||||
decision adds the data plane D17 could not have: **`globals.l3_tunnel` (opt-in,
|
||||
default off; `model.Globals.L3Tunnel`) opens a second, dedicated ingress — a TUN
|
||||
device — and LAN ICMP enters the engine as raw IP packets**, where the ordinary
|
||||
route rules pick an outbound exactly as for any flow. The policy is refined, not
|
||||
repealed: it keeps sole charge of the protocols the engine cannot ingest at all,
|
||||
and of the degraded paths (both below).
|
||||
|
||||
**The whole mechanism is one mark, one rule, one device — the TPROXY plane is
|
||||
untouched.** The nft prerouting chain stamps `L3Mark` (= fwmark_base + 0x80,
|
||||
`netplane/nft.go` `l3MarkOffset`) on LAN `ip protocol icmp` / `meta l4proto
|
||||
ipv6-icmp` ONLY, and only after every local plane was already accepted
|
||||
(fib-local, RFC1918/link-local/multicast daddr sets) and — for v6 — after a
|
||||
unicast ND/NA carve-out, because one tunnelled neighbour probe is enough to take
|
||||
the LAN's v6 plane down (`renderNft`, the L3 block). `addL3Routing`
|
||||
(`netplane/apply.go`) binds that mark to a table (= table_base + 0x08) whose
|
||||
only content is `default dev shater-l3`; del-then-add idempotent, and a failed
|
||||
rule or route is a NAMED operator warning, never an apply abort. `generate`
|
||||
emits the synthetic `l3-in` TUN inbound bound to exactly `netplane.L3Device`,
|
||||
MTU 65535 (the largest IP datagram there can be, so the KERNEL can never
|
||||
fragment on the way in — see "the device MTU is not a tunnel budget" below),
|
||||
point-to-point /30 + /126 addresses from private space,
|
||||
the v6 one only when `globals.ipv6` is on — and only next to a tproxy inbound:
|
||||
the ingress rides the same LAN divert plane, and without one the TUN would sit
|
||||
dark while the config claims ICMP is tunnelled, so it is skipped with a warning
|
||||
(`generate/inbound.go`, `appendL3TunInbound`). `shater/registry` registers the
|
||||
`tun` inbound type; that costs no new build tag and no meaningful size because
|
||||
`with_wireguard` already requires `with_gvisor` (D23, `scripts/router-tags.sh`).
|
||||
|
||||
**`auto_route: false` is load-bearing, not a default we happened to keep.**
|
||||
sing-box's auto_route rewrites the router's MAIN routing table — it would drag
|
||||
everything the router itself sends (WAN traffic, DNS, the tunnel's own underlay)
|
||||
into this TUN. The fwmark rule + dedicated table above is deliberately the ONLY
|
||||
entrance, and disabling the feature can never strand a stale default route in
|
||||
main (`generate/inbound.go`; pinned by `TestL3TunnelEmitsTunInbound`).
|
||||
|
||||
**`stack: "gvisor"` is a deliberate choice, and the tempting reason for it is
|
||||
wrong.** It is TRUE that sing-tun's system stack answers an ICMP echo LOCALLY —
|
||||
`processIPv4ICMP` rewrites Echo→EchoReply in place and swaps the addresses
|
||||
(sing-tun `stack_system.go:648`; the v6 twin sits right under it). It is FALSE
|
||||
that this makes the system stack unusable here: `dispatchIPv4`
|
||||
(`stack_system.go:355-372`) hands the packet to the SAME `ForwardDispatcher`
|
||||
first and only falls through to that forger for packets addressed to the TUN
|
||||
itself, exactly as the gVisor filter does (`stack_gvisor_filter.go:52-113`).
|
||||
Both stacks would forward. gvisor is chosen because it is already linked —
|
||||
`with_wireguard` requires `with_gvisor` (D23), so it costs no tag and no new
|
||||
code path — and because it is the combination the integration test actually
|
||||
exercises. Do not re-derive this as "the system stack fakes ping": it fakes ping
|
||||
only where the dispatcher declined the packet.
|
||||
|
||||
**The ceiling is ICMP echo, and it is upstream's dispatcher — NOT the netstack.**
|
||||
This distinction matters because the netstack answer is the intuitive one and it
|
||||
is wrong. On the forward path a WireGuard/AWG endpoint never consults gVisor at
|
||||
all: `Endpoint.WritePackets` (`transport/wireguard/port.go:21-58`) reads the IP
|
||||
version and the destination address and hands the raw bytes to
|
||||
`wgDevice.InputPackets` — the protocol byte is never examined — and
|
||||
`returnDeviceWrapper.Write` (`:127-157`) offers every decrypted packet to
|
||||
`returnPath.ReturnPackets` before the stack sees it. WireGuard would carry ESP
|
||||
today if anything handed it one. What refuses is `ForwardDispatcher`: its parser
|
||||
sets `hasFlow` for TCP, UDP and ICMP echo alone (`flow_parse.go`,
|
||||
`parseTransport`, the echo identifier serving as the pseudo-port), and
|
||||
`createFlow` NATs through a port-shaped selector (`flow_dispatch.go:325`,
|
||||
`allocateSelector`) that ESP, AH and GRE do not have. So ESP/AH/GRE/IGMP/SCTP
|
||||
cannot enter the engine in ANY configuration and REMAIN on the D17 policy —
|
||||
or on the kernel egress of D26, which sidesteps the dispatcher entirely. The nft
|
||||
plane encodes the same boundary on purpose: it marks `icmp`/`ipv6-icmp` only,
|
||||
never `l4proto != { tcp, udp }`, because a marked ESP packet would enter the
|
||||
device and vanish — a black hole wearing a tunnel's name — instead of receiving
|
||||
the policy's honest verdict (`netplane/nft.go`, the prerouting L3 comment).
|
||||
|
||||
**What works and what does not, read off the upstream source.** ping v4/v6 —
|
||||
yes. Windows `tracert` — yes: the gVisor return path recognises
|
||||
`ICMPv4TimeExceeded` and `ICMPv4DstUnreachable` alongside EchoReply and NATs
|
||||
them back to the LAN client (`stack_gvisor_icmp.go:341+`, `returnPacket`). IPv6
|
||||
traceroute — intermediate hops stay invisible: the v6 branch of the same
|
||||
function accepts EchoReply only, so just the final destination answers. Several
|
||||
LAN clients behind the one tunnel address are already solved upstream:
|
||||
`ForwardDispatcher` NATs by echo identifier and rewrites the source to the
|
||||
outbound's port address (`flow_dispatch.go:325+`, `createFlow`; `icmpFlowKey`) —
|
||||
we wrote no NAT of our own.
|
||||
|
||||
**Which outbounds can carry it.** The contract is `adapter.FlowOutbound`
|
||||
(= `Outbound` + `tun.Port` + `PreMatchFlow`, `adapter/outbound.go`). In-tree
|
||||
implementors: the WireGuard/AWG endpoint (`protocol/wireguard`), `direct`
|
||||
(`protocol/direct`), `bridge` (`protocol/bridge`), `tailscale`
|
||||
(`protocol/tailscale`). Of those, the shaterd registry can construct only
|
||||
WireGuard/AWG and direct (`shater/registry/registry.go` — bridge and tailscale
|
||||
are not registered). Every proxy protocol — vless/vmess/trojan/shadowsocks/
|
||||
hysteria2/tuic/socks/http/shadowtls — is L4-only and cannot. Recorded as a known
|
||||
gap: `masque` is L3 by nature (CONNECT-IP; it builds a userspace gVisor stack
|
||||
per tunnel, `protocol/masque/outbound.go`) but implements no `tun.Port` and is
|
||||
not in the shater registry, so today it cannot carry the ingress. Wiring it up
|
||||
is possible future work, not a promise.
|
||||
|
||||
**ICMP to an L4-only outbound is DROPPED, and that took patching upstream files
|
||||
(the `lx:l3-honest-drop` delta — see `docs-lx/lx-changelog.md`).** In the gVisor
|
||||
stack the fallthrough verdict is a forgery: `ICMPForwarder.HandlePacket` answers
|
||||
the echo ITSELF (Echo→EchoReply + address swap) whenever the flow judgment comes
|
||||
back Accept (`stack_gvisor_icmp.go:120`), and upstream maps "no flow route" to
|
||||
exactly that Accept — so a ping routed to vless would read as tunnelled while
|
||||
the packet died on the router. Two small marked hunks make the truth observable:
|
||||
`route/route.go` wraps the whole pre-match walk — the walk itself became
|
||||
`preMatch`, and the exported `PreMatch` is now a FUNNEL that rewrites
|
||||
`PreMatchContinue` and `PreMatchBypass` to `PreMatchDrop` for `N.NetworkICMP` —
|
||||
and `adapter/router.go` (`JudgeFlow`, the `!isPort` branch) returns `ActionDrop`
|
||||
for ICMP where it fell through to `ActionAccept` — the second line of defense,
|
||||
because `FlowOutbound` and `tun.Port` are distinct interfaces and a drift
|
||||
between them must not quietly re-enable the forger. TCP/UDP verdicts are
|
||||
byte-identical; `route/prematch_icmp_lx_test.go` and
|
||||
`adapter/judgeflow_icmp_lx_test.go` pin both directions. The operator-facing
|
||||
text says the same out loud (`shater/apply/warnings.go`): proxy-routed addresses
|
||||
"cannot be pinged at all — deliberately".
|
||||
|
||||
> **Why a funnel and not an override inside the walk.** The first version of
|
||||
> this delta overrode the pre-declared `continueResult` inside `preMatchFlow`
|
||||
> and claimed to cover "every exit point of the function at once". It covered
|
||||
> every exit of THAT function; the walk above it has exits of its own that never
|
||||
> reach it — the `prepareMatchMetadata` error return (which arrived later, with
|
||||
> the shared-metadata refactor, upstream `b911fb078`), the sniff bail-outs, and
|
||||
> the `default:` arm of the rule-action switch, which catches every action
|
||||
> pre-match has no arm for (`hijack-dns`, `direct`, and whatever upstream adds
|
||||
> next). Each of those returned `PreMatchContinue`, i.e. `tun.ActionAccept`,
|
||||
> i.e. the forged reply. A guard on the single return value cannot be outgrown
|
||||
> by a new exit. `PreMatchBypass` joined the drop for the same reason: sing-tun
|
||||
> implements `ActionBypass` on the nfqueue plane only — the name appears nowhere
|
||||
> in `flow_dispatch.go` or `stack_gvisor_icmp.go` — so on the TUN path it lands
|
||||
> in the same `default:` arm as Accept and forges too. There is no honest bypass
|
||||
> for a packet that is already inside the engine's TUN.
|
||||
|
||||
**The device MTU is NOT a tunnel budget, and pretending it was manufactured
|
||||
forged replies.** `l3-in` is created with MTU **65535**, not the tunnel's 1420,
|
||||
and the maximum is the whole argument. This MTU governs exactly one thing:
|
||||
whether the KERNEL splits a packet on its way INTO the device. What the engine
|
||||
then puts into the tunnel is sized separately and correctly, against the
|
||||
OUTBOUND's MTU — `ForwardDispatcher.forwardToPort` (`flow_dispatch.go:445-481`)
|
||||
measures every forwarded packet against `Port.PortMTU()` and either fragments to
|
||||
it (no DF, `fragmentIPv4Packet`) or answers a well-formed `fragmentation needed`
|
||||
quoting it (DF, `buildFragmentationNeeded`, source = the far host, so PMTU
|
||||
discovery works end to end). That machinery was always there; it was simply
|
||||
never handed a whole packet.
|
||||
|
||||
At 1420 it wasn't. Anything above 1392 bytes of payload was fragmented by the
|
||||
kernel at this device, and a fragment is the one thing sing-tun will not judge:
|
||||
`Dispatch` (`flow_dispatch.go:176-177`) returns on `parsed.fragment` BEFORE
|
||||
calling `JudgeFlow` at all. The fragments fell through to the gVisor stack —
|
||||
promiscuous and spoofing (`stack_gvisor.go:219-223`) — which reassembled them
|
||||
and handed the echo to `ICMPForwarder.HandlePacket` (`stack_gvisor_icmp.go:105+`),
|
||||
whose `installFlow` (`:233-244`) writes to the port UNMODIFIED and therefore
|
||||
demands a port address that is valid **and UNSPECIFIED**. `direct` qualifies
|
||||
(`IPv4Unspecified()`); a WireGuard/AWG endpoint reports its concrete interface
|
||||
address (`transport/wireguard/port.go:13`) and does not. So it declined, and
|
||||
`HandlePacket` fell past the switch and FORGED the reply: `SetType(EchoReply)` +
|
||||
address swap. Net effect on the operator's bench: `ping -s 1392` honest,
|
||||
`ping -s 1393` a lie told by the router — and the lie was, of course, only for
|
||||
the outbounds this feature exists for. (Upstream applies the very same
|
||||
unspecified test and answers it honestly in the cloudflared ICMP handler,
|
||||
`protocol/cloudflare/inbound.go:163-167`: it drops. Only the TUN path forges.)
|
||||
|
||||
65535 rather than "big enough": no IP datagram can exceed it, so the kernel
|
||||
CANNOT fragment at this device, for any packet, ever. Any smaller value leaves
|
||||
a band of sizes open and re-opens the class. It is also sing-box's own default
|
||||
TUN MTU on Linux. Pinned by `TestL3TunnelMTULeavesNothingForTheKernelToFragment`
|
||||
and `TestL3TunnelMTUIsNotATunnelBudget` (`generate/l3mtu_test.go`), and — the
|
||||
assertion that matters — by the integration test reading the MTU back off the
|
||||
real kernel device, since a kernel that clamped it would restore the forgery
|
||||
without changing a generated byte.
|
||||
|
||||
Memory was MEASURED, not reasoned about: three paired runs of
|
||||
`TestIntegrationL3TunInboundStarts` under `-test.memprofilerate=1` (exact
|
||||
accounting, not sampled) allocate 5.41 / 5.48 / 5.47 MB at 65535 against
|
||||
5.76 / 5.46 / 5.70 MB at 1420, and a `-diff_base` profile attributes every
|
||||
difference to netlink interface enumeration. Nothing in the read path scales
|
||||
with the MTU: gVisor reads through `fdbased.BufConfig`, which sing-tun's `init`
|
||||
pins to a single 65535-byte view regardless of MTU, and `fdbased` keeps `mtu`
|
||||
only to return it from `MTU()`. Two adjacent facts, recorded because both are
|
||||
easy to derive wrongly: (a) `protocol/tun` computes
|
||||
`enableGSO = stack == gvisor && mtu < 49152`, so this MTU turns GSO off there —
|
||||
and then `StartStateStart` turns it back ON unconditionally because an
|
||||
`adapter.FlowOutbound` exists in the config, so the ~1.98 MB of TCP/UDP GRO
|
||||
scaffolding is present at BOTH MTUs and is priced by the flow-capable outbound,
|
||||
not by this number; (b) the `mtu_fix` on the `shater_l3` fw4 zone is now inert —
|
||||
only ICMP is ever marked into the device — and its uci-defaults comment still
|
||||
says "the tunnel MTU is 1420".
|
||||
|
||||
**What is still NOT covered, said plainly.**
|
||||
|
||||
1. **A big ping does not start WORKING — it starts FAILING HONESTLY.** Upstream's
|
||||
ICMP NAT is unfragmented-only in BOTH directions: `classifyReturn`
|
||||
(`flow_dispatch.go:703-710`) returns `returnPass` on `parsed.fragment` exactly
|
||||
as the forward path does. So a non-DF `ping -s 2000` now genuinely leaves the
|
||||
router (fragmented to the tunnel MTU by `forwardToPort`), the far host really
|
||||
answers, and the reply — fragmented by the peer to fit the tunnel — is not
|
||||
NAT'd back to the LAN client. The operator sees a timeout. That is the
|
||||
feature's promise ("travels or fails honestly"), not a capability claim.
|
||||
Carrying oversized ICMP end to end would need reassembly upstream does not
|
||||
have; it is not planned.
|
||||
2. **A client that puts fragments on the wire ITSELF.** The device MTU cannot
|
||||
un-fragment what already arrived fragmented, so such packets still reach the
|
||||
gVisor stack, still get reassembled there, and still receive a forged reply
|
||||
when the outbound is WireGuard/AWG. This is the residue the planned
|
||||
`ip frag-off & 0x3fff != 0` prerouting carve-out (`netplane/nft.go`) is for.
|
||||
**Whoever writes that rule must first check whether it can ever match:** fw4's
|
||||
ruleset uses conntrack, conntrack pulls in `nf_defrag_ipv4`/`nf_defrag_ipv6`,
|
||||
and defrag REASSEMBLES in PREROUTING before our marking rules run. Where
|
||||
defrag is active the case does not arise (the MTU covers it) and the rule is
|
||||
dead; where it is not, the rule is the only cover. Verify on the bench with
|
||||
`nft list ruleset | grep -c ct` and a fragment counter, do not assume.
|
||||
3. **The DF path changed hands and is untested on hardware.** It used to be the
|
||||
kernel that answered `fragmentation needed` (from the router's LAN address,
|
||||
MTU 1420); it is now the engine (from the far host's address, quoting
|
||||
`Port.PortMTU()`). Both are correct PMTUD; only the first has ever run on a
|
||||
real router.
|
||||
**fw4 has to be told about the device, and `list device` is the only spelling
|
||||
that works.** nftables runs EVERY table on every packet and a drop in any one of
|
||||
them wins — an accept in `inet shater` cannot override fw4, and fw4 WILL reject
|
||||
this forward: netifd never learns about a device the daemon creates at runtime,
|
||||
so `shater-l3` belongs to no zone and falls into fw4's zone-less defaults. Hence
|
||||
a real fw4 zone `shater_l3` + a lan→shater_l3 forwarding, seeded idempotently
|
||||
(NAMED sections) and unconditionally in uci-defaults
|
||||
(`openwrt/shater-core/files/etc/uci-defaults/30_shater-core`, `seed_l3_zone`),
|
||||
with `mtu_fix` set. That `mtu_fix` is now inert and should be read as such: it
|
||||
clamps forwarded TCP MSS to the route MTU, the device MTU is 65535, and nothing
|
||||
but ICMP is ever marked into this device — the uci-defaults comment still says
|
||||
"the tunnel MTU is 1420" and is stale. The device is attached
|
||||
via `list device`, deliberately NOT `list network`: fw4 resolves a zone's
|
||||
networks through netifd, which yields an EMPTY device set for a runtime-created
|
||||
TUN (a proto-none stub would have to be brought UP to contribute an l3_device,
|
||||
and nothing ever brings it up), while `list device` compiles to a plain
|
||||
iifname/oifname string match — valid before the TUN exists, matching from the
|
||||
moment shaterd creates it. `kmod-tun` joined DEPENDS so a slimmed image cannot
|
||||
lose `/dev/net/tun` (`openwrt/shater-core/Makefile`). Our own forward chain
|
||||
accepts both TUN legs ahead of the fail-closed drops — accepts that speak for
|
||||
OUR table only (`netplane/nft.go`, forward chain step 4).
|
||||
|
||||
**What the policy still owns, and the one combination that now warns.** With the
|
||||
ingress on, the mark is stamped in prerouting and the ROUTING decision carries
|
||||
echo into the TUN before the forward chain — where the policy's verdicts live —
|
||||
is ever consulted; that holds under every `untunnelable` value. The policy
|
||||
therefore governs exactly two things: the never-markable protocols above, and
|
||||
the fallback when the L3 rule/route did not come up (engine down, partial apply)
|
||||
— `block` turns that failure into an honest loss, `direct` into a silent leak
|
||||
with the real address. That is why `l3_tunnel` + `untunnelable=direct` draws a
|
||||
validation warning naming the safe choice (`model/validate.go`), why every
|
||||
rule/route failure surfaces as a named panel warning rather than an abort
|
||||
(`addL3Routing`), and why the D17 HOLDING plane never marks: the TUN is created
|
||||
BY the engine, and the holding plane exists precisely because the engine is not
|
||||
running — marking would dead-end ping in a device that does not exist
|
||||
(`netplane/nft.go`, hold comment).
|
||||
|
||||
- **Rejected: `auto_route` / letting the engine own the routing.** It rewrites
|
||||
the main table and intercepts the router's own WAN/DNS/underlay traffic; the
|
||||
blast radius of a toggle meant for LAN ping would be the whole router.
|
||||
- **Rejected: marking all `l4proto != { tcp, udp }` into the TUN.** ESP/AH/GRE/
|
||||
IGMP/SCTP cannot be parsed into flows upstream; they would vanish inside the
|
||||
device. A drop with a name (the policy's) beats a silent black hole.
|
||||
- **Rejected: keeping upstream's accept-and-forge for unroutable ICMP.** A ping
|
||||
that "works" without leaving the router is the inverted lie this project keeps
|
||||
deleting (D17's fiction purge, D23's dead WireGuard, D24's obedient-client
|
||||
leak).
|
||||
|
||||
**Proven, and not proven, said plainly.** The cold start is PROVEN, not assumed:
|
||||
`TestIntegrationL3TunInboundStarts`
|
||||
(`shater/generate/l3_integration_linux_test.go`, run as root with NET_ADMIN and
|
||||
`/dev/net/tun`, PASS) drives an `l3_tunnel=1` config through the SLIM registry
|
||||
(`registry.Context`, not upstream's `include.Context`) under the shipped router
|
||||
tag set: `box.New` + `Start` accept it, the kernel really ends up with the
|
||||
`shater-l3` device at the contract MTU 65535 — the assertion the value exists
|
||||
for, since a kernel that clamped it would silently restore the forged-reply
|
||||
band — and Close removes it; precisely
|
||||
the "built with X, verified with Y" gap class D23 exists for (a lost
|
||||
`tun.RegisterInbound` or a trimmed `with_gvisor` changes no generated byte and
|
||||
would otherwise surface only on the operator's router). Each layer contract is
|
||||
pinned besides (`generate` `TestL3Tunnel*`, `netplane` `TestL3Ingress*`,
|
||||
`route/prematch_icmp_lx_test.go`). Exactly two things remain UNVERIFIED:
|
||||
(a) the end-to-end path on live hardware — LAN client → prerouting mark →
|
||||
ip rule → TUN → WireGuard peer → reply back to the client — has not been
|
||||
exercised on a real router; (b) the steady-state memory cost of the second
|
||||
gVisor netstack (the `l3-in` TUN beside the WireGuard endpoint's own) is
|
||||
unmeasured on the target hardware. An indicative figure exists and is only
|
||||
that: on x86_64 in a container, idle and carrying no flows, peak RSS of a
|
||||
process that brought the same engine up went from ~26.0-26.8 MB without
|
||||
`l3_tunnel` to ~28.3-28.7 MB with it over three paired runs — about +2.2 MB.
|
||||
That was measured on a throwaway harness, not on aarch64, not under load, and
|
||||
with an empty ICMP NAT table, so it bounds nothing on the router. Neither
|
||||
item is folded into any claim above.
|
||||
|
||||
Consequence: a ping from the LAN either genuinely travels through the tunnel
|
||||
(WireGuard/AWG, direct) or fails honestly, at every size the router itself can
|
||||
put into the device — and a router that never opts in renders the pre-feature
|
||||
plane byte-for-byte (`TestL3IngressOptIn` pins the off-state render). Read
|
||||
"fails honestly" strictly: above the tunnel MTU a non-DF ping now leaves the
|
||||
router for real and then times out, because upstream's ICMP NAT does not carry
|
||||
fragments back either. The one qualifier left is item 2 above — a client that
|
||||
puts fragments on the wire ITSELF, on a router where conntrack defrag is not
|
||||
reassembling them first. This paragraph has been overclaimed twice already;
|
||||
extend it only against a bench result, never against a reading.
|
||||
|
||||
## D26 — What the engine cannot carry, the kernel carries: `untunnelable_egress`
|
||||
Decided 2026-07-26. D25 ended with ESP/AH/GRE/IGMP/SCTP still owned by the D17
|
||||
policy — that is, with a choice between dropping them and leaking them out the
|
||||
WAN, never a data plane. This decision gives them one, and deliberately NOT
|
||||
ours: **`globals.untunnelable_egress` (default empty;
|
||||
`model.Globals.UntunnelableEgress`) names an existing egress of type
|
||||
interface/tunnel, and LAN traffic that is neither TCP nor UDP is stamped in
|
||||
prerouting with that egress's own mark, so the KERNEL routes it out that
|
||||
egress's device with the kernel's own NAT.** No proxy, no engine, no userspace
|
||||
stack ever touches the packet — which is exactly why every protocol works.
|
||||
|
||||
**Where the engine's boundary actually is — recorded so nobody digs for it
|
||||
twice.** It is NOT the gVisor stack, and it is not WireGuard: on the forward
|
||||
path the WG/AWG endpoint never consults gVisor at all. `Endpoint.WritePackets`
|
||||
(`transport/wireguard/port.go:21-58`) takes the raw IP packet bytes, reads
|
||||
exactly the IP version and the destination address, and hands
|
||||
`device.InputPacketRef`s to `wgDevice.InputPackets` — the protocol byte is
|
||||
never read; on the way back (`port.go:127-157`) `returnDeviceWrapper.Write`
|
||||
offers every decrypted packet to `returnPath.ReturnPackets` first and only the
|
||||
unconsumed remainder falls through to the gVisor device. gVisor serves
|
||||
`DialContext`/`ListenPacket` — traffic the ENGINE originates — while forwarded
|
||||
traffic bypasses the stack in both directions, indifferent to protocol. The
|
||||
real ceiling sits one step earlier, in sing-tun's `ForwardDispatcher`:
|
||||
`parseTransport` (`flow_parse.go:106-153`) sets `hasFlow` for exactly TCP, UDP,
|
||||
ICMPv4 Echo/EchoReply and ICMPv6 EchoRequest/EchoReply — a packet of any other
|
||||
protocol is never dispatched as a flow — and `createFlow`
|
||||
(`flow_dispatch.go:325`) builds its NAT through
|
||||
`allocateSelector(packet.protocol, …, packet.source.Port())` (line 355), which
|
||||
needs a port-like selector that ESP/AH/GRE simply do not have (SCTP has ports,
|
||||
but the parser above never grants it a flow either). Tailscale documents the
|
||||
same frontier for its own userspace mode — "Any IP protocol other than TCP or
|
||||
UDP (such as SCTP) is not supported in userspace mode… All IP protocols are
|
||||
supported" in kernel mode
|
||||
(https://tailscale.com/docs/reference/kernel-vs-userspace-routers) — useful as
|
||||
external corroboration of where userspace data planes generally end, though OUR
|
||||
boundary is the dispatcher, not the stack. The kernel egress was therefore
|
||||
chosen not because userspace "cannot" in principle, but because the kernel
|
||||
delivers all protocols with zero new code on the hot path.
|
||||
|
||||
**The mechanism already existed; the feature is one binding and one marking
|
||||
step.** `addEgressRouting` (`netplane/apply.go`) has always installed, for
|
||||
every interface/tunnel egress, an `ip rule fwmark <EgressMark> lookup
|
||||
<EgressTable>` plus a `default dev <device>` route in that table — per-rule
|
||||
egress selection rides on it. The only missing piece was that nothing ever
|
||||
marked non-TCP/UDP traffic: `untunnelable=direct` merely ACCEPTED it in the
|
||||
forward chain, so it left over the main table, i.e. the WAN.
|
||||
`UntunnelableEgressBinding` (`netplane/nft.go`) resolves the option to the
|
||||
egress's index, its OWN mark and its OWN device — deliberately no third
|
||||
mark/table pair to keep coherent — and the prerouting chain stamps that mark on
|
||||
the untunnelable protocols. A name that does not resolve to an interface/tunnel
|
||||
egress with a device renders nothing and is reported: the D17 policy stays in
|
||||
sole charge, which is the fail-closed reading of a typo.
|
||||
|
||||
**Why `l4proto != { tcp, udp }` is safe here when D25 banned it.** D25 rejected
|
||||
the broad filter because the receiving side was the `ForwardDispatcher`, which
|
||||
classifies nothing beyond TCP/UDP/ICMP echo — a marked ESP packet would enter
|
||||
the TUN and vanish, a black hole wearing a tunnel's name. Here the receiving
|
||||
side is the kernel, which forwards ANY IP protocol and NATs what it has
|
||||
machinery for: SCTP carries ports and NATs like TCP/UDP; GRE is NATed only
|
||||
through the PPTP helper keyed on the call-id — the kernel's own comment calls
|
||||
GRE "generally not very suited for NAT, as it has no protocol-specific part as
|
||||
port numbers" (`net/netfilter/nf_conntrack_proto_gre.c`); ESP/AH pass as plain
|
||||
routed IP. Nothing on this path can silently swallow a protocol it does not
|
||||
understand, which was the entire objection.
|
||||
|
||||
**Order against D25: the L3 ingress claims ICMP first.** With `l3_tunnel` on,
|
||||
LAN ICMP is marked into the engine's TUN before the egress carrier is consulted
|
||||
— the engine path routes ping by the operator's rules, which a kernel egress
|
||||
cannot do — and only the remaining protocols go to the egress. With `l3_tunnel`
|
||||
off, ICMP goes to the egress with everything else. In both shapes marked
|
||||
traffic is settled by ROUTING before the forward chain speaks, so the D17
|
||||
policy now governs exactly the failure case — the rule or route that did not
|
||||
come up — the same division D25 already established for the L3 mark.
|
||||
|
||||
**What the feature refuses to promise — and the operator text refuses with it
|
||||
(`shater/apply/warnings.go`, the egress-carrier note).** (a) It is not a tunnel
|
||||
per se: the option accepts any interface/tunnel egress, and on the target
|
||||
routers a WireGuard device is the exception (`kmod-wireguard` is usually
|
||||
absent) while a second WAN is routine. Through a WireGuard egress this
|
||||
genuinely is a tunnel; through a second WAN it is simply another uplink, and
|
||||
the destination sees that uplink's real address. No text, comment or doc line
|
||||
may call it a tunnel unconditionally. (b) It does not revive IPTV: IGMP is
|
||||
LAN-side multicast group management, WireGuard is L3 point-to-point and carries
|
||||
no multicast, and multicast never crossed this router under any setting —
|
||||
routing IGMP out an egress restores nothing, and no wording may hint otherwise.
|
||||
(c) IPsec through NAT-T never needed it: RFC 3948 encapsulates ESP in UDP/4500,
|
||||
so a modern IPsec client behind NAT is ordinary UDP that already follows the
|
||||
routing rules; the raw-ESP case this feature carries is the no-NAT-T remainder.
|
||||
|
||||
- **Rejected: teaching the engine these protocols.** Extending `parseTransport`
|
||||
and the selector NAT upstream would be new hot-path code in an
|
||||
actively-maintained adversarial area, for protocols the kernel already
|
||||
forwards for free — and for ESP/AH/GRE there is no port-like selector to NAT
|
||||
by in the first place.
|
||||
- **Rejected 2026-07-26: carrying them through the userspace AWG endpoint
|
||||
site-to-site, with no NAT at all.** This is the alternative the "no port-like
|
||||
selector" line above does NOT dispose of, and it is written down because the
|
||||
obvious reading of that line — "impossible" — is wrong and would be
|
||||
re-derived. The endpoint is already protocol-blind in both directions
|
||||
(`transport/wireguard/port.go:21-58`, `:127-157`), so an ESP packet could be
|
||||
forwarded UNTOUCHED, keeping the LAN client's own source address, and the
|
||||
reply would come back addressed to that client and need only be written to the
|
||||
TUN. No selector, no NAT, every protocol. It needs two things we declined to
|
||||
take on: lx-owned code in the forward hot path, bypassing `ForwardDispatcher`
|
||||
on both legs — precisely the surface CONSTITUTION §2 exists to keep small on
|
||||
an actively-maintained upstream — and a SERVER-side prerequisite (our LAN
|
||||
prefix in the peer's `AllowedIPs`, plus a route back), which turns a router
|
||||
option into a deployment contract. The kernel egress above buys the same
|
||||
protocols with zero hot-path code, so this stays a design on file, not a gap.
|
||||
- **Rejected: a dedicated mark/table pair for the carrier.** `addEgressRouting`
|
||||
already binds `EgressMark`/`EgressTable` to the device; a third pair would be
|
||||
a second copy of the same route that could drift from the first.
|
||||
|
||||
**Not verified, said plainly.** The end-to-end path — LAN client → prerouting
|
||||
mark → ip rule → egress device → far end and back — has not been exercised with
|
||||
real ESP or GRE on live hardware. Nothing above claims it has.
|
||||
|
||||
Consequence: raw IPsec, PPTP/GRE, SCTP — and ICMP when the L3 ingress is off —
|
||||
leave through an egress the operator explicitly named, under kernel routing and
|
||||
kernel NAT, instead of being dropped or silently leaking out the WAN; and with
|
||||
the option empty (the default) the plane renders byte-for-byte as before, with
|
||||
the D17 policy in sole charge.
|
||||
|
||||
+42
-6
@@ -12,9 +12,35 @@ usable release, **[T1]** next, **[T2]** later. Phases refer to `ROADMAP.md`.
|
||||
## Transparent proxying & routing
|
||||
- **[MVP]** TPROXY transparent proxy for multiple LAN interfaces (TCP + UDP), SNI/
|
||||
Host/QUIC sniffing.
|
||||
- **[MVP]** **L3 ingress for ICMP** (`globals.l3_tunnel`, opt-in, default off):
|
||||
LAN ping travels THROUGH the tunnel instead of being dropped or answered by a
|
||||
forged local reply. The engine opens a dedicated TUN (`shater-l3`, gVisor
|
||||
stack, `auto_route` off); nft marks LAN icmp/icmpv6 only and a scoped
|
||||
`ip rule` routes it in — the TPROXY plane and the main routing table stay
|
||||
untouched (D25). Carried only by L3-capable egresses (WireGuard/AmneziaWG,
|
||||
direct); ICMP routed to vless/vmess/… is honestly dropped, never faked.
|
||||
Ceiling is upstream sing-tun's: ICMP echo only — Windows tracert works, IPv6
|
||||
traceroute shows just the destination; ESP/AH/GRE/IGMP stay with the
|
||||
`untunnelable` policy (D17) unless `untunnelable_egress` carries them (D26).
|
||||
- **[MVP]** **Kernel egress for untunnelable protocols**
|
||||
(`globals.untunnelable_egress`, opt-in, default empty): names an existing
|
||||
interface/tunnel egress, and IPsec (ESP/AH), PPTP/GRE, SCTP — everything that
|
||||
is neither TCP nor UDP, plus ICMP when the L3 ingress is off — is routed out
|
||||
that egress's device by the KERNEL with kernel NAT, reusing the egress's own
|
||||
fwmark/table from `addEgressRouting`; the proxy never sees a byte, which is
|
||||
why every protocol works (D26). What that buys depends on the device: a
|
||||
WireGuard interface really is a tunnel, a second WAN is just another uplink
|
||||
whose real address the destination sees. It does not revive multicast IPTV,
|
||||
and UDP-based VPNs (WireGuard, OpenVPN-UDP, IPsec NAT-T) never needed it —
|
||||
they follow the routing rules as before. The `untunnelable` policy (D17)
|
||||
keeps only the failure case: a route that did not come up.
|
||||
- **[MVP]** First-match routing rules by source (IP/CIDR/MAC/interface/zone),
|
||||
destination (domain/suffix/keyword/geosite), reusable domain/IP lists, port,
|
||||
proto → target (outbound/selector/chain/direct/block) + egress.
|
||||
destination, port, proto → target (outbound/selector/chain/direct/block) + egress.
|
||||
A rule names its **destination through a rule-set only** — a reusable named list
|
||||
(inline domains/CIDRs, a local or remote file, or a geosite/geoip category) that is
|
||||
compiled once into a `.srs` and shared by every rule that references it. Domain
|
||||
entries take `full:` (exact), `suffix:` / a leading dot (host + subdomains),
|
||||
`keyword:` (substring) and `regexp:`; a bare entry means host + subdomains.
|
||||
- **[MVP]** Node groups with balancer/observatory (least-ping/failover/round-robin).
|
||||
- **[T1]** Multi-hop chains (L1→Ln); per-rule egress selection; egress via any
|
||||
interface/tunnel (e.g. an AmneziaWG tunnel).
|
||||
@@ -36,6 +62,16 @@ usable release, **[T1]** next, **[T2]** later. Phases refer to `ROADMAP.md`.
|
||||
type=fakeip + pool — there is no global "FakeIP mode"); no DNS leaks. Routing
|
||||
is decided by in-engine rule-sets — the v0.1 dnsmasq→nftset population
|
||||
mechanism does not exist in v0.2 (see generate/dns.go).
|
||||
The hijack covers the queries a client sends **to the router itself** — the
|
||||
address DHCP hands out — because `globals.dns_intercept` is **ON by default**
|
||||
(D24). With it off, those queries go to dnsmasq and out to the ISP in the clear,
|
||||
so the well-behaved client leaks while the one that hard-codes 8.8.8.8 does not.
|
||||
`.lan` and the private PTR zones are preserved through dnsmasq either way. Two
|
||||
things the promise does NOT cover, both by design: while the engine is DOWN the
|
||||
holding plane hooks `forward` only, so dnsmasq still answers router-addressed
|
||||
:53 unfiltered (client traffic and DNS to external resolvers stay blocked); and
|
||||
with no `config resolver` at all there is no DNS plane to filter with — queries
|
||||
fall through to the system resolver and generate says so.
|
||||
- **[MVP]** Client DoT/DoH blocking (stop devices bypassing the filter).
|
||||
- **[MVP]** **Blocklists** with **flexible sources**: `inline` (type your own) /
|
||||
`file` / `url` (auto-update) / `geosite` category (only when geodata present).
|
||||
@@ -89,8 +125,8 @@ usable release, **[T1]** next, **[T2]** later. Phases refer to `ROADMAP.md`.
|
||||
SIM uplink → different egress); backup/restore; i18n (EN + RU).
|
||||
|
||||
## Ops & distribution
|
||||
- **[MVP]** Single signed binary; signed opkg feed on Gitea (reuse key
|
||||
`5ac4b177689cb8e0`); one-line install; `opkg upgrade`.
|
||||
- **[MVP]** Single signed binary; signed apk feed on Gitea (EC key
|
||||
`dist/shater-apk.pem`); one-line install; named-package `apk upgrade`.
|
||||
- **[T1]** Upstream-rebase cadence (track sing-box-lx tags) with a smoke suite.
|
||||
- **[T2]** apk (OpenWrt 25.x) packaging; multi-router fleet management; REST/gRPC
|
||||
external API; Telegram bot.
|
||||
- **[T2]** Multi-router fleet management; REST/gRPC external API; Telegram bot.
|
||||
(apk packaging landed and is now the only lane — D22.)
|
||||
|
||||
+173
-84
@@ -1,7 +1,7 @@
|
||||
# Shater v0.2 — Build & Install
|
||||
|
||||
How to build the ship artifact (the SPA-embedded `shaterd` binary) and install
|
||||
the OpenWrt feed onto a router.
|
||||
the signed apk repo onto a router.
|
||||
|
||||
## 1. Build the `shaterd` binary
|
||||
|
||||
@@ -26,7 +26,9 @@ What it does:
|
||||
Arg / env:
|
||||
|
||||
- `VERSION` — stamped into `constant.Version`. Resolution: positional arg →
|
||||
`$SHATER_VERSION` → `git describe --tags` → `v0.2.0-dev`.
|
||||
`$SHATER_VERSION` → `ci/version.sh --binary` → `v0.2.0-dev`. `ci/version.sh` is
|
||||
the **same** computation the package version comes from (§2.1), so the string
|
||||
the panel shows always matches what `apk list -I shaterd` reports.
|
||||
- `--fast` — skip `npm ci` when `panel/node_modules` already exists.
|
||||
- `UPX=/path/to/upx` — override the UPX binary (default `upx` on `PATH`). UPX is
|
||||
cross-arch, so one host packs both the amd64 and aarch64 ELFs. (Note: UPX also
|
||||
@@ -41,22 +43,44 @@ UPX="…/scratchpad/upx-4.2.4-win64/upx.exe" scripts/build-shaterd.sh v0.2.0 --f
|
||||
The `dist/*` and `openwrt/shaterd/files/shaterd-*.upx` outputs are gitignored —
|
||||
they are release artifacts, not source.
|
||||
|
||||
Tag set (D9 — keep in sync with `docs-shater/DECISIONS.md`):
|
||||
Tag set (D9/D23) — defined in **one** place, `scripts/router-tags.sh`, which
|
||||
documents every tag and is sourced by the build:
|
||||
|
||||
```
|
||||
with_quic,with_wireguard,with_utls,
|
||||
with_gvisor,with_quic,with_wireguard,with_utls,
|
||||
badlinkname,tfogo_checklinkname0,with_xhttp,with_awg,with_lx_command
|
||||
```
|
||||
|
||||
We drop `with_purego,with_naive_outbound`: they pull cronet-go, which forces a
|
||||
glibc `PT_INTERP` even under `CGO_ENABLED=0`, making the binary unusable on musl.
|
||||
We drop `with_gvisor`: the shater data plane is tproxy/redirect and generate
|
||||
never emits a tun inbound, so the userspace gvisor netstack is unreachable code.
|
||||
We drop `with_clash_api`: the admin panel is shater's own web server and the
|
||||
generator never emits a `clash_api` service, so the Clash server is dead code.
|
||||
We drop `with_dhcp`: shater resolver types are `udp/tcp/doh/dot/local/fakeip`;
|
||||
a `dhcp://` DNS transport is never generated or registered.
|
||||
|
||||
`with_gvisor` was dropped in 2026-07 as "unreachable — we emit no tun inbound"
|
||||
and **put back on 2026-07-25**: gVisor is also the netstack of the WireGuard
|
||||
endpoint, so without it every `wg://`/`awg://` node died at apply time with
|
||||
*"gVisor is not included in this build"* while the panel still offered the
|
||||
feature. It costs ~2.8 MB raw / ~0.65 MB UPX per arch. Full story: `DECISIONS.md`
|
||||
D23.
|
||||
|
||||
### Changing the tag set
|
||||
|
||||
Run the guard — it is what stands between a size trim and a silently dead
|
||||
feature, and CI runs it before the artifact is built:
|
||||
|
||||
```sh
|
||||
scripts/check-router-tags.sh # from Windows/macOS it re-execs itself in golang:1.26
|
||||
```
|
||||
|
||||
It (1) fails if a feature declared in `FEATURES.md` lost a build tag it needs to
|
||||
run (`shater/buildtags`, no tags/OS/network required) and (2) constructs one node
|
||||
of every declared protocol through `box.New` **compiled with the shipped tag
|
||||
set** — nothing may be skipped in that run. Adding a protocol to
|
||||
`shater/parse`+`shater/generate` means adding a row to `buildtags.Features` and a
|
||||
probe case in `shater/generate/shipped_tags_linux_test.go`.
|
||||
|
||||
## 2. Packages
|
||||
|
||||
Four OpenWrt packages live under `openwrt/`:
|
||||
@@ -84,22 +108,65 @@ it. Because the binary is UPX-packed, the package disables the SDK's default str
|
||||
feed installed and run `make package/shaterd/compile` (and the others) per target.
|
||||
See `openwrt-package-build-ci` for SDK/feed mechanics.
|
||||
|
||||
### 2.1 Package versions come from the git tag
|
||||
|
||||
`PKG_VERSION`/`PKG_RELEASE` are **not** maintained by hand. They used to be, and
|
||||
nobody bumped them: **v0.2.2 … v0.2.6 all shipped as `shaterd 0.2.0-r3`** with
|
||||
different binaries inside (v0.2.6's ELF is 5 491 616 B against r2's 5 488 336 B).
|
||||
apk offers an upgrade only when the feed's version string differs from the
|
||||
installed one, so `apk update` saw nothing new and the routers could not be
|
||||
updated through the normal path at all.
|
||||
|
||||
`ci/version.sh` now derives them from `git describe`, once per CI job:
|
||||
|
||||
| Build | `PKG_VERSION` | `PKG_RELEASE` | `constant.Version` |
|
||||
|---|---|---|---|
|
||||
| tag push `v0.2.7` | `0.2.7` | `1` | `v0.2.7-r1` |
|
||||
| dispatch, 3 commits past `v0.2.7` | `0.2.7` | `4` | `v0.2.7-r4-g<sha>` |
|
||||
| no reachable tag / no git | `0.0.0` | `1` | `v0.0.0-r1` |
|
||||
|
||||
Ordering is what makes this safe (checked with `apk version -t` on apk-tools
|
||||
3.0.3): the dotted part decides first, `-rN` only breaks ties — so
|
||||
`0.2.7-r1 > 0.2.6-r12 > 0.2.6-r1 > 0.2.0-r3`. A release therefore always
|
||||
outranks every rolling build before it, rolling builds between two releases grow
|
||||
monotonically, and an untagged build (`0.0.0`) can never masquerade as an
|
||||
upgrade.
|
||||
|
||||
The value travels as `SHATER_PKG_VERSION`/`SHATER_PKG_RELEASE` in the SDK build
|
||||
environment; the Makefiles read it with a literal fallback for manual/offline
|
||||
builds. `ci/sdk-build-apk.sh` then **asserts** the produced `.apk` really carries
|
||||
it, so a lost variable fails the build instead of shipping a stale version. The
|
||||
release job asserts the same version again on the published rolling repo (§5.1).
|
||||
|
||||
`byedpi` is deliberately excluded — `PKG_VERSION:=0.17.3` is *upstream ByeDPI's*
|
||||
version, which is what `PKG_HASH` pins and what tells you which ByeDPI is
|
||||
installed. Stamping our tag on it would also be a downgrade: every comparator
|
||||
reads `0.2.7 < 0.17.3` (component-wise, `2 < 17`). Bump its `PKG_RELEASE` by hand
|
||||
when our packaging of it changes.
|
||||
|
||||
## 3. Install on a router
|
||||
|
||||
Install order follows the deps (`shaterd` → `shater-core` → `luci-app-shater`):
|
||||
**The normal path is the signed apk repo — §5.** This section is the manual
|
||||
fallback (a router with no route to the Gitea host, or a hand-carried build).
|
||||
|
||||
Install order follows the deps (`shaterd` → `shater-core` → `luci-app-shater`).
|
||||
apk filenames carry no architecture, so make sure you copied the `.apk` built for
|
||||
*this* router's arch (`cat /etc/apk/arch`):
|
||||
|
||||
```sh
|
||||
opkg install shaterd_0.2.0-1_<arch>.ipk # or: apk add shaterd (25.12+)
|
||||
opkg install shater-core_0.2.0-1_all.ipk
|
||||
opkg install luci-app-shater_0.2.0-1_all.ipk
|
||||
opkg install byedpi_0.17.3-1_<arch>.ipk # optional: ByeDPI egress
|
||||
# <ver> = the release version, e.g. 0.2.7-r1 (§2.1 — it comes from the git tag)
|
||||
# --allow-untrusted: our member .apk are unsigned by design — trust lives in the
|
||||
# signed packages.adb index (§5), which a loose file install does not consult.
|
||||
apk add --allow-untrusted ./shaterd-<ver>.apk
|
||||
apk add --allow-untrusted ./shater-core-<ver>.apk
|
||||
apk add --allow-untrusted ./luci-app-shater-<ver>.apk
|
||||
apk add --allow-untrusted ./byedpi-0.17.3-r1.apk # optional: ByeDPI egress
|
||||
```
|
||||
|
||||
Installing from a signed feed instead:
|
||||
From the repo instead (§5 sets it up once), deps pull the rest in:
|
||||
|
||||
```sh
|
||||
# add the feed (customfeeds.conf / apk repositories), then:
|
||||
opkg update && opkg install shater-core luci-app-shater # shaterd pulled in as a dep
|
||||
apk update && apk add luci-app-shater # -> shater-core -> shaterd
|
||||
```
|
||||
|
||||
## 4. Enable
|
||||
@@ -119,83 +186,87 @@ daemon (`shaterd run`), which owns the engine, the `inet shater` data plane, pol
|
||||
routing, in-process DNS, and the admin panel (default `:8088`). The LuCI app's
|
||||
"Open panel" button mints a single-use token and hands the browser off to the panel.
|
||||
|
||||
## 5. Add the signed feed (recommended — then `opkg upgrade` just works)
|
||||
### What enabling does to DNS
|
||||
|
||||
CI (`.gitea/workflows/release.yml`) publishes every build as a **rolling `latest`
|
||||
Gitea release** that is itself a signed opkg `src/gz` feed: the release holds the
|
||||
`.ipk` for all arches, a `Packages`/`Packages.gz` index, a usign `Packages.sig`,
|
||||
and the public key `shater-feed.pub`. opkg filters by `Architecture`, so the **same
|
||||
two lines work on every device** (x86 testbed picks `x86_64 + all`; the BPI routers
|
||||
pick `aarch64_cortex-a53 + all`).
|
||||
From the first apply, **every** LAN plaintext `:53` goes into the engine — including
|
||||
the queries a client sends to the router's own address, which is what DHCP hands out.
|
||||
That is `globals.dns_intercept`, and it is **on by default** (D24); without it those
|
||||
queries reach dnsmasq and the ISP unfiltered, i.e. the client with default settings
|
||||
leaks while the one that hard-coded `8.8.8.8` does not. What follows from it:
|
||||
|
||||
> **Format:** OpenWrt 24.10 (our SDK) uses **opkg** (`.ipk`, `Packages.gz`, usign),
|
||||
> so the feed is `src/gz` and the trust anchor is the usign key
|
||||
> `dist/shater-feed.pub` (fingerprint **`5ac4b177689cb8e0`**). apk only replaces
|
||||
> opkg at OpenWrt **25.12** — see §6.
|
||||
- `.lan` and private reverse (PTR) lookups still go to dnsmasq — the engine gets a
|
||||
rule for those suffixes. If you renamed dnsmasq's domain away from `lan`, add a
|
||||
`config dns_rule` for the new suffix.
|
||||
- Configure at least one `config resolver`. With none, the engine has no resolver
|
||||
plane: intercepted queries fall through to the system resolver (dnsmasq → your
|
||||
ISP, in the clear), blocklists and per-device DNS rules are inert, and the apply
|
||||
says so in its warnings.
|
||||
- While the engine is DOWN, DNS is **not** blacked out: the fail-closed holding
|
||||
plane hooks `forward` only, so dnsmasq keeps answering router-addressed `:53`
|
||||
(unfiltered, plaintext) while client traffic and DNS to external resolvers stay
|
||||
blocked. "The tunnel is down" is not "DNS is private".
|
||||
|
||||
One-time setup on the router:
|
||||
To opt out, on the router:
|
||||
|
||||
```sh
|
||||
# 1) trust the feed key — the FILENAME must equal the usign key fingerprint.
|
||||
wget -O /etc/opkg/keys/5ac4b177689cb8e0 \
|
||||
https://git.qomar.pw/omar/shater/releases/download/latest/shater-feed.pub
|
||||
|
||||
# 2) add the feed (one URL serves every arch).
|
||||
echo "src/gz shater https://git.qomar.pw/omar/shater/releases/download/latest" \
|
||||
>> /etc/opkg/customfeeds.conf
|
||||
|
||||
# 3) refresh + install (shaterd is pulled in as a dependency).
|
||||
opkg update
|
||||
opkg install luci-app-shater # -> shater-core -> shaterd
|
||||
opkg install byedpi # optional: ByeDPI desync egress
|
||||
uci set shater.globals.dns_intercept=0
|
||||
uci commit shater
|
||||
shaterd apply
|
||||
```
|
||||
|
||||
With the key installed, opkg's default `check_signature 1` verifies the feed on
|
||||
every `opkg update`; no `--nocheck-signature` needed. A **tagged** release
|
||||
(`vX.Y.Z`) publishes the identical layout at
|
||||
`.../releases/download/vX.Y.Z` if you prefer to pin a version instead of tracking
|
||||
`latest`.
|
||||
Your `0` is kept: `/etc/config/shater` is a conffile (upgrades never replace it) and
|
||||
the daemon always writes the option back explicitly, so it is never re-enabled by a
|
||||
default.
|
||||
|
||||
### Updating
|
||||
## 5. The signed apk repo (the normal install path)
|
||||
|
||||
```sh
|
||||
opkg update
|
||||
opkg upgrade shaterd shater-core luci-app-shater byedpi # only our own packages
|
||||
```
|
||||
OpenWrt/ImmortalWrt **25.12** packages with Alpine's **apk**: `.apk` files, a
|
||||
binary `packages.adb` index, EC (prime256v1) keys in `/etc/apk/keys/`, and
|
||||
effectively mandatory signatures (unsigned needs `--allow-untrusted`). This is
|
||||
the only format shater publishes — the `.ipk`/opkg lane was removed in 2026-07
|
||||
(`DECISIONS.md` D22); every device we serve is on 25.12 with apk-tools 3.
|
||||
|
||||
Updates are only offered when the feed's `Version` differs from the installed one,
|
||||
so **bump `PKG_RELEASE`** (or `PKG_VERSION`) in the package Makefile on every
|
||||
shipped change — otherwise `opkg upgrade` sees the same version and does nothing.
|
||||
Do **not** `opkg upgrade` base/system packages from this feed; upgrade only the
|
||||
four shater packages above.
|
||||
|
||||
## 6. apk feed (OpenWrt/ImmortalWrt 25.12+ — incl. BananaWRT 25.12-mtk-vendor)
|
||||
|
||||
OpenWrt/ImmortalWrt **25.12** replaces opkg with Alpine's **apk**: `.apk` files,
|
||||
a binary `packages.adb` index, EC (prime256v1) keys in `/etc/apk/keys/`, and
|
||||
effectively mandatory signatures (unsigned needs `--allow-untrusted`). The
|
||||
package **Makefiles are unchanged** — the SDK release decides the format.
|
||||
|
||||
CI builds this lane **in parallel** with the opkg feed (same manual triggers:
|
||||
`v*` tag push or `workflow_dispatch`): the `build-apk` jobs in
|
||||
`.gitea/workflows/release.yml` compile the same 4 packages through the official
|
||||
**ImmortalWrt 25.12 SDK** (tarballs from
|
||||
CI (`v*` tag push or `workflow_dispatch`) compiles the 4 packages through the
|
||||
official **ImmortalWrt 25.12 SDK** (tarballs from
|
||||
`downloads.immortalwrt.org/releases/25.12.1/targets/{x86/64,mediatek/filogic}/`)
|
||||
and publish **one release per arch** — rolling `apk-latest-x86_64` /
|
||||
`apk-latest-aarch64_cortex-a53`, or `apk-vX.Y.Z-<arch>` for a tagged version.
|
||||
Per-arch (unlike the combined opkg release) because apk filenames carry no
|
||||
architecture and packages are fetched relative to the `packages.adb` URL.
|
||||
and publishes **one release per arch**: the rolling `apk-latest-x86_64` /
|
||||
`apk-latest-aarch64_cortex-a53`, plus `apk-vX.Y.Z-<arch>` on a tag. Per-arch
|
||||
because apk filenames carry no architecture and packages are fetched *relative to
|
||||
the `packages.adb` URL*, so one flat multi-arch release would collide.
|
||||
|
||||
> **Key:** apk cannot use the usign key. The apk trust anchor is the separate EC
|
||||
> public key **`dist/shater-apk.pem`** (generated once by `ci/gen-apk-key.sh`;
|
||||
> private half lives ONLY in the Gitea secret **`KEY_APK`**, the apk analog of
|
||||
> `KEY_BUILD`). Never regenerate either key — that invalidates every deployed
|
||||
> router's trust. The usign identity `shater-feed.pub` keeps signing the
|
||||
> opkg/24.10 feed, untouched.
|
||||
> **Key:** the trust anchor is the EC public key **`dist/shater-apk.pem`**
|
||||
> (generated once by `ci/gen-apk-key.sh`; the private half lives ONLY in the
|
||||
> Gitea secret **`KEY_APK`**). Never regenerate it — that invalidates every
|
||||
> deployed router's trust.
|
||||
|
||||
One-time setup on a 25.12 router (BananaWRT `25.12-mtk-vendor` on the BPI-R3
|
||||
mini, BPI-R4 on 25.12, or the future 25.12 VM — `/etc/apk/arch` picks the right
|
||||
per-arch release automatically):
|
||||
### 5.1 Rolling or pinned — pick the repo URL deliberately
|
||||
|
||||
The repo line names an **index file**, and which one you name is the whole
|
||||
update policy:
|
||||
|
||||
| Repo line points at | Behaviour | Cost |
|
||||
|---|---|---|
|
||||
| `apk-latest-<arch>/packages.adb` (**rolling**) | Every release run REPLACES this release's assets, so `apk update && apk upgrade <our packages>` always sees the newest build. Install once, never touch the file again. | You get whatever CI published last; there is no per-router pin. |
|
||||
| `apk-vX.Y.Z-<arch>/packages.adb` (**pinned**) | The router stays on exactly that build. `apk update` will never offer a newer shater. | `/etc/apk/repositories.d/shater.list` must be edited **by hand on every upgrade**, on every router. |
|
||||
|
||||
`mini_router` is deliberately on a **pinned** URL — a considered choice, and the
|
||||
hand-edit per release is its price. Use rolling unless you specifically want to
|
||||
freeze a device.
|
||||
|
||||
> The rolling release used to go stale silently: publishing was an either/or, so
|
||||
> tag runs wrote only `apk-vX.Y.Z-<arch>` and `apk-latest-<arch>` was last
|
||||
> refreshed on 2026-07-24 at `0.2.0` while v0.2.9/v0.2.10 shipped. A router on
|
||||
> the rolling URL kept getting a successful `apk update` with nothing new. Fixed
|
||||
> 2026-07-25: `release-apk` writes the rolling pointer on **every** run and then
|
||||
> reads the release back over the Gitea API, asserting it holds our three
|
||||
> tag-versioned packages at exactly the version just built and **no** leftover
|
||||
> asset at another version (two versions of one package in one index would let
|
||||
> apk choose instead of us).
|
||||
|
||||
### 5.2 One-time setup on the router
|
||||
|
||||
BananaWRT `25.12-mtk-vendor` on the BPI-R3 mini, OpenWrt 25.12 on the BPI-R4, or
|
||||
the testbed VM — `/etc/apk/arch` picks the right per-arch release automatically:
|
||||
|
||||
```sh
|
||||
# 1) trust the apk feed key (any *.pem filename under /etc/apk/keys works).
|
||||
@@ -203,6 +274,7 @@ wget -O /etc/apk/keys/shater-apk.pem \
|
||||
"https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/shater-apk.pem"
|
||||
|
||||
# 2) add the repo — the line points at the packages.adb INDEX FILE itself.
|
||||
# (rolling; for a pinned router put apk-vX.Y.Z-$(cat /etc/apk/arch) here — §5.1)
|
||||
echo "https://git.qomar.pw/omar/shater/releases/download/apk-latest-$(cat /etc/apk/arch)/packages.adb" \
|
||||
> /etc/apk/repositories.d/shater.list
|
||||
|
||||
@@ -212,17 +284,34 @@ apk add luci-app-shater # -> shater-core -> shaterd
|
||||
apk add byedpi # optional: ByeDPI desync egress
|
||||
```
|
||||
|
||||
### Updating
|
||||
### 5.3 Updating
|
||||
|
||||
**Never run a bare `apk upgrade`.** With no arguments apk reconciles *every*
|
||||
installed package against *every* configured repository at once; on a router
|
||||
whose distfeeds point at a moving snapshot that can pull in — or roll back —
|
||||
unrelated system packages. Always name ours:
|
||||
|
||||
```sh
|
||||
apk update
|
||||
apk upgrade shaterd shater-core luci-app-shater byedpi # only our own packages
|
||||
apk upgrade shaterd shater-core luci-app-shater byedpi
|
||||
```
|
||||
|
||||
Same rule as opkg: an upgrade is only offered when the feed version differs, so
|
||||
bump `PKG_RELEASE`/`PKG_VERSION` on every shipped change (apk shows it as
|
||||
`0.2.0-r1`). Pin a version instead of tracking rolling by pointing the repo line
|
||||
at `.../download/apk-vX.Y.Z-$(cat /etc/apk/arch)/packages.adb`.
|
||||
apk-tools 3 documents exactly this behaviour for `apk upgrade`: *"When no
|
||||
packages are specified, all packages are upgraded if possible. If list of
|
||||
packages is provided, only those packages are upgraded along with needed
|
||||
dependencies."* The equivalent form, which additionally re-pins the packages in
|
||||
`world`, is:
|
||||
|
||||
```sh
|
||||
apk add -u shaterd shater-core luci-app-shater byedpi # -u = --upgrade
|
||||
```
|
||||
|
||||
Drop `byedpi` from either list if you never installed it. Check what you are on
|
||||
with `apk list -I shaterd shater-core luci-app-shater byedpi` — the version reads
|
||||
`0.2.7-r1` (§2.1: `PKG_VERSION-rPKG_RELEASE`, derived from the git tag by CI, so
|
||||
every build really is a new version; before that fix v0.2.2…v0.2.6 all published
|
||||
as `0.2.0-r3` and `apk update` offered nothing). Rolling vs pinned repo URL —
|
||||
§5.1.
|
||||
|
||||
### BananaWRT `25.12-mtk-vendor` compatibility
|
||||
|
||||
|
||||
+41
-4
@@ -195,7 +195,7 @@ type Chain struct { Name string; Hops []string } // "group:<n>" | "node:<n>", L1
|
||||
type Egress struct { Name,Type,Interface,Target string } // interface|proxy|direct|block
|
||||
type Rule struct {
|
||||
Name string; Enabled bool; Order int
|
||||
Src []string; DstDomain,DstRuleset,DstIP []string; DstPort,Proto string
|
||||
Src []string; DstRuleset []string; DstPort,Proto string // dst = ruleset only (v0.2 schema v2)
|
||||
Target string // chain:|group:|node:|direct|block
|
||||
Egress,Kill string
|
||||
SchedEnabled bool; SchedDays []string; SchedStart,SchedEnd string; SchedUTCOffset int
|
||||
@@ -251,14 +251,51 @@ Apply/rollback: `apSnapshot` (run→last-good, nft→last-good.nft, route marks)
|
||||
> v0.2: "restart engine only on change" → config-hash gate + Close+New box (no reload).
|
||||
|
||||
### uci.go — `/etc/config/shater` schema
|
||||
- `config globals`: enabled, loglevel, kill_switch, dns_mode, ipv6, fwmark_base, table_base, confirm_timeout, resolver_default, resolver_fallback, probe_url, probe_interval, schema_version, active_profile.
|
||||
- `config globals` — the full option set, with the value used when the option is
|
||||
ABSENT (the `model.DefaultGlobals` seed). Booleans are always written back as
|
||||
`'1'`/`'0'` by `render.go`, so an explicit value never decays into the seed:
|
||||
|
||||
| option | default | meaning |
|
||||
|---|---|---|
|
||||
| `enabled` | `0` as shipped | master switch; `0` ⇒ `Reconcile` tears the stack down instead of applying |
|
||||
| `loglevel` (alias `log_level`) | `warning` | engine + daemon level; `none/off/silent/disabled` ⇒ log disabled, unknown ⇒ `warn` + a validation warning |
|
||||
| `log_syslog` / `log_file` / `log_persist` | `1` / `1` / `0` | operational log (`shater/logsink`): syslog, rotated file, and whether that file lives on flash instead of tmpfs |
|
||||
| `log_max_kb` | `2048` | size cap of the log file, clamped to 128…8192; `0` = "use the default", not "off" |
|
||||
| `kill_switch` | `closed` | `closed` = fail-closed (block on engine loss, incl. a holding plane when the engine never started); `open` = plain routing |
|
||||
| `ipv6` | `1` | `0` drops LAN IPv6 in the forward chain instead of leaving it unproxied |
|
||||
| `fwmark_base` / `table_base` | `0x2000` | reserved fwmark / routing-table bases (must not collide with fw4 or other apps) |
|
||||
| `confirm_timeout` | `0` | seconds before an unconfirmed apply auto-rolls back; `0` = commit-confirm off |
|
||||
| `resolver_default` / `resolver_fallback` / `endpoint_resolver` | unset | `config resolver` names: the DNS catch-all, its failover chain, and the bootstrap-direct server that resolves proxy endpoint DOMAINS |
|
||||
| `probe_url` / `probe_interval` | engine defaults | the ONE instrument all health probing uses (D20 — there are no per-group overrides) |
|
||||
| `panel_port` | `0` ⇒ `8088` | admin-panel HTTP port |
|
||||
| `dns_filter` | `0` | master enable of the blocklist/allowlist filter (D15); needs at least one `config resolver` |
|
||||
| `dns_intercept` | **`1`** | force ALL LAN plaintext `:53` into the engine, INCLUDING queries addressed to the router itself. See D24 for why this is the default, what preserves `.lan`, and what happens while the engine is down |
|
||||
| `block_doh` | `0` | NXDOMAIN the known public DoH hostnames + the Firefox canary and reject `:443` to their IPs, so clients fall back to `:53` (which the engine catches) |
|
||||
| `group_health` | `1` | OUR background group probing (the observatory). Does not touch sing-box's own urltest inside a group |
|
||||
| `untunnelable` | `block` | policy for what TPROXY cannot carry (ICMP/IGMP/ESP/AH/GRE/SCTP): `block` \| `icmp` (echo out, rest dropped) \| `direct` (all out, bypassing the tunnel) |
|
||||
| `geo_provider` | unset = auto | `sagernet` \| `loyalsoldier` \| `metacubex` \| `custom`; auto = country codes from SagerNet, everything else from Loyalsoldier |
|
||||
| `geosite_url` / `geoip_url` | unset | `{category}` templates, honoured only when `geo_provider=custom` |
|
||||
| `geosite_index_url` / `geoip_index_url` | unset | git-trees URLs used to SUGGEST categories in the panel; empty = no suggestions |
|
||||
| `stats_backend` | `memory` | `off` (no aggregation at all) \| `memory` (RAM, lost on restart) \| `sqlite` (aggregates in RAM + query/connection log on disk) |
|
||||
| `stats_ring_size` / `stats_timeline_minutes` / `stats_max_domains` | `200` / `60` / `5000` | live-log length, sparkline minutes, domain-map cap. **`0` = UNLIMITED** (grows with traffic), which is why these three are always emitted |
|
||||
| `stats_disk_limit_mb` | `64` | on-disk cap of `stats.db`; only meaningful for `stats_backend=sqlite`; `0` = unlimited |
|
||||
| `stats_retention_disabled` | `0` | master switch that turns OFF all trimming/pruning — every aggregate then grows unbounded |
|
||||
| `schema_version` | `0` = pre-versioned | UCI schema revision; `shaterd migrate` writes `2` |
|
||||
| `active_profile` | unset | display bookkeeping: the last profile switched to |
|
||||
|
||||
Deleted options still parse (unknown keys are ignored) and drain out on the next
|
||||
render: `dns_mode` (D17 — fake-IP is a resolver TYPE), `sweep_interval` (D19).
|
||||
- `config inbound`: name, enabled, type, network, tproxy_port(12345), listen, port, auth, user, pass, target_addr, target_port, target_network, tcp, udp, sniff.
|
||||
- `config subscription`: name, enabled, url, update_interval, fetch_via(direct|proxy), ua, hwid, device_os, ver_os, device_model, list header, format, list include/exclude/filter_proto/filter_country, dedup, expire_alert_days.
|
||||
- `config node`: name, enabled, uri, mux, mux_concurrency, xudp_concurrency, xudp_udp443, sockopt_mark, tcp_fast_open, tcp_keepalive_idle.
|
||||
- `config group`: name, source, subscription, list node, strategy, include/exclude/filter_proto/filter_country, dedup, probe_url, probe_interval.
|
||||
- `config chain`: name, list hop. `config egress`: name, type, interface, target.
|
||||
- `config ruleset`: name, type(domain|ipcidr), source(inline|file|url), url, path, format, update_interval, list entry.
|
||||
- `config rule`: name, enabled, order, list src/dst_domain/dst_ruleset/dst_ip, dst_port, proto, target, egress, kill, sched_enabled, list sched_day, sched_start/end/tz.
|
||||
- `config ruleset`: name, type(domain|ipcidr), source(inline|file|url|geosite|geoip), url, path, format, update_interval, list category, list entry.
|
||||
- `config rule`: name, enabled, order, list src, list dst_ruleset, dst_port, proto, target, egress, kill, sched_enabled, list sched_day, sched_start/end, sched_utc_offset.
|
||||
v0.1 carried `dst_domain`/`dst_ip` on the rule itself; **schema v2 removed both** — a
|
||||
destination is a `config ruleset` and nothing else. `shaterd migrate` folds each legacy
|
||||
list into a generated `rule-<name>` (and `rule-<name>-ip`) inline ruleset; see
|
||||
`DECISIONS.md` D21 for the entry-by-entry conversion table.
|
||||
- `config preset`: name, enabled, order, target. `config profile`: name, enabled, priority, list match_iface, probe_url, probe_mode, sched_*, list enable_rule/disable_rule, default_target, default_egress.
|
||||
- `config resolver`: name, type, address, detour, pool. `config dns_rule`: order, list match_domain/match_src, resolver.
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Документация shater
|
||||
|
||||
Документация продукта **shater** (управляемый интернет-шлюз для роутеров на
|
||||
OpenWrt). Лицо репозитория и быстрый старт — в корневом [`../README.md`](../README.md).
|
||||
|
||||
| Документ | О чём |
|
||||
|----------|-------|
|
||||
| [CONTEXT.md](CONTEXT.md) | **Начните здесь** — контекст проекта, история v0.1→v0.2, решения в кратце, testbed/инфра |
|
||||
| [INSTALL.md](INSTALL.md) | Сборка ship-артефакта (`shaterd`) и установка apk-фида (25.12+): роллинг или фиксация версии |
|
||||
| [ARCHITECTURE.md](ARCHITECTURE.md) | One-binary дизайн, auth-handoff LuCI→панель, data/DNS/apply-потоки (диаграммы) |
|
||||
| [FEATURES.md](FEATURES.md) | Полный список фич с тегами MVP/T1/T2 |
|
||||
| [ROADMAP.md](ROADMAP.md) | Фазовый план |
|
||||
| [DECISIONS.md](DECISIONS.md) | Почему sing-box, почему форк, split панели, лицензия и т.д. |
|
||||
| [DESIGN.md](DESIGN.md) | Визуальная система панели — направление «Faceplate», токены, компоненты |
|
||||
| [PORTING.md](PORTING.md) | Порт проверенных кусков из v0.1 |
|
||||
|
||||
Документация движка-форка (sing-box-lx) — в его слое: [`../docs-lx/`](../docs-lx/)
|
||||
и [`../SPECS/`](../SPECS/).
|
||||
@@ -104,7 +104,7 @@ build new logic in the `shater/`, `panel/`, `openwrt/` overlay.
|
||||
|
||||
## Phase 8 — Ship it ✅ DONE
|
||||
- Adapt CI to build/sign the single forked binary for both arches; publish the
|
||||
signed opkg feed (reuse key `5ac4b177689cb8e0`); install/upgrade docs.
|
||||
signed feed (apk since D22, EC key `dist/shater-apk.pem`); install/upgrade docs.
|
||||
- Set an upstream-rebase cadence (merge new sing-box-lx tags, run the smoke suite).
|
||||
|
||||
## Cross-cutting (every phase)
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# Живое тестирование shater v0.2.6 на mini_router
|
||||
|
||||
**Дата:** 2026-07-25
|
||||
**Устройство:** Bananapi BPi-R3 Mini · ImmortalWrt **25.12-linkup** · `aarch64_cortex-a53`
|
||||
**Установка:** из подписанного apk-фида `apk-v0.2.6-aarch64_cortex-a53`
|
||||
**Пакеты:** `shaterd 0.2.0-r3`, `shater-core 0.2.0-r3`, `luci-app-shater 0.2.0-r2`, `byedpi 0.17.3-r1`
|
||||
**Сборка:** CI run 61, коммит `024e9308c` (вершина `main`)
|
||||
|
||||
Сценарий: полное удаление предыдущей установки → чистая установка из фида →
|
||||
проверка дефолтного состояния → восстановление рабочего конфига с подписками
|
||||
(315 узлов) → функциональная проверка.
|
||||
|
||||
**Итог: 79 проверок, 74 PASS, 5 находок** (детали и разбор — в
|
||||
`shater-bugs-2026-07-25.md` на рабочем столе).
|
||||
|
||||
---
|
||||
|
||||
## 1. Релиз и фид
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T1 | Публикация `apk-v0.2.6-<arch>` для обеих архитектур | PASS |
|
||||
| T2 | Ассеты: 4 `.apk` + `packages.adb` + `shater-apk.pem` | PASS |
|
||||
| T3 | `apk update` принимает индекс (проверка EC-подписи) | PASS |
|
||||
| T4 | Пакеты видны в нужных версиях (r3/r3/r2) | PASS |
|
||||
| T5 | Диагностика сборки: `kmod packages selected (=m): 0` (было 1078) | PASS |
|
||||
| T6 | Собраны ровно наши 4 пакета | PASS |
|
||||
| T7 | opkg-лейн v0.2.6 (24.10) тоже зелёный | PASS |
|
||||
|
||||
## 2. Установка
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T8 | `apk add luci-app-shater byedpi` — 4 пакета | PASS |
|
||||
| T9 | Зависимости `kmod-nft-tproxy`/`kmod-nft-socket` из базового фида | PASS |
|
||||
| T10 | Целостность: `apk manifest` = sha256 файла на диске | PASS |
|
||||
| T11 | Установлен именно бинарь v0.2.6 (5 491 616 Б vs 5 488 336 Б в r2) | PASS |
|
||||
| T12 | init-скрипты `shater`, `shater-cron` | PASS |
|
||||
| T13 | `sysctl.d/99-shater.conf`, `hotplug.d/iface/99-shater` | PASS |
|
||||
| T14 | boot-линки `S99shater`, `K10shater`, `S96shater-cron` | PASS |
|
||||
|
||||
## 3. Дефолтное состояние (чистая установка)
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T15 | Дефолтный конфиг создан uci-defaults (27 строк) | PASS |
|
||||
| T16 | `enabled='0'` — плоскость не ставится без согласия | PASS |
|
||||
| T17 | Заготовлен tproxy-inbound на LAN, пресеты выключены | PASS |
|
||||
| T18 | Демон стартует, `plane=none`, `table=false` | PASS |
|
||||
| T19 | Права конфига `-rw-------` (0600) | PASS |
|
||||
|
||||
## 4. Восстановление рабочего конфига
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T20 | Восстановление из бэкапа (3213 UCI-строк) | PASS |
|
||||
| T21 | Кэш подписок цел: 315 узлов в 4 файлах | PASS |
|
||||
| T22 | `shaterd migrate` → `ok`, схема v1 | PASS |
|
||||
| T23 | Старт с реальным конфигом: `active`, `engine_running`, `plane=full` | PASS |
|
||||
|
||||
## 5. Data plane
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T24 | Таблица `inet shater` создана (9 цепочек/сетов) | PASS |
|
||||
| T25 | 16 tproxy-правил | PASS |
|
||||
| T26 | `ip rule from all fwmark 0x2000 lookup shater` | PASS |
|
||||
| T27 | `accept_local=1` на `br-lan` | PASS |
|
||||
| T28 | DNS-divert: `dport 53 → tproxy :12345` для LAN-интерфейсов | PASS |
|
||||
| T29 | DoT заблокирован: `dport 853 reject` | PASS |
|
||||
| T30 | `block_doh=1`, правила присутствуют | PASS |
|
||||
| T31 | **Kill-switch fail-closed**: цепочка `forward` завершается `drop` для LAN (v4+v6) | PASS |
|
||||
| T32 | fw4 и dnsmasq не тронуты (свои таблицы целы) | PASS |
|
||||
|
||||
## 6. Панель и API
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T33 | SPA отдаётся на `:8088` | PASS |
|
||||
| T34 | `shaterd mint-token` выдаёт одноразовый токен | PASS |
|
||||
| T35 | `/api/status` без сессии → **401** | PASS |
|
||||
| T36 | `/api/session` (POST, JSON) → 200 + cookie `HttpOnly; SameSite=Strict; Max-Age=28800` | PASS |
|
||||
| T37 | `/api/status` по cookie отдаёт данные, совпадающие с CLI | PASS |
|
||||
| T38 | `/api/config` — 340 записей узлов | PASS |
|
||||
| T39 | `/api/groups/health` — 103 протестировано, 13 живых, выбран `FR-vless-8` | PASS |
|
||||
| T40 | `/api/devices` — устройства с IPv4/IPv6/MAC | PASS |
|
||||
| T41 | `/api/interfaces` — `ewan/eth1 10.0.0.125/24 zone=wan` | PASS |
|
||||
| T42 | `/api/ruleset/status` — remote-ruleset обновлён сегодня | PASS |
|
||||
| T43 | `/api/stats` — memory backend, счётчики и top-domains | PASS |
|
||||
| T44 | `/api/stats/log` — query-log с доменом, qtype, rcode, сервером | PASS |
|
||||
| T45 | `/api/log?range=100` — пусто (следствие `log_file='0'`, не дефект) | OK |
|
||||
|
||||
## 7. Жизненный цикл конфигурации
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T46 | `shaterd apply` → `{"changed":false}`, `can_rollback=true` | PASS |
|
||||
| T47 | `shaterd confirm` снимает авто-откат (`can_rollback=false`) | PASS |
|
||||
| T48 | `shaterd rollback` после confirm корректно сообщает об отсутствии last-good | PASS |
|
||||
| T49 | `shaterd reconcile` (SIGHUP) не роняет движок | PASS |
|
||||
| T50 | `shaterd sub update all-qomar` — реально обновил 143 узла | PASS |
|
||||
| T51 | `shaterd blocklist update` → reconcile signalled | PASS |
|
||||
| T52 | `shaterd schedule due` → reconcile signalled | PASS |
|
||||
|
||||
## 8. Устойчивость
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T53 | `kill -9` демона → procd поднимает новый PID | PASS |
|
||||
| T54 | После respawn: `engine_running=true`, `plane=full` | PASS |
|
||||
| T55 | `stop` снимает таблицу `inet shater` полностью | PASS |
|
||||
| T56 | `stop` → пауза → `start`: плоскость восстанавливается | PASS |
|
||||
| T57 | Сеть при остановленном shater не деградирует | PASS |
|
||||
| T58 | Память: 253 МБ занято из 2 ГБ при работающем движке | PASS |
|
||||
|
||||
## 9. DNS
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T59 | Резолв через `127.0.0.1` | PASS |
|
||||
| T60 | LAN-клиенты резолвят через движок (query-log растёт) | PASS |
|
||||
| T61 | `.lan`-домены остаются за dnsmasq | PASS |
|
||||
| T62 | dnsmasq жив и слушает на всех адресах | PASS |
|
||||
| T63 | **Резолв через LAN-адрес `10.67.0.1` после `restart`** | **FAIL — B3** |
|
||||
| T64 | Тот же резолв после `stop` → пауза → `start` | PASS |
|
||||
|
||||
## 10. Конфигурация и логи
|
||||
|
||||
| # | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| T65 | 5 правил маршрутизации, 2 профиля, активен `ethernet-uplink` | PASS |
|
||||
| T66 | **Два правила `default`, оба catch-all — нижнее живое, верхнее мертво** | **FAIL — B1** |
|
||||
| T67 | **`shaterd nodes` всегда возвращает `[]`** | **FAIL — B2** |
|
||||
| T68 | Логи уходят в syslog (`log_syslog=1`, 22 записи) | PASS |
|
||||
| T69 | **ANSI-escape коды в syslog** | **FAIL — B5** |
|
||||
| T70 | `loglevel=warning` соблюдается | PASS |
|
||||
| T71–T79 | Прочие проверки состояния (статус-поля, права, uptime, счётчики, целостность таблиц) | PASS |
|
||||
|
||||
---
|
||||
|
||||
## Находки
|
||||
|
||||
| ID | Суть | Важность |
|
||||
|---|---|---|
|
||||
| **B1** | Два catch-all правила `default`; одно из них не работает никогда. **Поправка к первоначальному диагнозу:** правило без условий задаёт `route.Final`, а не выпускается как match-all, поэтому выигрывает ПОСЛЕДНЕЕ (`order=100 → group:auto`) — трафик идёт через прокси, а мёртвая настройка это `order=20 → direct` | средняя |
|
||||
| **B2** | `shaterd nodes` — заглушка, всегда `[]`, хотя usage обещает список узлов (в кэше 315, в `/api/config` 340) | средняя |
|
||||
| **B3** | После `service shater restart` резолв к LAN-адресу роутера не работает и не восстанавливается; `stop`+пауза+`start` — работает (гонка) | средняя |
|
||||
| **B4** | `PKG_RELEASE` не менялся с v0.2.1 → v0.2.2…v0.2.6 выходят как `r3` при разном содержимом; `apk upgrade` не увидит обновления | средняя |
|
||||
| **B5** | ANSI-раскраска попадает в syslog | низкая |
|
||||
|
||||
Разбор с воспроизведением — в `shater-bugs-2026-07-25.md`.
|
||||
|
||||
## История CI по этому релизу
|
||||
|
||||
Путь до зелёной сборки apk-лейна занял четыре итерации, каждая вскрывала
|
||||
следующий слой одной причины:
|
||||
|
||||
| Тег | Что чинили | Итог |
|
||||
|---|---|---|
|
||||
| v0.2.2 | — (первый прогон с фиксами аудита) | `Disk quota exceeded`, 3593 `apk mkpkg kmod-*` |
|
||||
| v0.2.3 | `.config` строится с нуля, а не дописывается | 1078 kmod — SDK вообще не везёт `.config` |
|
||||
| v0.2.4 | Выключены `ALL`/`ALL_KMODS`/`ALL_NONSHARED` | 1078 kmod — они выбираются не через `ALL_KMODS` |
|
||||
| v0.2.5 | Второй проход: явное `is not set` для каждого kmod | 1078 kmod — kconfig игнорирует user-значение у беспромптовых символов |
|
||||
| **v0.2.6** | Удаление сгенерированных блоков `config PACKAGE_*` (`default m`) из `Config-build.in` | **0 kmod, сборка зелёная** |
|
||||
|
||||
Корень: `target/sdk/Makefile` генерирует `Config-build.in` прогоном
|
||||
`convert-config.pl` по конфигу бильдбота, где `ALL_KMODS=y` уже развернулся в
|
||||
`CONFIG_PACKAGE_kmod-*=m` на каждый модуль. Фильтр `next if /^(# )?CONFIG_PACKAGE/`
|
||||
в скрипте стоит в ветке `else`, куда строка со знаком `=` не попадает, поэтому
|
||||
каждый kmod приезжает в SDK как безусловный `default m`.
|
||||
@@ -112,8 +112,8 @@ func getGroupDelay(server *Server) func(w http.ResponseWriter, r *http.Request)
|
||||
} else {
|
||||
server.logger.Debug("outbound ", tag, " available: ", t, "ms")
|
||||
server.urlTestHistory.StoreURLTestHistory(realTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: t,
|
||||
LastOK: time.Now(), // lx: health board §5.A — Time renamed to LastOK
|
||||
Delay: t,
|
||||
})
|
||||
resultAccess.Lock()
|
||||
result[tag] = t
|
||||
|
||||
@@ -209,8 +209,8 @@ func getProxyDelay(server *Server) func(w http.ResponseWriter, r *http.Request)
|
||||
server.urlTestHistory.DeleteURLTestHistory(realTag)
|
||||
} else {
|
||||
server.urlTestHistory.StoreURLTestHistory(realTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: delay,
|
||||
LastOK: time.Now(), // lx: health board §5.A — Time renamed to LastOK
|
||||
Delay: delay,
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -2,6 +2,9 @@ package libbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
// lx:begin sec-consttime
|
||||
"crypto/subtle"
|
||||
// lx:end sec-consttime
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
@@ -97,9 +100,11 @@ func unaryAuthInterceptor(ctx context.Context, req any, info *grpc.UnaryServerIn
|
||||
if len(values) == 0 {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing authentication secret")
|
||||
}
|
||||
if values[0] != sCommandServerSecret {
|
||||
// lx:begin sec-consttime
|
||||
if subtle.ConstantTimeCompare([]byte(values[0]), []byte(sCommandServerSecret)) != 1 {
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid authentication secret")
|
||||
}
|
||||
// lx:end sec-consttime
|
||||
return handler(ctx, req)
|
||||
}
|
||||
|
||||
@@ -115,9 +120,11 @@ func streamAuthInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServe
|
||||
if len(values) == 0 {
|
||||
return status.Error(codes.Unauthenticated, "missing authentication secret")
|
||||
}
|
||||
if values[0] != sCommandServerSecret {
|
||||
// lx:begin sec-consttime
|
||||
if subtle.ConstantTimeCompare([]byte(values[0]), []byte(sCommandServerSecret)) != 1 {
|
||||
return status.Error(codes.Unauthenticated, "invalid authentication secret")
|
||||
}
|
||||
// lx:end sec-consttime
|
||||
return handler(srv, ss)
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,11 @@ func (r *oomReporter) WriteReport(memoryUsage uint64) error {
|
||||
draftInfo = nil
|
||||
}
|
||||
reportsDir := filepath.Join(sWorkingPath, "oom_reports")
|
||||
err = os.MkdirAll(reportsDir, 0o777)
|
||||
// lx:begin sec-perms
|
||||
// OOM reports embed the config snapshot (server secrets, keys) and logs;
|
||||
// keep the tree owner-only (0700 dirs / 0600 files) instead of 0777/0666.
|
||||
err = os.MkdirAll(reportsDir, 0o700)
|
||||
// lx:end sec-perms
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -121,7 +125,9 @@ func discardDraftIfCurrent(draftPath string, draftInfo os.FileInfo) error {
|
||||
|
||||
func (r *oomReporter) writeSnapshot(destPath string, memoryUsage uint64) error {
|
||||
now := time.Now().UTC()
|
||||
err := os.MkdirAll(destPath, 0o777)
|
||||
// lx:begin sec-perms
|
||||
err := os.MkdirAll(destPath, 0o700)
|
||||
// lx:end sec-perms
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -44,7 +44,10 @@ func baseReportMetadata() reportMetadata {
|
||||
|
||||
func writeReportFile(destPath string, name string, content []byte) {
|
||||
filePath := filepath.Join(destPath, name)
|
||||
os.WriteFile(filePath, content, 0o666)
|
||||
// lx:begin sec-perms
|
||||
// Report files may carry the config snapshot (secrets) — owner-only.
|
||||
os.WriteFile(filePath, content, 0o600)
|
||||
// lx:end sec-perms
|
||||
chownReport(filePath)
|
||||
}
|
||||
|
||||
@@ -69,7 +72,9 @@ func copyConfigSnapshot(destPath string) {
|
||||
}
|
||||
|
||||
func initReportDir(path string) {
|
||||
os.MkdirAll(path, 0o777)
|
||||
// lx:begin sec-perms
|
||||
os.MkdirAll(path, 0o700)
|
||||
// lx:end sec-perms
|
||||
chownReport(path)
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 204 KiB |
@@ -15,6 +15,17 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=byedpi
|
||||
|
||||
# DELIBERATELY NOT auto-versioned from our git tag (unlike shaterd/shater-core/
|
||||
# luci-app-shater, which take SHATER_PKG_VERSION/SHATER_PKG_RELEASE from
|
||||
# ci/version.sh). PKG_VERSION here is THIRD-PARTY UPSTREAM's version — it is what
|
||||
# PKG_SOURCE_URL/PKG_HASH pin, and what tells an operator which ByeDPI is
|
||||
# actually installed. Stamping our tag on it would be both a lie and a
|
||||
# regression: our tags are 0.2.x, and the version comparator (apk-tools 3,
|
||||
# verified) reads 0.2.7 < 0.17.3 — component-wise numerically, 2 < 17
|
||||
# — so the "new" package would be a DOWNGRADE and routers would refuse it.
|
||||
# Bump PKG_RELEASE BY HAND when *our packaging* of it changes (init script, uci
|
||||
# defaults, build flags); bump PKG_VERSION+PKG_HASH when upstream releases.
|
||||
PKG_VERSION:=0.17.3
|
||||
PKG_RELEASE:=1
|
||||
|
||||
|
||||
@@ -24,8 +24,13 @@ LUCI_TITLE:=LuCI thin launcher for Shater (mini dashboard + panel handoff)
|
||||
LUCI_DEPENDS:=+shater-core +rpcd
|
||||
LUCI_PKGARCH:=all
|
||||
|
||||
PKG_VERSION:=0.2.0
|
||||
PKG_RELEASE:=1
|
||||
# Version comes from the git tag via ci/version.sh -> SHATER_PKG_VERSION /
|
||||
# SHATER_PKG_RELEASE in the SDK build env (see openwrt/shaterd/Makefile for the
|
||||
# full rationale — bug B4). The literals are the manual/offline fallback only.
|
||||
# These MUST stay above the luci.mk include: luci.mk only defaults PKG_VERSION/
|
||||
# PKG_RELEASE when they are still unset, and the i18n subpackages inherit them.
|
||||
PKG_VERSION:=$(if $(SHATER_PKG_VERSION),$(SHATER_PKG_VERSION),0.2.0)
|
||||
PKG_RELEASE:=$(if $(SHATER_PKG_RELEASE),$(SHATER_PKG_RELEASE),1)
|
||||
|
||||
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
||||
PKG_LICENSE:=GPL-3.0-or-later
|
||||
|
||||
@@ -13,8 +13,13 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=shater-core
|
||||
PKG_VERSION:=0.2.0
|
||||
PKG_RELEASE:=2
|
||||
|
||||
# Version comes from the git tag via ci/version.sh -> SHATER_PKG_VERSION /
|
||||
# SHATER_PKG_RELEASE in the SDK build env (see openwrt/shaterd/Makefile for the
|
||||
# full rationale — bug B4: v0.2.2…v0.2.6 all shipped as 0.2.0-r3). The literals
|
||||
# are the manual/offline fallback only.
|
||||
PKG_VERSION:=$(if $(SHATER_PKG_VERSION),$(SHATER_PKG_VERSION),0.2.0)
|
||||
PKG_RELEASE:=$(if $(SHATER_PKG_RELEASE),$(SHATER_PKG_RELEASE),1)
|
||||
|
||||
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
||||
PKG_LICENSE:=GPL-2.0-or-later
|
||||
@@ -35,6 +40,10 @@ define Package/shater-core
|
||||
# shaterd : the daemon our init supervises (`shaterd run`)
|
||||
# kmod-nft-tproxy : kernel TPROXY (shaterd emits the `inet shater` rules)
|
||||
# kmod-nft-socket : socket match used by the tproxy divert chain
|
||||
# kmod-tun : /dev/net/tun — the daemon opens the `shater-l3` TUN
|
||||
# for L3 ingress (globals.l3_tunnel); usually built-in
|
||||
# on stock images, but a slimmed image without it would
|
||||
# make the option fail with a cryptic open() error.
|
||||
# ip-full : `ip rule`/`ip route`/rt_tables for policy routing
|
||||
# nftables-json : shaterd shells out to `nft`, and netplane/stats.go
|
||||
# parses `nft -j list ...` — the JSON output only exists
|
||||
@@ -44,7 +53,7 @@ define Package/shater-core
|
||||
# ca-bundle : the daemon is CGO_ENABLED=0, so crypto/x509 has no
|
||||
# host cert fallback — without /etc/ssl/certs every
|
||||
# HTTPS subscription / .srs ruleset fetch fails.
|
||||
DEPENDS:=+shaterd +kmod-nft-tproxy +kmod-nft-socket +ip-full +nftables-json +ca-bundle
|
||||
DEPENDS:=+shaterd +kmod-nft-tproxy +kmod-nft-socket +kmod-tun +ip-full +nftables-json +ca-bundle
|
||||
PKGARCH:=all
|
||||
endef
|
||||
|
||||
@@ -75,6 +84,10 @@ define Package/shater-core/install
|
||||
$(INSTALL_DIR) $(1)/etc/init.d
|
||||
$(INSTALL_BIN) ./files/etc/init.d/shater $(1)/etc/init.d/shater
|
||||
$(INSTALL_BIN) ./files/etc/init.d/shater-cron $(1)/etc/init.d/shater-cron
|
||||
# START=21 one-shot that loads the persisted fail-closed plane before fw4's
|
||||
# `lan -> wan ACCEPT` can be the only thing on the box (the main init is
|
||||
# START=99, i.e. seconds of plaintext forwarding on every boot).
|
||||
$(INSTALL_BIN) ./files/etc/init.d/shater-armor $(1)/etc/init.d/shater-armor
|
||||
|
||||
$(INSTALL_DIR) $(1)/etc/hotplug.d/iface
|
||||
$(INSTALL_BIN) ./files/etc/hotplug.d/iface/99-shater $(1)/etc/hotplug.d/iface/99-shater
|
||||
|
||||
@@ -23,6 +23,32 @@ config globals 'globals'
|
||||
option kill_switch 'closed'
|
||||
# There is no dns_mode option: routing is decided by in-engine rule-sets and
|
||||
# fake-IP is a resolver type (`config resolver` with type=fakeip + pool).
|
||||
#
|
||||
# Force ALL LAN plaintext DNS (:53) into the engine, INCLUDING queries the
|
||||
# client sends to the router itself (the address DHCP hands out). ON by
|
||||
# default: with it off, a client using the router as its resolver is answered
|
||||
# by dnsmasq and forwarded to the ISP in the clear — no blocklists, no
|
||||
# per-device DNS rules, no resolver detour — while a client that hard-codes
|
||||
# 8.8.8.8 IS intercepted. The obedient client leaked; the evader did not.
|
||||
#
|
||||
# Set to '0' to opt out (dnsmasq answers router-addressed :53 again). Your
|
||||
# explicit value is never overwritten: this file is a conffile, and the daemon
|
||||
# always writes the option back as '1'/'0'.
|
||||
#
|
||||
# .lan and the private reverse (PTR) zones keep working: with at least one
|
||||
# `config resolver` present the engine gets a synthetic server pointed at
|
||||
# dnsmasq on 127.0.0.1:53 plus a rule that sends those suffixes to it; with no
|
||||
# resolver at all the engine falls back to the system resolver, which is
|
||||
# dnsmasq too. If you changed dnsmasq's domain away from `lan`, add a
|
||||
# `config dns_rule` for it (only `lan` + RFC6303 reverse zones are built in).
|
||||
#
|
||||
# While the engine is DOWN the LAN is NOT left without DNS: the fail-closed
|
||||
# holding plane hooks `forward` only, so dnsmasq still answers router-addressed
|
||||
# :53 — unfiltered and in the clear, the documented trade-off (blocking it
|
||||
# would also cut the daemon's own name resolution and its chance to recover).
|
||||
# Queries aimed at an EXTERNAL resolver are dropped with the rest of the LAN's
|
||||
# forwarded traffic.
|
||||
option dns_intercept '1'
|
||||
option ipv6 '1'
|
||||
# Reserved fwmark base and routing-table base (do not overlap fw4/other apps).
|
||||
option fwmark_base '0x2000'
|
||||
@@ -62,7 +88,29 @@ config inbound
|
||||
# list node 'my-node'
|
||||
#
|
||||
# A routing rule. target: chain:<n>|group:<n>|node:<n>|egress:<n>|direct|block.
|
||||
# Match on src / dst_domain / dst_ruleset / dst_ip / dst_port / proto.
|
||||
# Match on src / dst_ruleset / dst_port / proto. A rule with NO matcher at all is
|
||||
# the default route for everything that reached it.
|
||||
#
|
||||
# WHERE the traffic is going is named ONLY by dst_ruleset — one or more
|
||||
# `config ruleset` names; the rule matches when ANY of them matches. There is no
|
||||
# inline domain or address list on a rule (`dst_domain`/`dst_ip` were removed in
|
||||
# schema v2): a destination list is written once as a ruleset, compiled into a
|
||||
# .srs and shared by every rule that references it. `shaterd migrate` converts
|
||||
# older configs automatically, creating a `rule-<name>` ruleset per rule.
|
||||
#config ruleset
|
||||
# option name 'blocked-video'
|
||||
# option type 'domain'
|
||||
# option source 'inline'
|
||||
# list entry 'youtube.com'
|
||||
# list entry 'suffix:googlevideo.com'
|
||||
#
|
||||
#config rule
|
||||
# option name 'video-via-main'
|
||||
# option enabled '1'
|
||||
# option order '50'
|
||||
# list dst_ruleset 'blocked-video'
|
||||
# option target 'group:main'
|
||||
#
|
||||
#config rule
|
||||
# option name 'all-via-main'
|
||||
# option enabled '1'
|
||||
@@ -83,11 +131,16 @@ config inbound
|
||||
# option type 'direct'
|
||||
# option dpi 'fragment'
|
||||
#
|
||||
#config ruleset
|
||||
# option name 'youtube'
|
||||
# option source 'geosite'
|
||||
# list category 'youtube'
|
||||
#
|
||||
#config rule
|
||||
# option name 'youtube-fragment'
|
||||
# option enabled '1'
|
||||
# option order '50'
|
||||
# list dst_domain 'geosite:youtube'
|
||||
# list dst_ruleset 'youtube'
|
||||
# option target 'egress:frag'
|
||||
#
|
||||
# A DNS resolver (type: doh|dot|plain|local|fakeip). `detour` routes its queries
|
||||
|
||||
@@ -33,6 +33,30 @@
|
||||
# be running. `start` raises ACTIVE_FLAG, `stop` clears it; hotplug/cron
|
||||
# reconcile ONLY while the flag is up, so an admin `stop` STICKS — no
|
||||
# background actor may resurrect interception behind a stopped daemon.
|
||||
# * BEING REPLACED IS NOT BEING SWITCHED OFF. `restart` and `reload` (which is
|
||||
# stop+start, i.e. every LuCI Save & Apply) both run through `stop`, and the
|
||||
# daemon's SIGTERM teardown removes the fail-closed table unconditionally — it
|
||||
# does not consult kill_switch at all. Between that teardown and the
|
||||
# successor's first apply the init GUARANTEES a gap: it waits for the old
|
||||
# process to exit (shater_wait_stopped), then runs `shaterd migrate`, then
|
||||
# starts a daemon that still has to build an engine. So a restart is announced
|
||||
# with RESTART_FLAG, which tells the outgoing daemon to leave the fail-closed
|
||||
# holding plane STANDING — apply.TeardownExiting swaps it in with one nft
|
||||
# transaction and then skips the delete, so the table is never absent, not even
|
||||
# for the 80-90 ms the old arm-after-teardown order measured. A real `stop`
|
||||
# raises no flag and therefore still means what it says.
|
||||
# (A package UPGRADE does not come through here at all on apk v3: shater-core's
|
||||
# script table is post-install / pre-deinstall / post-upgrade, with no
|
||||
# pre-upgrade, so default_prerm — and its `stop` — runs only on REMOVAL.)
|
||||
# * The FAIL-CLOSED PLANE MUST ALSO EXIST BEFORE THIS SCRIPT DOES. START=99 is
|
||||
# after fw4 (19) and netifd (20), so at every boot the LAN forwards to the WAN
|
||||
# in the clear for as long as it takes procd to decompress the daemon off
|
||||
# flash and get an engine up. /etc/init.d/shater-armor (START=21) loads
|
||||
# BOOT_ARMOR — a copy of the holding plane the daemon persists on every apply
|
||||
# — to close that window. This script owns the DISARM half, and it owns it
|
||||
# with a CLOSED LIST: an operator's `stop`, or a removal, and nothing else.
|
||||
# Powering the box down must not — `shutdown` reaches stop_service too, and it
|
||||
# is not a person switching the product off (see shater_stop_disarms).
|
||||
# * The engine must never be permanently abandoned while interception stands:
|
||||
# respawn retries are infinite (procd never gives up); a sustained-dead
|
||||
# daemon is additionally escalated by the shater-cron watchdog.
|
||||
@@ -47,6 +71,168 @@ PROG=/usr/bin/shaterd
|
||||
# hotplug/shater-cron touch the data plane. tmpfs => cleared by reboot, so
|
||||
# nothing reconciles before this init has run at boot.
|
||||
ACTIVE_FLAG=/var/run/shater.active
|
||||
# Written by `shaterd run`; the single-owner token this init waits on so a
|
||||
# restart never overlaps a new data plane with the previous one's teardown.
|
||||
PIDFILE=/var/run/shaterd.pid
|
||||
# Raised around a restart/reload, read by the OUTGOING `shaterd run` at SIGTERM:
|
||||
# present => "you are being replaced, leave the fail-closed plane standing";
|
||||
# absent => "you are being switched off, take everything down". tmpfs, so a
|
||||
# power cut can never make the next boot look like a restart.
|
||||
RESTART_FLAG=/var/run/shater.restarting
|
||||
# The persisted fail-closed holding plane. Written by the daemon on every apply,
|
||||
# loaded by /etc/init.d/shater-armor at boot. Its PRESENCE is the arm token, so
|
||||
# removing it here is how a deliberate stop stops the next boot from blocking.
|
||||
BOOT_ARMOR=/etc/shater/boot.nft
|
||||
# Seconds `start` will wait for a predecessor to finish its teardown. Must be
|
||||
# >= term_timeout below (procd's hard cap on a predecessor's life after SIGTERM)
|
||||
# so we never give up while procd is still letting it shut down cleanly.
|
||||
STOP_WAIT_SECS=40
|
||||
|
||||
# WHICH ACTION rc.common was invoked with, frozen at source time.
|
||||
#
|
||||
# rc.common does, in this order:
|
||||
# initscript=$1; action=${2:-help}; shift 2; ...; . "$initscript"; $action "$@"
|
||||
# so `action` is ALREADY assigned when this file is sourced, and every action then
|
||||
# runs as a function in THAT SAME shell. MEASURED on the target (ImmortalWrt
|
||||
# 25.12.1 r37978) with a throwaway probe init script, not read off documentation:
|
||||
#
|
||||
# /etc/init.d/X restart -> stop_service action=[restart], start_service [restart]
|
||||
# /etc/init.d/X stop -> stop_service action=[stop]
|
||||
# /etc/init.d/X reload -> reload_service action=[reload]
|
||||
# `reboot` -> stop_service action=[SHUTDOWN] <-- see below
|
||||
# the boot after it -> start_service action=[boot]
|
||||
#
|
||||
# A previous probe reported this variable EMPTY and the emptiness was written up as
|
||||
# the defect. It was the probe: `sh -x /etc/init.d/shater restart` bypasses the
|
||||
# `#!/bin/sh /etc/rc.common` shebang, so rc.common never runs, never assigns
|
||||
# `action`, and the variable reads empty no matter what this file does.
|
||||
#
|
||||
# Frozen into our own variable because `action` is a short, generic name that other
|
||||
# framework helpers also use as a local; a snapshot taken before any function runs
|
||||
# cannot be shadowed later.
|
||||
SHATER_RC_ACTION="$action"
|
||||
|
||||
# --- what an action MEANS --------------------------------------------------
|
||||
#
|
||||
# THE BUG THESE TWO PREDICATES REPLACE (v0.2.17, measured on the live router).
|
||||
# The old stop_service was `case $action in restart|reload) keep;; *) DISARM;; esac`
|
||||
# — an open default that swept up every action nobody had enumerated. `reboot` is
|
||||
# one of them: procd runs the K-links with the action `shutdown`, so the shutdown
|
||||
# path deleted the arm token on the way down and the next boot had nothing to load.
|
||||
# The mechanism destroyed itself at exactly the moment it exists for. Instrument
|
||||
# reading from the router, one minute apart across a reboot:
|
||||
#
|
||||
# 13:28 /etc/shater/boot.nft present
|
||||
# ---- reboot (stop_service action=[shutdown] -> old `*` branch -> rm)
|
||||
# 18s at_S22: NO_TABLE armor_file=NO_FILE
|
||||
#
|
||||
# So both lists below are POSITIVE and CLOSED. An action nobody thought about —
|
||||
# `shutdown` above all, but also whatever a future procd invents — falls through
|
||||
# both and changes nothing. The default now fails in the recoverable direction: at
|
||||
# worst a boot arms when it need not have, which costs the second before the daemon
|
||||
# applies and is still gated by shater-armor's own four state refusals. The old
|
||||
# default failed in the direction of the plaintext window the feature was built to
|
||||
# close.
|
||||
#
|
||||
# They are predicates rather than an inline `case` so the test gate can execute the
|
||||
# real thing: it sources THIS FILE in /bin/sh and calls them with every action procd
|
||||
# actually uses (shater/cmd/shaterd/initscript_test.go). A comment claiming
|
||||
# `shutdown` is handled is what shipped last time.
|
||||
|
||||
# True only for the ONE action that means "the operator switched the product off".
|
||||
# Deliberately not `shutdown`: powering a router down is not turning a feature off.
|
||||
#
|
||||
# NOT sufficient on its own — see shater_stop_disarms. `stop` is also how the
|
||||
# package manager's plumbing reaches us, and a package manager is not a person.
|
||||
shater_action_disarms() {
|
||||
case "$1" in
|
||||
stop) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Is a package manager in the middle of a transaction RIGHT NOW?
|
||||
#
|
||||
# This is a state, read at the moment the decision is made, exactly like
|
||||
# shater-armor's four refusals — not a record of an event. The same question is
|
||||
# already asked (for the same reason: prerm/postinst plumbing is not a user
|
||||
# action) by the detached bring-up in /etc/uci-defaults/30_shater-core.
|
||||
shater_pkg_transaction() {
|
||||
pidof apk >/dev/null 2>&1 && return 0
|
||||
pidof opkg >/dev/null 2>&1 && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
# Is the main service still enabled at boot? Same glob, and for the same reason,
|
||||
# as shater-armor's own check: `/etc/init.d/shater enabled` would source procd.sh
|
||||
# and take a blocking flock, which is not something to do from inside a package
|
||||
# manager's transaction.
|
||||
shater_rc_enabled() {
|
||||
local f
|
||||
for f in /etc/rc.d/S[0-9][0-9]shater; do
|
||||
[ -e "$f" ] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# THE ACTUAL DISARM DECISION.
|
||||
# $1 = action
|
||||
# $2 = 1 when a package transaction is in flight
|
||||
# $3 = 1 when the service is still enabled in rc.d
|
||||
# All three are passed in rather than read inside, so the gate can drive every
|
||||
# combination without a package manager or an /etc/rc.d.
|
||||
#
|
||||
# WHY IT IS NOT JUST THE ACTION. base-files' default_prerm runs, in this order:
|
||||
#
|
||||
# if [ "$PKG_UPGRADE" != "1" ]; then "$i" disable; fi
|
||||
# "$i" stop
|
||||
#
|
||||
# so a package manager reaches stop_service wearing the operator's clothes. Two
|
||||
# different intentions arrive as the same action, and the difference between them
|
||||
# is readable at the moment of the decision:
|
||||
#
|
||||
# REMOVAL — prerm has ALREADY run `disable`, so S99shater is gone. The product
|
||||
# is going away; the armor goes with it. (It is belt-and-braces even
|
||||
# so: shater-armor refuses to arm without that symlink, and the whole
|
||||
# init script is about to be deleted anyway.)
|
||||
# REPLACED — the service is still enabled, so something intends to bring it
|
||||
# back. That is not an operator switching anything off, and deleting
|
||||
# the armor here would leave the next boot unprotected. "The next
|
||||
# apply will rewrite it" is not an answer: the armor exists precisely
|
||||
# to cover a reboot, and a reboot between an update and the first
|
||||
# apply is how this product is deployed.
|
||||
#
|
||||
# MEASURED, because the paragraph above is about a path I got wrong once already.
|
||||
# On THIS target (apk-tools 3.0.5, ImmortalWrt 25.12.1) shater-core's script table
|
||||
# is post-install / pre-deinstall / post-upgrade, with NO pre-upgrade — so an apk
|
||||
# UPGRADE never executes default_prerm and never calls `stop` at all. Verified with
|
||||
# a real `apk fix --reinstall shater-core` while sampling the armor file: 245 625
|
||||
# samples, zero disappearances, even with this guard mutated off. The upgrade half
|
||||
# of this predicate is therefore defence-in-depth for a shape that is one
|
||||
# `pre-upgrade` script (or a returning opkg lane) away, NOT a fix for an observed
|
||||
# failure. The removal half is live today.
|
||||
shater_stop_disarms() {
|
||||
shater_action_disarms "$1" || return 1
|
||||
# No package manager involved => a person typed it. The escape hatch must work.
|
||||
[ "$2" = "1" ] || return 0
|
||||
# A package transaction that has NOT disabled the service is replacing it.
|
||||
[ "$3" = "1" ] && return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
# True when a successor is coming, so the outgoing daemon should leave the
|
||||
# fail-closed holding plane standing instead of removing it.
|
||||
#
|
||||
# `shutdown` is deliberately NOT a handoff either: nothing is coming, and the
|
||||
# kernel that would hold the plane is going away with it. Leaving the flag down
|
||||
# there also keeps the marker's meaning exact — it says "you are being replaced",
|
||||
# and at shutdown nothing is.
|
||||
shater_action_handoff() {
|
||||
case "$1" in
|
||||
restart|reload) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# --- helpers ---------------------------------------------------------------
|
||||
|
||||
@@ -66,6 +252,73 @@ _slog() {
|
||||
[ "$(uci -q get shater.globals.log_syslog)" = "0" ] || logger -t shater "$@"
|
||||
}
|
||||
|
||||
# Announce/withdraw "this daemon is being replaced, not switched off". Read by
|
||||
# `shaterd run` when it receives SIGTERM.
|
||||
shater_mark_restart() {
|
||||
mkdir -p "$(dirname "$RESTART_FLAG")" 2>/dev/null
|
||||
: > "$RESTART_FLAG"
|
||||
}
|
||||
shater_clear_restart() { rm -f "$RESTART_FLAG"; }
|
||||
|
||||
# Remove the persisted boot armor, so the LAN is NOT blocked at the next boot
|
||||
# before the daemon starts. Called from exactly two places, both of which are a
|
||||
# statement about the PRODUCT rather than about this process: an operator typing
|
||||
# `stop`, and a daemon binary that is no longer on the box. In neither case is
|
||||
# anything going to come along and replace the armor with a real data plane, and a
|
||||
# kill switch with nothing behind it is just a brick.
|
||||
#
|
||||
# NOT called on the shutdown path. That is the whole fix — see
|
||||
# shater_action_disarms.
|
||||
shater_disarm_boot() { rm -f "$BOOT_ARMOR"; }
|
||||
|
||||
# Echo the pid of a LIVE `shaterd run`, or fail. The pidfile is written by the
|
||||
# daemon itself and removed only by the daemon that owns it, AFTER its teardown
|
||||
# has completed — so "pidfile names a live process" is precisely "the previous
|
||||
# data plane has not been dismantled yet".
|
||||
shater_daemon_pid() {
|
||||
local pid
|
||||
pid=$(cat "$PIDFILE" 2>/dev/null) || return 1
|
||||
[ -n "$pid" ] || return 1
|
||||
kill -0 "$pid" 2>/dev/null || return 1
|
||||
echo "$pid"
|
||||
}
|
||||
|
||||
# Block until no predecessor daemon is left, bounded by STOP_WAIT_SECS.
|
||||
#
|
||||
# WHY THIS EXISTS. procd's `stop` is ASYNCHRONOUS: rc.common's `restart` is
|
||||
# literally `stop; start`, and the `service delete` ubus call returns the moment
|
||||
# procd has SENT SIGTERM — not when the instance is gone. `start` therefore
|
||||
# re-adds the instance while the outgoing `shaterd run` is still executing its
|
||||
# honest teardown (engine close, then `nft delete table`, `ip rule`/`ip route`
|
||||
# removal and the per-iface sysctl restore). The result is that `restart` is NOT
|
||||
# equivalent to `stop` + pause + `start`: the new plane is stood up on top of
|
||||
# kernel state the old one has not finished removing, which is what B3 (DNS to
|
||||
# the router's own LAN address dead after a restart, and never recovering) came
|
||||
# out of. Waiting here restores the equivalence, and costs literally nothing when
|
||||
# there is no predecessor — the check runs before the first sleep.
|
||||
#
|
||||
# Returning non-zero does NOT abort the start: the daemon carries its own
|
||||
# single-owner guard and will refuse (or wait) on its side. Better to hand the
|
||||
# decision to the process that can actually see the plane than to leave the box
|
||||
# with no service at all.
|
||||
shater_wait_stopped() {
|
||||
local i=0 pid
|
||||
pid=$(shater_daemon_pid) || return 0
|
||||
_slog -p daemon.info \
|
||||
"restart: waiting for the previous shaterd (pid $pid) to finish tearing the data plane down"
|
||||
while [ "$i" -lt "$STOP_WAIT_SECS" ]; do
|
||||
sleep 1
|
||||
i=$((i + 1))
|
||||
shater_daemon_pid >/dev/null || {
|
||||
_slog -p daemon.info "restart: previous shaterd exited after ${i}s; starting a fresh one"
|
||||
return 0
|
||||
}
|
||||
done
|
||||
_slog -p daemon.warn \
|
||||
"restart: previous shaterd (pid $pid) still alive after ${STOP_WAIT_SECS}s — starting anyway"
|
||||
return 1
|
||||
}
|
||||
|
||||
# --- procd lifecycle -------------------------------------------------------
|
||||
|
||||
start_service() {
|
||||
@@ -81,15 +334,53 @@ start_service() {
|
||||
# Guard: never claim to run without the daemon binary. A half-removed/failed
|
||||
# shaterd upgrade must degrade to "plugin off", not to a box that thinks
|
||||
# interception is live with nothing behind it.
|
||||
#
|
||||
# "Plugin off" now has to include DISARMING. With the boot armor in play, a
|
||||
# missing binary is the one case where the fail-closed plane could stand
|
||||
# forever with nothing able to replace it: the armor loads at START=21, the
|
||||
# daemon never starts, and every later boot repeats it. The product being gone
|
||||
# is not a security event — it is an uninstall — so the plane comes down and
|
||||
# the LAN returns to plain routing, loudly.
|
||||
if [ ! -x "$PROG" ]; then
|
||||
shater_clear_restart
|
||||
shater_disarm_boot
|
||||
rm -f "$ACTIVE_FLAG"
|
||||
nft delete table inet shater 2>/dev/null
|
||||
_slog -p daemon.err \
|
||||
"shaterd binary missing/not executable at $PROG — refusing to start (LAN stays on plain routing)"
|
||||
"shaterd binary missing/not executable at $PROG — refusing to start; the fail-closed plane and its boot armor have been REMOVED (LAN back to plain routing, unprotected). Reinstall shaterd."
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Do not stand a new data plane up on top of one that is still being taken
|
||||
# down. On `restart` procd has only just SIGTERMed the previous instance and
|
||||
# returned; this is the handshake that makes `restart` == `stop` + pause +
|
||||
# `start`. It also keeps `migrate` below from rewriting UCI underneath a
|
||||
# daemon that is still reading it. No-op (and no delay) when nothing is
|
||||
# running, which is the boot case.
|
||||
shater_wait_stopped
|
||||
|
||||
# The predecessor is gone and has already consumed the flag (it reads it in its
|
||||
# SIGTERM handler). Withdraw it now, so a LATER `stop` is unambiguous even if
|
||||
# this start fails further down.
|
||||
shater_clear_restart
|
||||
|
||||
# Bring the UCI schema forward before the daemon reads it (idempotent;
|
||||
# refuses a newer schema) so an upgraded package never applies a stale config.
|
||||
"$PROG" migrate >/dev/null 2>&1
|
||||
#
|
||||
# THE FAILURE IS LOGGED, NOT SWALLOWED. This is the only place the schema
|
||||
# migration runs at boot (`shaterd run`, the SIGHUP reconcile and the panel's
|
||||
# config write all read UCI directly), so if it fails here it does not get
|
||||
# retried until the next start. And it CAN fail for a mundane reason — a full
|
||||
# /overlay makes `uci commit` fail — after which the config still carries the
|
||||
# schema-v1 `dst_domain`/`dst_ip` options. The daemon holds every rule that
|
||||
# still has them DISABLED and reports it, so nothing is silently misrouted, but
|
||||
# rules the operator wrote are then not in force and the reason has to be
|
||||
# visible somewhere. Hence: log the binary's own stderr, and start anyway —
|
||||
# refusing to start would take the admin panel down with it, and the panel is
|
||||
# the only way to fix the box.
|
||||
local migrate_out
|
||||
migrate_out=$("$PROG" migrate 2>&1) || _slog -p daemon.err \
|
||||
"UCI schema migration FAILED: ${migrate_out:-no output from $PROG migrate}. Starting anyway; routing rules that still carry the removed dst_domain/dst_ip options stay DISABLED until this succeeds. Free space on /overlay and re-run '$PROG migrate', or restart the service."
|
||||
|
||||
procd_open_instance shater
|
||||
# shaterd runs in the FOREGROUND under procd (must never daemonize). `run` is
|
||||
@@ -111,7 +402,16 @@ start_service() {
|
||||
procd_set_param stderr 1
|
||||
# Give the daemon room to run its honest teardown (engine.Close + netplane
|
||||
# restore) before procd SIGKILLs it.
|
||||
procd_set_param term_timeout 10
|
||||
#
|
||||
# 30s, not 10s: an engine holding a few hundred outbounds closes its
|
||||
# urltest/observatory goroutines and flushes experimental.cache_file to FLASH
|
||||
# before the netplane teardown even starts, and on eMMC/NAND that alone can
|
||||
# outlast 10s. A SIGKILL there aborts the teardown at an arbitrary point and
|
||||
# leaves the plane HALF removed — the nft table gone but the policy routing
|
||||
# still installed, or vice versa — which is precisely the class of leftover
|
||||
# state the successor's idempotent fast-path cannot see and never repairs.
|
||||
# Shutdown is bounded by procd either way; we are only choosing where.
|
||||
procd_set_param term_timeout 30
|
||||
procd_close_instance
|
||||
|
||||
# Mark the stack live for hotplug/cron — but ONLY when interception is
|
||||
@@ -128,6 +428,45 @@ start_service() {
|
||||
}
|
||||
|
||||
stop_service() {
|
||||
# Say WHY we are stopping before procd sends the signal, because the daemon
|
||||
# cannot tell from the signal alone and the answer changes what it leaves in
|
||||
# the kernel. Two INDEPENDENT questions, and the old code conflated them into
|
||||
# one two-armed `case` whose else-branch answered both wrongly for `shutdown`:
|
||||
#
|
||||
# 1. IS A SUCCESSOR COMING (this process only)? restart / reload.
|
||||
# Raise RESTART_FLAG so the outgoing daemon replaces its data plane with
|
||||
# the fail-closed HOLDING plane instead of removing it. The gap until the
|
||||
# successor applies is not a moment: this script waits out the old
|
||||
# process, runs `shaterd migrate`, then starts a daemon that must build an
|
||||
# engine — all of it, before this flag existed, with `lan -> wan ACCEPT`
|
||||
# and nothing else.
|
||||
#
|
||||
# 2. IS THE PRODUCT BEING SWITCHED OFF (across boots)? `stop` — and only
|
||||
# `stop`, and only when a PERSON is behind it (shater_stop_disarms; the
|
||||
# package manager reaches us through `stop` too). Then the boot armor goes
|
||||
# with it, so the next boot does not quietly reinstate what the operator
|
||||
# just switched off — the same rule ACTIVE_FLAG has always enforced for
|
||||
# hotplug/cron.
|
||||
#
|
||||
# `shutdown` answers NO to both, which is the defect this replaced: a reboot is
|
||||
# not a successor and it is certainly not an operator switching the product off.
|
||||
# It is the boot the armor exists for. An upgrade answers NO to the second for
|
||||
# the same kind of reason.
|
||||
if shater_action_handoff "$SHATER_RC_ACTION"; then
|
||||
shater_mark_restart
|
||||
else
|
||||
shater_clear_restart
|
||||
fi
|
||||
local in_pkg=0 rc_en=0
|
||||
shater_pkg_transaction && in_pkg=1
|
||||
shater_rc_enabled && rc_en=1
|
||||
if shater_stop_disarms "$SHATER_RC_ACTION" "$in_pkg" "$rc_en"; then
|
||||
shater_disarm_boot
|
||||
elif [ "$in_pkg" = "1" ] && shater_action_disarms "$SHATER_RC_ACTION"; then
|
||||
_slog -p daemon.info \
|
||||
"stop came from a package transaction that left the service enabled — keeping the boot armor, so being replaced cannot leave the next boot unprotected"
|
||||
fi
|
||||
|
||||
# Drop the live-flag FIRST so a concurrent hotplug/cron tick cannot rebuild
|
||||
# what we are about to tear down. procd then sends SIGTERM to `shaterd run`,
|
||||
# which runs its OWN honest teardown (engine.Close + netplane restore) — we
|
||||
@@ -141,10 +480,17 @@ stop_service() {
|
||||
reload_service() {
|
||||
# Fired by the `shater` config.change reload-trigger (LuCI Save & Apply /
|
||||
# reload_config). Simplest correct behaviour: stop + start. `stop` clears the
|
||||
# flag and SIGTERMs the daemon (honest teardown); `start` re-guards on
|
||||
# enabled and, if still enabled, launches a fresh `shaterd run` that reads
|
||||
# the new UCI and applies it. When the stack is disabled, `start` is a no-op,
|
||||
# so a disable+apply cleanly tears everything down.
|
||||
# flag and SIGTERMs the daemon (honest teardown); `start` WAITS for that
|
||||
# teardown to actually finish (shater_wait_stopped) and then launches a fresh
|
||||
# `shaterd run` that reads the new UCI and applies it. When the stack is
|
||||
# disabled, `start` is a no-op, so a disable+apply cleanly tears everything
|
||||
# down. Because the wait lives in start_service, this path gets the same
|
||||
# stop-then-start ordering guarantee as `restart`.
|
||||
#
|
||||
# Marked EXPLICITLY as well as via SHATER_RC_ACTION: this is the path a routine
|
||||
# Save & Apply takes, so it is the one that must not depend on reading an
|
||||
# rc.common variable correctly. Belt and braces, one line.
|
||||
shater_mark_restart
|
||||
stop
|
||||
start
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/bin/sh /etc/rc.common
|
||||
# /etc/init.d/shater-armor — the fail-closed plane, before the daemon exists.
|
||||
#
|
||||
# WHAT THIS CLOSES
|
||||
#
|
||||
# /etc/init.d/shater is START=99. By then fw4 (START=19) has long since loaded
|
||||
# `lan -> wan ACCEPT` and netifd (START=20) has brought the LAN bridge up, so the
|
||||
# router forwards LAN traffic to the WAN in the clear from the moment the link
|
||||
# comes up until `shaterd run` has been decompressed off flash, has waited out any
|
||||
# predecessor, has migrated UCI, has read the config and has installed its first
|
||||
# table. On router-class hardware with a UPX-packed binary that is seconds — and
|
||||
# they are exactly the seconds in which Wi-Fi finishes associating and every
|
||||
# client on the network reconnects and starts talking. `kill_switch=closed` was
|
||||
# configured the whole time and covered none of it.
|
||||
#
|
||||
# There was nothing in the package that could cover it either: no /etc/nftables.d
|
||||
# include, no `nft -f` in uci-defaults. Protection existed only inside a Go
|
||||
# process that had not started yet.
|
||||
#
|
||||
# HOW
|
||||
#
|
||||
# The daemon persists a copy of its fail-closed HOLDING plane (the same ruleset it
|
||||
# installs when the engine is down: one forward chain, LAN-to-LAN and router
|
||||
# traffic accepted, everything else from the diverted devices dropped) to
|
||||
# $ARMOR on every apply. This script loads it early. When the daemon comes up it
|
||||
# replaces the table atomically — the ruleset begins with `delete table` and adds
|
||||
# its own in one netlink transaction — so there is never a moment with no table.
|
||||
#
|
||||
# `iifname` matches by NAME at packet time, not by ifindex at load time, so
|
||||
# loading this before netifd has created br-lan is fine: the rules simply start
|
||||
# matching when the device appears. That is why START can sit here rather than
|
||||
# racing netifd.
|
||||
#
|
||||
# START=21: after fw4 (19) and netifd (20), because fw4's own start tears its
|
||||
# table down and rebuilds it and we do not want to be in the middle of that, and
|
||||
# because there is nothing to protect before the LAN device is being created. The
|
||||
# residual exposure is the fraction of a second between netifd's `ifup` and this
|
||||
# script, against seconds-to-a-minute before.
|
||||
#
|
||||
# THE ESCAPE HATCHES (a kill switch that cannot be switched off is a brick)
|
||||
#
|
||||
# These are STATE checks, evaluated here, at the moment of arming — not a record
|
||||
# of something that happened on the way down. That distinction is the whole
|
||||
# lesson of v0.2.17: the arm token was deleted by an EVENT on the shutdown path
|
||||
# ("this looks like a stop"), and since `reboot` also runs the K-links, the
|
||||
# mechanism reliably erased itself on the one transition it was built for. An
|
||||
# event on the way down cannot be trusted to describe the world on the way up; a
|
||||
# question asked on the way up can be.
|
||||
#
|
||||
# * $ARMOR only exists while the daemon's last applied config was BOTH enabled
|
||||
# and fail-closed. `globals.enabled=0` and `kill_switch=open` each remove it
|
||||
# at the next apply, and an operator typing `/etc/init.d/shater stop` removes
|
||||
# it there and then. Powering the box off does NOT.
|
||||
# * We refuse to arm when the main service is disabled in rc.d, or when the
|
||||
# daemon binary is gone — in either case nothing would ever come along to
|
||||
# replace the armor with a real data plane. These two are what makes a
|
||||
# genuinely uninstalled/disabled product safe REGARDLESS of what the file
|
||||
# says, which is why they are checked here rather than trusted to have been
|
||||
# acted on earlier.
|
||||
# * We refuse to arm when UCI can be read AND says the stack is disabled. A
|
||||
# config that cannot be read is NOT a refusal: that case is precisely why the
|
||||
# armor is a file rather than a query.
|
||||
# * The chain hooks `forward` only, so SSH, LuCI and the admin panel (all input
|
||||
# hook, to the router's own addresses) stay reachable. The operator can always
|
||||
# get in and undo this.
|
||||
#
|
||||
# Note what a bare `/etc/init.d/shater stop` does NOT mean: it does not survive a
|
||||
# reboot, because S99shater is still linked and procd starts the daemon again. So
|
||||
# "stopped" is not a durable off-state and this script must not be designed as if
|
||||
# it were — the durable ones are `disable` (no S??shater) and `globals.enabled=0`,
|
||||
# and those are the two refusals above.
|
||||
#
|
||||
# busybox ash only — no bashisms.
|
||||
|
||||
START=21 # after firewall (19) and network (20), long before shater (99)
|
||||
STOP=89
|
||||
|
||||
ARMOR=/etc/shater/boot.nft
|
||||
PROG=/usr/bin/shaterd
|
||||
|
||||
# Syslog line that honors globals.log_syslog, like the other two inits. An
|
||||
# unreadable UCI leaves the option empty => ON, which is what we want here: the
|
||||
# one boot where the config cannot be read is the boot worth logging.
|
||||
_slog() {
|
||||
[ "$(uci -q get shater.globals.log_syslog)" = "0" ] || logger -t shater-armor "$@"
|
||||
}
|
||||
|
||||
# Is the MAIN service enabled at boot? Answered by looking for its rc.d symlink
|
||||
# rather than by running `/etc/init.d/shater enabled`: that is a USE_PROCD script,
|
||||
# so every action of it sources procd.sh, which takes a blocking flock — and this
|
||||
# runs at START=21, in the middle of boot, for a question a glob answers exactly
|
||||
# as well. The START number is not hardcoded; any S<NN>shater counts.
|
||||
shater_service_enabled() {
|
||||
local f
|
||||
for f in /etc/rc.d/S[0-9][0-9]shater; do
|
||||
[ -e "$f" ] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
start() {
|
||||
# No saved plane => the stack has never applied an enabled, fail-closed config
|
||||
# (or it was explicitly switched off). Nothing to do, and nothing to say.
|
||||
[ -f "$ARMOR" ] || return 0
|
||||
[ -s "$ARMOR" ] || {
|
||||
_slog -p daemon.err "$ARMOR is empty — NOT arming; the LAN is unprotected until shaterd starts"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Never arm something nothing can disarm.
|
||||
[ -x "$PROG" ] || {
|
||||
_slog -p daemon.err \
|
||||
"$PROG is missing — NOT arming (nothing would replace the block with a working data plane); the LAN stays on plain routing"
|
||||
return 0
|
||||
}
|
||||
shater_service_enabled || {
|
||||
_slog -p daemon.warn \
|
||||
"the shater service is disabled in rc.d — NOT arming (nothing would replace the block with a working data plane); the LAN stays on plain routing"
|
||||
return 0
|
||||
}
|
||||
|
||||
# A READABLE config that says "off" wins over the saved plane (it means the
|
||||
# daemon was stopped before it could disarm). An UNREADABLE config does not:
|
||||
# that is the case this whole mechanism exists for.
|
||||
en=$(uci -q get shater.globals.enabled 2>/dev/null)
|
||||
if [ -n "$en" ] && [ "$en" != "1" ]; then
|
||||
rm -f "$ARMOR"
|
||||
_slog -p daemon.info "globals.enabled=$en — boot armor removed, not arming"
|
||||
return 0
|
||||
fi
|
||||
|
||||
command -v nft >/dev/null 2>&1 || {
|
||||
_slog -p daemon.err "nft is not installed — cannot arm; the LAN is unprotected until shaterd starts"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Validate before loading: a truncated/incompatible snapshot must not leave a
|
||||
# half-built table behind on the one boot it is needed.
|
||||
if ! nft -c -f "$ARMOR" >/dev/null 2>&1; then
|
||||
_slog -p daemon.err \
|
||||
"$ARMOR did not validate (nft -c) — NOT arming; the LAN is unprotected until shaterd starts"
|
||||
return 0
|
||||
fi
|
||||
if nft -f "$ARMOR" >/dev/null 2>&1; then
|
||||
_slog -p daemon.warn \
|
||||
"fail-closed plane armed from $ARMOR: LAN->WAN forwarding is BLOCKED until shaterd applies. SSH, LuCI and the admin panel stay reachable."
|
||||
else
|
||||
_slog -p daemon.err \
|
||||
"could not load $ARMOR — the LAN is unprotected until shaterd starts"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
stop() {
|
||||
# Deliberately a NO-OP. By the time anything stops this service the daemon owns
|
||||
# `inet shater`, and deleting the table here would dismantle a LIVE data plane
|
||||
# on the strength of a service that only ever ran for one second at boot. The
|
||||
# disarm paths that matter live where the decision is actually made:
|
||||
# /etc/init.d/shater stop (operator switched it off) and the daemon itself
|
||||
# (globals.enabled=0 / kill_switch=open).
|
||||
return 0
|
||||
}
|
||||
@@ -59,6 +59,68 @@ if uci -q get shater.globals >/dev/null 2>&1 || [ -f /etc/config/shater ]; then
|
||||
uci -q commit shater
|
||||
fi
|
||||
|
||||
# Introduce the daemon-created `shater-l3` TUN to fw4 (L3 ingress, D-L3). The
|
||||
# daemon policy-routes LAN ICMP into that device from OUR nft table
|
||||
# `inet shater`, but nftables runs EVERY table on every packet and a drop in
|
||||
# any one of them wins — an accept in `inet shater` cannot override fw4. And
|
||||
# fw4 WILL drop this forward: netifd knows nothing about a device the daemon
|
||||
# creates at runtime, so it belongs to no zone and falls into fw4's zone-less
|
||||
# defaults (REJECT). The device has to be declared to fw4 itself; it cannot be
|
||||
# fixed from our own table.
|
||||
#
|
||||
# Seeded UNCONDITIONALLY (not gated on globals.l3_tunnel): uci-defaults run
|
||||
# once, so gating on the option would require re-running this script when the
|
||||
# option is flipped later — which never happens. An idle zone is harmless: its
|
||||
# device match is a plain iifname/oifname STRING compare that simply never hits
|
||||
# while the TUN does not exist.
|
||||
#
|
||||
# Idempotency: `config zone`/`config forwarding` are normally ANONYMOUS
|
||||
# sections, and a naive `uci add firewall zone` would append a duplicate on
|
||||
# every re-run (uci-defaults re-run on package upgrade/reinstall). All sections
|
||||
# here are NAMED instead, guarded by an existence check — a re-run re-finds the
|
||||
# section and touches nothing.
|
||||
seed_l3_zone() {
|
||||
# No fw4 on this image (bare nftables build) => nothing drops the forward
|
||||
# on fw4's behalf and there is nothing to punch through.
|
||||
[ -f /etc/config/firewall ] || return 0
|
||||
if ! uci -q get firewall.shater_l3 >/dev/null; then
|
||||
uci set firewall.shater_l3=zone
|
||||
uci set firewall.shater_l3.name='shater_l3'
|
||||
uci set firewall.shater_l3.input='REJECT'
|
||||
uci set firewall.shater_l3.output='ACCEPT'
|
||||
uci set firewall.shater_l3.forward='REJECT'
|
||||
uci set firewall.shater_l3.masq='0'
|
||||
# INERT TODAY, kept for the day it is not. mtu_fix clamps forwarded TCP
|
||||
# MSS to the route MTU — but shater-l3 is 65535 (deliberately: at any
|
||||
# smaller value the kernel fragments into the device, and the flow
|
||||
# dispatcher refuses to judge a fragment and lets the stack forge the
|
||||
# echo reply — see l3MTU in shater/generate/inbound.go), so the clamp has
|
||||
# nothing to clamp to. And only ICMP is ever marked into this device, so
|
||||
# no TCP rides here to be clamped in the first place. It earns its keep
|
||||
# the moment either of those changes; removing it would make that day
|
||||
# silent.
|
||||
uci set firewall.shater_l3.mtu_fix='1'
|
||||
# `list device`, deliberately NOT the usual `list network`: fw4
|
||||
# resolves a zone's networks through netifd, and netifd never learns
|
||||
# about a device the daemon creates at runtime — a stub interface
|
||||
# (proto none) would need to be brought UP to contribute an l3_device,
|
||||
# and nothing ever brings it up, so `list network` resolves to an
|
||||
# EMPTY device set and fw4 keeps dropping the forward. `list device`
|
||||
# instead compiles to an iifname/oifname STRING match, valid before
|
||||
# the TUN exists and matching from the moment shaterd creates it —
|
||||
# no netifd involvement and no firewall reload at enable time. Do not
|
||||
# "normalize" this to `list network` in a refactor; it breaks silently.
|
||||
uci add_list firewall.shater_l3.device='shater-l3'
|
||||
fi
|
||||
if ! uci -q get firewall.shater_l3_fwd >/dev/null; then
|
||||
uci set firewall.shater_l3_fwd=forwarding
|
||||
uci set firewall.shater_l3_fwd.src='lan'
|
||||
uci set firewall.shater_l3_fwd.dest='shater_l3'
|
||||
fi
|
||||
uci -q commit firewall
|
||||
}
|
||||
seed_l3_zone
|
||||
|
||||
# Bring the UCI schema forward on upgrade (idempotent; refuses a newer schema).
|
||||
[ -x /usr/bin/shaterd ] && /usr/bin/shaterd migrate >/dev/null 2>&1
|
||||
|
||||
@@ -110,8 +172,27 @@ SHATER_BRINGUP='
|
||||
done
|
||||
[ -x /etc/init.d/shater ] && /etc/init.d/shater enable
|
||||
[ -x /etc/init.d/shater-cron ] && /etc/init.d/shater-cron enable
|
||||
# The boot-time fail-closed armor. `enable` only — it is a one-shot that loads
|
||||
# the persisted holding plane at START=21, and running it NOW would install a
|
||||
# block on a live box moments before the daemon replaces it anyway. It has to
|
||||
# be enabled here regardless of whether the stack is on: the file it loads only
|
||||
# exists while the daemon wants it to, so an enabled-but-unarmed service is a
|
||||
# no-op, and enabling it later would mean the first boot after an upgrade is
|
||||
# the one boot still exposed.
|
||||
[ -x /etc/init.d/shater-armor ] && /etc/init.d/shater-armor enable
|
||||
[ -x /etc/init.d/shater ] && /etc/init.d/shater restart
|
||||
[ -x /etc/init.d/shater-cron ] && /etc/init.d/shater-cron restart
|
||||
# Fold the seeded shater_l3 zone into the LIVE ruleset — matters on a live
|
||||
# opkg/apk install only, where firewall started long before our commit and
|
||||
# nothing else would re-read it until the next reboot. Gated on the fw4
|
||||
# table actually being loaded: at FIRST boot this job can run before the
|
||||
# S19 firewall start, and an early reload would install a ruleset built
|
||||
# from a half-initialized netifd AND make the later start a no-op (fw4
|
||||
# start skips when its table already exists). No table => the pending S19
|
||||
# start reads the committed config by itself, no reload needed.
|
||||
if nft list tables 2>/dev/null | grep -q "inet fw4"; then
|
||||
[ -x /etc/init.d/firewall ] && /etc/init.d/firewall reload
|
||||
fi
|
||||
exit 0
|
||||
'
|
||||
SHATER_TMO=""
|
||||
|
||||
@@ -34,8 +34,17 @@
|
||||
include $(TOPDIR)/rules.mk
|
||||
|
||||
PKG_NAME:=shaterd
|
||||
PKG_VERSION:=0.2.0
|
||||
PKG_RELEASE:=2
|
||||
|
||||
# VERSIONING — derived from the git tag, NOT hand-maintained here (bug B4).
|
||||
# ci/version.sh turns `git describe` into SHATER_PKG_VERSION/SHATER_PKG_RELEASE
|
||||
# (tag vX.Y.Z -> X.Y.Z + r1; off-tag -> last tag + r<commits+1>), and
|
||||
# ci/build-feed-apk.sh exports them into the SDK build env. ci/sdk-build-apk.sh
|
||||
# then ASSERTS that the produced .apk really carries that version, so a lost env
|
||||
# can never silently ship a stale one again.
|
||||
# The literals below are ONLY the manual/offline fallback (no CI, no git) — they
|
||||
# are not "the release version"; releases are named by the tag.
|
||||
PKG_VERSION:=$(if $(SHATER_PKG_VERSION),$(SHATER_PKG_VERSION),0.2.0)
|
||||
PKG_RELEASE:=$(if $(SHATER_PKG_RELEASE),$(SHATER_PKG_RELEASE),1)
|
||||
|
||||
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
|
||||
PKG_LICENSE:=GPL-3.0-or-later
|
||||
@@ -95,8 +104,8 @@ define Package/shaterd/install
|
||||
$(INSTALL_BIN) $(CURDIR)/files/$(SHATERD_BIN) $(1)/usr/bin/shaterd
|
||||
endef
|
||||
|
||||
# This package ships ONLY the binary — no init script — so opkg's default
|
||||
# postinst never touches the running service. On `opkg upgrade shaterd` the new
|
||||
# This package ships ONLY the binary — no init script — so the package manager's
|
||||
# postinst never touches the running service. On `apk upgrade shaterd` the new
|
||||
# ELF lands at /usr/bin/shaterd while the OLD image keeps running from its
|
||||
# unlinked inode: the upgrade silently has no effect until the next reboot, and
|
||||
# meanwhile the new CLI (`shaterd reconcile`, `status`, `mint-token` — invoked by
|
||||
|
||||
@@ -18,6 +18,32 @@ type URLTestOutboundOptions struct {
|
||||
// lx: SPEC 019 v2 — load-balancing.
|
||||
Mode string `json:"mode,omitempty"` // least_test (default) | round_robin
|
||||
Balancer *URLTestBalancerOptions `json:"balancer,omitempty"`
|
||||
// lx: health board §5.C — SelfCheck stands the group's OWN background
|
||||
// health-check up or down. nil/absent == true, so every existing config keeps
|
||||
// today's behaviour.
|
||||
//
|
||||
// Why this exists at all: a urltest group probes its members BY ITSELF — a
|
||||
// warm-up sweep at PostStart and a ticker for as long as traffic keeps
|
||||
// touching it — and it dials the members' outbounds DIRECTLY, from the
|
||||
// router, over whatever the default WAN route is. For a group that traffic
|
||||
// actually flows through, that is exactly right: the probe travels the same
|
||||
// path the connections do. But for a group NO routing rule reaches, that
|
||||
// same probe measures a path nothing uses — and it stores the result under
|
||||
// the members' BASE tags, which every health consumer then reads as "the
|
||||
// node's health". A node that is blocked on the direct WAN and perfectly
|
||||
// alive behind a tunnel therefore reads "dead" the moment such a group
|
||||
// probes it; the reading is not merely stale, it is FALSE, and it poisons
|
||||
// the shared board for everyone (selection, the panel, the observatory's
|
||||
// freshness gate). SelfCheck=false is how the control plane stands such a
|
||||
// group's own schedule down: the shater engine computes which groups the
|
||||
// applied rules actually reach (the observatory's used-set) and disables
|
||||
// the self-check on the rest, so the ONLY prober left is the observatory —
|
||||
// which probes along the real dial paths and nothing else.
|
||||
//
|
||||
// The flag suppresses only the group's own SCHEDULE (the PostStart warm-up
|
||||
// and the Touch ticker). An EXPLICIT CheckOutbounds/URLTest call — the
|
||||
// adapter interface a human or an API invokes on purpose — still works.
|
||||
SelfCheck *bool `json:"self_check,omitempty"`
|
||||
}
|
||||
|
||||
// URLTestBalancerOptions configures round_robin: a fixed-size pool of live nodes, lazily
|
||||
|
||||
+2
-1
@@ -8,7 +8,8 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "node --test src/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.3.1",
|
||||
|
||||
+221
-55
@@ -85,61 +85,6 @@
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---- query log wrapper + honest empty state ---- */
|
||||
.log-wrap {
|
||||
margin-top: calc(var(--u, 8px) * 3);
|
||||
}
|
||||
/* DNS-filter readout that sits above the live query log. */
|
||||
.filter-readout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr);
|
||||
gap: calc(var(--u, 8px) * 2);
|
||||
align-items: center;
|
||||
margin-bottom: calc(var(--u, 8px) * 1.5);
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.filter-readout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.topblocked {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
.topblocked li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 3px;
|
||||
background: var(--recess, transparent);
|
||||
}
|
||||
.topblocked .tb-dom {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--ink, inherit);
|
||||
}
|
||||
.topblocked .tb-n {
|
||||
color: var(--accent, #e8823c);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.qempty {
|
||||
margin: 10px 2px 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.6;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
/* ---- apply / confirm / rollback controls ---- */
|
||||
.controls {
|
||||
display: flex;
|
||||
@@ -317,6 +262,150 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- fixture band (dev builds only; see App.tsx MockBanner) ----
|
||||
Deliberately outside the crit/amber vocabulary: nothing is wrong with the
|
||||
router, there is no router. The hazard hatch is the service-sticker language a
|
||||
piece of network hardware already uses for "this unit is not in service". */
|
||||
.mock-band {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1.5);
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
padding: 10px 14px;
|
||||
border: 1px dashed var(--faint);
|
||||
border-radius: 9px;
|
||||
background: repeating-linear-gradient(
|
||||
-45deg,
|
||||
var(--sink),
|
||||
var(--sink) 9px,
|
||||
var(--panel) 9px,
|
||||
var(--panel) 18px
|
||||
);
|
||||
}
|
||||
.mock-band-tag {
|
||||
flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
padding: 3px 7px;
|
||||
border: 1px solid var(--faint);
|
||||
border-radius: 4px;
|
||||
background: var(--raised);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
color: var(--dim);
|
||||
}
|
||||
.mock-band-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.mock-band-headline {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--ink);
|
||||
}
|
||||
.mock-band-detail {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--dim);
|
||||
max-width: 76ch;
|
||||
}
|
||||
.mock-band-detail code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* ---- commit-confirm band (every page except Apply, which has the full panel) ----
|
||||
Same plate as the protection banner so the two read as one family; the seconds
|
||||
are the loud element because they are the only thing that is running out. */
|
||||
.cfm-band {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1.5);
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
padding: 10px 14px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 50%, var(--groove));
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(180deg, color-mix(in srgb, var(--amber) 10%, var(--raised)), var(--raised));
|
||||
box-shadow: 0 1px 0 var(--edge) inset;
|
||||
}
|
||||
.cfm-band-count {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
font-family: var(--font-mono);
|
||||
color: var(--amber);
|
||||
}
|
||||
.cfm-band-num {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
.cfm-band-unit {
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
.cfm-band-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
.cfm-band-headline {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--ink);
|
||||
}
|
||||
.cfm-band-detail {
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--dim);
|
||||
max-width: 76ch;
|
||||
}
|
||||
.cfm-band-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.cfm-band-link {
|
||||
padding: 6px 11px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 6px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
text-decoration: none;
|
||||
color: var(--ink);
|
||||
background: var(--raised);
|
||||
}
|
||||
.cfm-band-link:hover {
|
||||
border-color: var(--accent);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.cfm-band {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.cfm-band-actions {
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- last-apply findings (Overview) ----
|
||||
Severity carries the colour; the accent is reserved for interactive controls. */
|
||||
.findings {
|
||||
@@ -367,6 +456,13 @@
|
||||
.finding--warning {
|
||||
border-color: color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
}
|
||||
/* The daemon's "the list is capped" disclosure. Dashed, because the row is about
|
||||
what ISN'T here — it must not read as one more finding to work through. */
|
||||
.finding--truncated {
|
||||
border-style: dashed;
|
||||
border-color: color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
background: var(--panel);
|
||||
}
|
||||
.finding-copy {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -460,3 +556,73 @@
|
||||
color: var(--dim);
|
||||
max-width: 74ch;
|
||||
}
|
||||
|
||||
/* ---- inline rename (shared) ----
|
||||
The pencil-in-the-row interaction: click the ✎ beside a name, type over it,
|
||||
Enter commits / Esc cancels / blur commits. Lifted out of Devices.css when
|
||||
Nodes grew the same affordance — one interaction, one set of rules, so the two
|
||||
pages can never drift apart. `--locked` is the same control with the action
|
||||
withheld: it stays visible and focusable-looking so a missing rename reads as
|
||||
a stated rule, not a dead button. */
|
||||
.inline-rename {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
background: none;
|
||||
color: var(--faint);
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, background 0.15s, border-color 0.15s;
|
||||
}
|
||||
.inline-rename:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||
}
|
||||
.inline-rename:focus-visible {
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.inline-rename:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
/* Withheld, not broken: keep the glyph readable and let the cursor say "there is
|
||||
a reason" rather than dimming it into invisibility. */
|
||||
.inline-rename--locked {
|
||||
opacity: 0.75;
|
||||
cursor: help;
|
||||
}
|
||||
.inline-rename--locked:hover {
|
||||
color: var(--dim);
|
||||
background: none;
|
||||
}
|
||||
|
||||
.inline-rename-input {
|
||||
min-width: 0;
|
||||
max-width: 24ch;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 6px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
box-shadow: 0 1px 2px var(--shadow) inset;
|
||||
}
|
||||
.inline-rename-input:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.inline-rename-input:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
+119
-8
@@ -1,12 +1,14 @@
|
||||
import './App.css'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Faceplate, FaceplateHeader, Led, Module } from './components'
|
||||
import { Button, Faceplate, FaceplateHeader, Led, Module } from './components'
|
||||
import type { LedVariant } from './components'
|
||||
import { ApiError, MOCK, getStatus } from './api'
|
||||
import { ApiError, MOCK, confirm as apiConfirm, getStatus } from './api'
|
||||
import type { Status } from './api'
|
||||
import { usePendingConfirm } from './pendingConfirm'
|
||||
import { bootstrapSession } from './session'
|
||||
import { ROUTES, navigate, useRoute } from './router'
|
||||
import { protectionState } from './planeState'
|
||||
import { engineState, protectionState } from './planeState'
|
||||
import { truncationNote } from './findings'
|
||||
import type { Route } from './router'
|
||||
import { Overview, Placeholder, Nodes, Routing, Apply, DNS, Devices, Targets, Settings, Profiles, Insights, Networks } from './pages'
|
||||
|
||||
@@ -35,7 +37,7 @@ const SOON: Record<Exclude<Route, 'overview'>, string> = {
|
||||
dns: 'Pick resolvers and blocklists — DoH/DoT upstreams, fakeip pool, and per-source DNS rules.',
|
||||
devices: 'See LAN clients and their traffic — per-device policy and activity at a glance.',
|
||||
insights: 'Traffic & DNS insights — top domains, per-rule bytes, exits, and per-device volume.',
|
||||
profiles: 'WAN-mode / failover profiles — auto-switch routing by uplink, probe, or schedule.',
|
||||
profiles: 'WAN-mode / failover profiles — auto-switch routing by the active uplink.',
|
||||
settings: 'Global settings — kill-switch, IPv6, marks/tables, commit-confirm, health probe.',
|
||||
apply: 'Review, apply, and roll back config changes with the commit-confirm safety window.',
|
||||
}
|
||||
@@ -99,12 +101,102 @@ export function App() {
|
||||
footer={<StatusBar status={status} />}
|
||||
>
|
||||
<Nav route={route} />
|
||||
<MockBanner />
|
||||
<PlaneBanner status={status} route={route} />
|
||||
<ConfirmBand route={route} onChanged={() => void refreshStatus()} />
|
||||
<Page route={route} status={status} onStatusChange={() => void refreshStatus()} />
|
||||
</Faceplate>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The commit-confirm countdown, on every page.
|
||||
*
|
||||
* The daemon arms an auto-rollback on EVERY apply, but only the Apply page ever
|
||||
* said so: press Apply on Routing, read "Applied", walk away, and the router
|
||||
* reverts a minute later with nothing on screen having mentioned it. This band
|
||||
* carries that deadline — and the button that stops it — to wherever the operator
|
||||
* actually is.
|
||||
*
|
||||
* Suppressed on Apply, which renders the full control room for the same window
|
||||
* (and reads the same record, so a reload no longer loses the countdown there
|
||||
* either).
|
||||
*/
|
||||
function ConfirmBand({ route, onChanged }: { route: Route; onChanged: () => void }) {
|
||||
const armed = usePendingConfirm()
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Keeping the config is the only action offered here; rolling back early is a
|
||||
// deliberate act with its own before/after readout, and that lives on Apply.
|
||||
const keep = useCallback(async () => {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const r = await apiConfirm()
|
||||
if (r.error) setError(r.error)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'request failed')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
onChanged()
|
||||
}
|
||||
}, [onChanged])
|
||||
|
||||
if (!armed || route === 'apply') return null
|
||||
|
||||
return (
|
||||
<div className="cfm-band" role="alert">
|
||||
<Led variant="amber" pulse />
|
||||
<div className="cfm-band-count" role="timer" aria-label={`${armed.remaining} seconds until auto-rollback`}>
|
||||
<span className="cfm-band-num">{armed.remaining}</span>
|
||||
<span className="cfm-band-unit">s</span>
|
||||
</div>
|
||||
<div className="cfm-band-copy">
|
||||
<span className="cfm-band-headline">This config is live but not kept</span>
|
||||
<span className="cfm-band-detail">
|
||||
{error
|
||||
? `Couldn’t keep it — ${error}. Try again, or open Apply.`
|
||||
: 'Every apply arms an auto-rollback. Keep this config before the timer runs out, or the router reverts to the last-good one.'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="cfm-band-actions">
|
||||
<Button variant="primary" onClick={() => void keep()} disabled={busy}>
|
||||
{busy ? 'Keeping…' : 'Keep this config'}
|
||||
</Button>
|
||||
<a className="cfm-band-link" href="#/apply" onClick={() => navigate('apply')}>
|
||||
Apply page
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Says, on every page, that nothing on screen came from a router.
|
||||
*
|
||||
* Only a DEV build can ever render this — the fixtures are not in a production
|
||||
* bundle (api.ts initMockBackend), so an operator cannot reach this state at all.
|
||||
* It is here for the person who CAN: a footer line reading "DEMO DATA" is easy to
|
||||
* work past for an afternoon and then screenshot into a bug report, and every
|
||||
* number above it is invented.
|
||||
*/
|
||||
function MockBanner() {
|
||||
if (!MOCK) return null
|
||||
return (
|
||||
<div className="mock-band" role="status">
|
||||
<span className="mock-band-tag">FIXTURES</span>
|
||||
<div className="mock-band-copy">
|
||||
<span className="mock-band-headline">No router is being read</span>
|
||||
<span className="mock-band-detail">
|
||||
Every reading on this page is invented by <code>src/mock.ts</code> for offline
|
||||
development. Drop <code>?mock</code> from the address to talk to a daemon.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The protection state, pinned under the nav on every page EXCEPT Overview
|
||||
* (which shows the same state as its own headline readout — see planeState.ts).
|
||||
@@ -130,12 +222,15 @@ function PlaneBanner({ status, route }: { status: Status | null; route: Route })
|
||||
|
||||
const criticals = (status.warnings ?? []).filter((w) => w.severity === 'critical').length
|
||||
const state = protectionState(status)
|
||||
// The published list is capped at 50, so with a note attached the count is a
|
||||
// floor. Say "at least" rather than quoting a total the daemon didn't send.
|
||||
const atLeast = truncationNote(status.warnings) ? 'At least ' : ''
|
||||
|
||||
// Wording comes from the shared source of truth so the banner and Overview can
|
||||
// never describe the same router differently.
|
||||
const headline = state.alarm
|
||||
? state.headline
|
||||
: `${criticals} protection ${criticals === 1 ? 'gap' : 'gaps'} from the last apply`
|
||||
: `${atLeast}${criticals} protection ${criticals === 1 ? 'gap' : 'gaps'} from the last apply`
|
||||
const detail = state.alarm
|
||||
? state.detail
|
||||
: 'Something you configured isn’t in effect. Review the findings before relying on it.'
|
||||
@@ -225,14 +320,30 @@ function StatusBar({ status }: { status: Status | null }) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The one lamp that is on screen no matter which page you are on.
|
||||
*
|
||||
* It used to read `status.running`, which the daemon hardcoded to `true` — so the
|
||||
* "Offline" branch could never be reached and the plate said "Online" through an
|
||||
* engine that had failed to start. It now asks {@link engineState}, whose whole
|
||||
* job is to be able to answer "down", and refuses to guess when nothing has been
|
||||
* reported: an unlit socket, not a green light.
|
||||
*/
|
||||
function masterIndicator(
|
||||
phase: Phase,
|
||||
status: Status | null,
|
||||
): { label: string; variant: LedVariant; pulse?: boolean } {
|
||||
if (phase === 'loading' || !status) return { label: 'Linking', variant: 'off' }
|
||||
if (status.running && status.active) return { label: 'Online', variant: 'on', pulse: true }
|
||||
if (status.running) return { label: 'Standby', variant: 'amber' }
|
||||
return { label: 'Offline', variant: 'crit' }
|
||||
switch (engineState(status)) {
|
||||
case 'down':
|
||||
return { label: 'Engine down', variant: 'crit' }
|
||||
case 'up':
|
||||
return status.active
|
||||
? { label: 'Online', variant: 'on', pulse: true }
|
||||
: { label: 'Standby', variant: 'amber' }
|
||||
default:
|
||||
return { label: 'Unknown', variant: 'off' }
|
||||
}
|
||||
}
|
||||
|
||||
function UnauthPlate() {
|
||||
|
||||
+443
-171
@@ -13,8 +13,13 @@
|
||||
// serves in-memory fixtures instead of hitting the network, so `npm run dev`
|
||||
// and screenshot runs render without a live backend. A real backend in dev is
|
||||
// reachable instead via the Vite proxy in vite.config.ts (no flag ⇒ real fetch).
|
||||
//
|
||||
// THE FIXTURES ARE A DEV-BUILD-ONLY ARTEFACT — see initMockBackend below. They
|
||||
// used to be a plain static import, decided at RUNTIME off `location.search`, so
|
||||
// the invented router shipped inside the binary that goes on real hardware and a
|
||||
// link ending in `?dev` painted a healthy appliance without making one request.
|
||||
|
||||
import * as mock from './mock'
|
||||
import { armPendingConfirm, clearPendingConfirm, noteConfirmTimeout } from './pendingConfirm'
|
||||
|
||||
// --- error type -------------------------------------------------------------
|
||||
|
||||
@@ -51,6 +56,38 @@ export class ApiError extends Error {
|
||||
*/
|
||||
export type Plane = 'full' | 'hold' | 'none'
|
||||
|
||||
/**
|
||||
* Where the router's traffic actually ENDS UP, decided by the daemon from the
|
||||
* engine config it is running (apply.Status.traffic ← generate.TrafficOf).
|
||||
*
|
||||
* tunnel — the default route goes into a tunnel: everything not matched by a
|
||||
* more specific rule is proxied.
|
||||
* split — the default leaves directly, but some rules do tunnel their traffic.
|
||||
* direct — the default leaves directly and nothing is tunnelled at all.
|
||||
* blocked — the default is the fail-closed backstop: unmatched traffic is
|
||||
* dropped, not let out. Nothing leaks.
|
||||
*
|
||||
* `plane` DOES NOT ANSWER THIS and must never be read as if it did. `plane` says
|
||||
* how much of the data plane is installed (nft table, policy routing, engine up);
|
||||
* a router whose only rule is `default → direct` has all of it and sends the whole
|
||||
* LAN out the plain WAN with its real address. That combination — plane "full",
|
||||
* traffic "direct" — was live on a user's router under a green "Protected" LED.
|
||||
*/
|
||||
export type TrafficVerdict = 'tunnel' | 'split' | 'direct' | 'blocked'
|
||||
|
||||
export interface Traffic {
|
||||
// '' or absent ⇒ not known (daemon that predates this field, nothing applied
|
||||
// yet, or the plane is on hold). NEVER treat unknown as 'tunnel'.
|
||||
verdict?: TrafficVerdict | ''
|
||||
// The outbound tag the engine's default route names, in the engine's own
|
||||
// vocabulary ("direct", "block", a node/group tag). Diagnostic — wording is
|
||||
// driven by `verdict`, never by parsing this.
|
||||
default?: string
|
||||
// How many of the engine's route rules send their matched traffic into a tunnel.
|
||||
// Separates "some of your traffic is protected" from "none of it is".
|
||||
tunnel_rules?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* One thing the last apply could not do. Deliberately fail-OPEN with a warning
|
||||
* rather than refusing the whole config (the alternative was taking the network
|
||||
@@ -88,6 +125,10 @@ export interface Status {
|
||||
// How much of the data plane is installed. Absent on older daemons ⇒ unknown,
|
||||
// in which case the UI shows nothing rather than guessing "full".
|
||||
plane?: Plane
|
||||
// Where the traffic actually goes under the running config. Absent on older
|
||||
// daemons ⇒ unknown; see TrafficVerdict for why this is a separate question
|
||||
// from `plane`.
|
||||
traffic?: Traffic
|
||||
// Findings from the last apply. ALWAYS an array from the daemon (never null);
|
||||
// empty means the last apply was clean. Pre-sorted critical-first and capped at
|
||||
// 50, where a truncated list ends with an `info` entry saying "suppressed".
|
||||
@@ -308,11 +349,11 @@ export interface GroupMemberHealth {
|
||||
* auto 119 / 122 alive tested 122 of 298
|
||||
* stealth 2 / 2 alive
|
||||
*
|
||||
* Untested must NEVER be folded into dead. A group probes its members LAZILY —
|
||||
* only while it is being used — so a freshly booted router with a 376-node
|
||||
* subscription legitimately has almost no history, and "3 alive / 373 dead"
|
||||
* would be an alarm raised at the moment nothing is wrong. `dead` is only ever a
|
||||
* POSITIVE finding: a probe ran and failed.
|
||||
* Untested must NEVER be folded into dead. The daemon's observatory probes a
|
||||
* group only when an enabled routing rule can reach it (see `used`), and only a
|
||||
* probe that RAN and FAILED writes `dead` — so a freshly (re)started engine
|
||||
* legitimately reads mostly untested for a few seconds, and an unused group
|
||||
* reads untested forever. Neither is an alarm.
|
||||
*
|
||||
* `bound: true` means every member is a per-group egress COPY — this health was
|
||||
* measured through the group's own egress and is deliberately NOT comparable
|
||||
@@ -326,6 +367,12 @@ export interface GroupHealth {
|
||||
group: string
|
||||
type: string // "selector" | "urltest"
|
||||
bound: boolean
|
||||
/** An enabled routing rule (the Final target, a DNS-resolver detour, a device
|
||||
* target, …) reaches this group, so the observatory probes its members in
|
||||
* the background. false ⇒ nothing routes through the group: it is skipped by
|
||||
* the background probing and every member stays `untested`. That is an
|
||||
* "unused" note about the ROUTING CONFIG, never a health problem. */
|
||||
used: boolean
|
||||
/** Node name the group routes through right now; '' when it hasn't picked. */
|
||||
selected: string
|
||||
total: number
|
||||
@@ -338,61 +385,161 @@ export interface GroupHealth {
|
||||
members?: GroupMemberHealth[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The daemon's background health sweep — the thing that keeps these numbers
|
||||
* filling in without anyone pressing a button. Absent on older daemons, in which
|
||||
* case the UI must not promise that untested members will resolve on their own.
|
||||
*/
|
||||
export interface HealthSweep {
|
||||
enabled: boolean
|
||||
cursor: number
|
||||
total: number
|
||||
cycles: number
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/groups/health. `groups` is ALWAYS an array, never null.
|
||||
*
|
||||
* The `node_test_*` fields mirror GET /api/nodes/test: the probe-all run is what
|
||||
* turns a group's untested members into a real alive/dead verdict, so one poll of
|
||||
* this endpoint drives the numbers, the button and its progress readout.
|
||||
* The numbers fill in on their own: the daemon's observatory probes every group
|
||||
* and chain an enabled routing rule can reach (a ~10 s tick on the global Probe
|
||||
* URL / Interval), so a used group's untested members resolve to a real
|
||||
* alive/dead verdict within seconds. There is no manual run-everything button
|
||||
* any more and nothing to report here beyond the groups themselves.
|
||||
*/
|
||||
|
||||
/**
|
||||
* One hop of one chain, measured where that hop actually sits in the path.
|
||||
*
|
||||
* This is the reading the daemon always took and never showed. A chain is not a
|
||||
* target with a single health — it is an ordered series of them, and the only
|
||||
* question an operator ever asks about a broken chain is WHICH hop broke. The
|
||||
* end-to-end exit reading cannot answer that: it says "the path is dead" for a
|
||||
* four-hop chain and leaves the person to guess between four suspects.
|
||||
*
|
||||
* WIRE ORDER. `index` is 1-based and counts hops in the order the router dials
|
||||
* them: hop 1 is the first physical hop, and each later hop is dialled THROUGH
|
||||
* the ones before it. The hop carrying `exit: true` — always the largest index —
|
||||
* is where traffic leaves for the internet. A leading `egress:` in the chain's
|
||||
* configured Hops is NOT a numbered hop: the daemon lifts it into the entry
|
||||
* detour of hop 1, so a chain written `egress:ewan → node:awgout → group:sub0`
|
||||
* reports two hops, not three. Anything zipping this against the model's Hops
|
||||
* must drop that leading egress first and give up on labelling entirely if the
|
||||
* counts still disagree — a chain that splices sub-chains gets flattened here,
|
||||
* and a confidently WRONG hop name is worse than no name.
|
||||
*
|
||||
* `tag` is the engine-side outbound (`chain-<name>-h2`). Debugging and tooltips
|
||||
* only; it is never a label to put in front of a person.
|
||||
*
|
||||
* ORDERED WALK — THE READING STOPS AT THE FIRST DEAD HOP. Hops are NOT measured
|
||||
* independently, and never were measurable that way: hop 3 is dialled THROUGH
|
||||
* hop 2, so probing hop 3 while hop 2 is down measures hop 2 a second time and
|
||||
* learns nothing about hop 3. The daemon therefore walks the path in wire order
|
||||
* and stops at the first hop that does not answer. Every hop below that one is
|
||||
* left undialled and reported `state: "untested"` — no measurement exists —
|
||||
* carrying {@link ChainHopBlock} in `blocked_by` to name the hop that stopped the
|
||||
* walk. So a chain never reports a dead hop with a live hop below it; that shape
|
||||
* is not a rare case, it is unreachable.
|
||||
*
|
||||
* NODE HOP vs GROUP HOP. For `kind: "node"` the hop IS the measurement: `total`
|
||||
* is 1, the counters follow its own state, and `selected` is ''. For
|
||||
* `kind: "group"` the counters roll up that hop's per-hop member COPIES — the
|
||||
* copies dialled through the hops in front of it, which is exactly why they can
|
||||
* read alive here while the same group's standalone card reads dead. Both
|
||||
* readings are true; they measure different dial paths. `selected` is the node
|
||||
* NAME the hop routes through right now, and `delay_ms` / `age_seconds` belong
|
||||
* to that selected member (or the freshest alive one).
|
||||
*
|
||||
* Invariants the daemon guarantees — never re-derive them, just read them:
|
||||
* `tested === alive + dead` and `alive + dead + untested === total`.
|
||||
*
|
||||
* `state` is a closed set of THREE. `untested` is NEVER "dead" and never
|
||||
* "healthy": it means nothing fresh enough is known. Without `blocked_by` that is
|
||||
* a matter of timing — for a used chain it resolves on its own within seconds.
|
||||
* With `blocked_by` it will not resolve until the named hop is fixed. There is no
|
||||
* fourth state for that; the state stays `untested` because that is what it is.
|
||||
* `age_seconds: -1` means the age is unknown.
|
||||
*/
|
||||
export interface ChainHopHealth {
|
||||
/** 1-based WIRE order. Hop 1 is dialled first; see the note above. */
|
||||
index: number
|
||||
/** Engine outbound tag (`chain-<name>-h2`) — tooltips/debugging, never a label. */
|
||||
tag: string
|
||||
/** `node` ⇒ the hop is the measurement. `group` ⇒ the counters roll up members. */
|
||||
kind: 'node' | 'group'
|
||||
/** This hop is where traffic leaves for the internet. Always the largest index. */
|
||||
exit: boolean
|
||||
/** Closed set — switch on it exhaustively. `untested` is never "dead". */
|
||||
state: 'alive' | 'dead' | 'untested'
|
||||
/** RTT of the selected/freshest alive member; 0 (meaningless) when not alive. */
|
||||
delay_ms: number
|
||||
/** Age of that measurement in seconds; -1 when unknown. */
|
||||
age_seconds: number
|
||||
/** Node name this GROUP hop routes through right now; '' for a node hop. */
|
||||
selected: string
|
||||
total: number
|
||||
tested: number
|
||||
alive: number
|
||||
dead: number
|
||||
untested: number
|
||||
/**
|
||||
* PRESENT ONLY on a hop the ordered walk never reached — i.e. a hop sitting
|
||||
* below one the prober found `dead`. The key is omitted otherwise; absent is
|
||||
* the normal case and means "this hop was actually dialled".
|
||||
*
|
||||
* Its presence is the daemon's own statement that this hop has NO measurement,
|
||||
* and it comes with the rest of that statement already filled in: `state` is
|
||||
* `untested`, `delay_ms` is 0, `age_seconds` is -1, and the counters are
|
||||
* `alive: 0, dead: 0, tested: 0, untested: total`. Read those; do not re-derive
|
||||
* a verdict from them, and do not infer a block from zeroed counters either —
|
||||
* an unprobed-yet hop has the same numbers and a very different meaning.
|
||||
* `selected` MAY still be non-empty: the wrapper does have a pick, it simply
|
||||
* was not measured, so it says which node the hop would use, not which node is
|
||||
* carrying traffic.
|
||||
*/
|
||||
blocked_by?: ChainHopBlock
|
||||
}
|
||||
|
||||
/**
|
||||
* The hop that stopped the ordered walk, as reported on every hop below it.
|
||||
*
|
||||
* This exists because "no reading" and "no reading, and here is whose fault that
|
||||
* is" are different answers to the operator's actual question. Without it a
|
||||
* blocked hop is indistinguishable from one the observatory has not come round to
|
||||
* yet, and the interface can only shrug.
|
||||
*
|
||||
* `index` is the 1-based WIRE index of the blocking hop and is ALWAYS smaller
|
||||
* than the index of the hop carrying it, so it points at a hop already on screen.
|
||||
* `tag` is that hop's engine outbound (`chain-<name>-h3`) — debugging and
|
||||
* tooltips only, never a label to put in front of a person, exactly as on
|
||||
* {@link ChainHopHealth}.tag.
|
||||
*/
|
||||
export interface ChainHopBlock {
|
||||
/** 1-based wire index of the hop that did not answer. Always < this hop's index. */
|
||||
index: number
|
||||
/** That hop's engine outbound tag — tooltips/debugging, never a label. */
|
||||
tag: string
|
||||
}
|
||||
|
||||
/** Per-chain reachability, the chain analogue of {@link GroupHealth}.used (plan
|
||||
* §5.E): a chain no enabled routing rule routes through is outside the
|
||||
* observatory's plan, so nothing probes it and the Targets card says so instead
|
||||
* of rendering a health reading. A chain has no membership counters of its own —
|
||||
* it is a fixed path, and its health lives on its {@link ChainHopHealth} hops. */
|
||||
export interface ChainHealth {
|
||||
name: string
|
||||
/** An enabled routing rule (the Final target, a DNS-resolver detour, a device
|
||||
* target, …) reaches this chain, so the observatory probes its hops in the
|
||||
* background. false ⇒ nothing routes through the chain: it is skipped by the
|
||||
* background probing and its health stays untested. That is an "unused" note
|
||||
* about the ROUTING CONFIG, never a health problem. */
|
||||
used: boolean
|
||||
/**
|
||||
* Per-hop health in wire order (see {@link ChainHopHealth}).
|
||||
*
|
||||
* MAY BE ABSENT, and absent does not mean "this chain has no hops". It means
|
||||
* the engine never materialised per-hop outbounds for it: the chain is unused,
|
||||
* or it collapses to a single hop and the daemon points traffic straight at
|
||||
* that target instead of building a copy of it. Read a missing key as "nothing
|
||||
* measured per hop", never as an empty path or as a fault.
|
||||
*/
|
||||
hops?: ChainHopHealth[]
|
||||
}
|
||||
|
||||
export interface GroupsHealth {
|
||||
groups: GroupHealth[]
|
||||
node_test_running: boolean
|
||||
node_test_done: number
|
||||
node_test_total: number
|
||||
sweep?: HealthSweep
|
||||
}
|
||||
|
||||
/**
|
||||
* The health run's scope, as the daemon publishes it (panel/api.go NodeTestScope).
|
||||
*
|
||||
* It is a CONSTANT, not a list, and that is the whole point: a health run measures
|
||||
* every node, every endpoint and every group's egress copies in one pass, so it can
|
||||
* never be attributed to one card. Render it as a single global progress indicator.
|
||||
* The scoped counterpart is {@link GroupTestStatus.scope}.
|
||||
*/
|
||||
export const NODE_TEST_SCOPE = 'all_nodes'
|
||||
export type NodeTestScope = typeof NODE_TEST_SCOPE
|
||||
|
||||
/**
|
||||
* GET /api/nodes/test — progress of a manual "Test all nodes" probe-all run.
|
||||
* `running` is true while a run is in flight; `done`/`total` count finished vs
|
||||
* targeted node probes. Idle (never run, or finished) reads `{running:false}`.
|
||||
*/
|
||||
export interface NodeTestStatus {
|
||||
running: boolean
|
||||
done: number
|
||||
total: number
|
||||
/** Always {@link NODE_TEST_SCOPE}; absent on daemons older than the split. */
|
||||
scope?: NodeTestScope
|
||||
}
|
||||
|
||||
/** POST /api/nodes/test reply: `started` when a fresh run began, else `running`. */
|
||||
export interface NodeTestStart {
|
||||
started?: boolean
|
||||
running?: boolean
|
||||
/** Per-chain reachability, same "unused" badge as groups (plan §5.E). Present on
|
||||
* the summary and `?members=` shapes; the single-group (`?group=`) shape is a
|
||||
* group detail request and omits it. Always an array when present; absent ⇒ not
|
||||
* reported by this daemon version (the page treats absence like "not known yet"). */
|
||||
chains?: ChainHealth[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -463,23 +610,6 @@ export interface Globals {
|
||||
EndpointResolver: string
|
||||
ProbeURL: string
|
||||
ProbeInterval: string
|
||||
/**
|
||||
* Tick period of the daemon's background health sweep — the walk that keeps
|
||||
* every node's health fresh so the group cards fill in without anyone pressing
|
||||
* a button (model.Globals.SweepInterval, UCI `sweep_interval`).
|
||||
*
|
||||
* `""` means ENABLED at the engine's default tick, NOT off. That default is
|
||||
* load-bearing: urltest groups probe only while they are being used and selector
|
||||
* groups never probe at all, so without the sweep a 376-node subscription reads
|
||||
* almost entirely "not measured".
|
||||
*
|
||||
* Accepted: a duration ("30s", "5m", "1h") or a bare integer of seconds; any of
|
||||
* `0` / `off` / `none` / `disabled` to switch the sweep off. Below 5 s the
|
||||
* daemon raises it to that floor. An UNRECOGNISED value does not disable the
|
||||
* sweep — the daemon warns and falls back to the default — so the panel refuses
|
||||
* it at the input instead of saving something that will be silently ignored.
|
||||
*/
|
||||
SweepInterval: string
|
||||
SchemaVersion: number
|
||||
ActiveProfile: string
|
||||
/**
|
||||
@@ -508,14 +638,17 @@ export interface Globals {
|
||||
DNSIntercept?: boolean // force ALL LAN plaintext DNS (:53) through the engine, incl. router-addressed queries
|
||||
BlockDoH?: boolean // block known public DoH resolvers (by host + IP:443 + Firefox canary) so clients fall back to plaintext :53
|
||||
/**
|
||||
* Our background health sweep of group members — the walk that fills the alive /
|
||||
* The daemon's observatory — the background probing that fills the alive /
|
||||
* dead / tested numbers the Targets page shows for each group (model.Globals
|
||||
* .GroupHealth, UCI `group_health`). Default ON.
|
||||
* .GroupHealth, UCI `group_health`). It probes only the groups and chains an
|
||||
* enabled routing rule can reach, on the global Probe URL / Interval, and
|
||||
* skips everything else. Default ON.
|
||||
*
|
||||
* This governs OUR sweep and the health/testing UI ONLY. It does NOT touch
|
||||
* sing-box's own internal urltest / least_test probes: a group always keeps
|
||||
* picking a live member under the hood regardless of this switch. Turning it off
|
||||
* just stops the extra sweep and hides the health statistics.
|
||||
* This gates the observatory and the health/testing UI ONLY. It does NOT
|
||||
* touch sing-box's own internal urltest / least_test probes: a group always
|
||||
* keeps picking a live member under the hood regardless of this switch.
|
||||
* Turning it off stops the background probing and hides the health
|
||||
* statistics.
|
||||
*
|
||||
* ABSENT ⇒ enabled (an older config never wrote the key), so the invariant the
|
||||
* panel reads by is `globals?.GroupHealth !== false` — never `=== true`.
|
||||
@@ -662,8 +795,6 @@ export interface Group {
|
||||
FilterProto?: string[] | null
|
||||
FilterCountry?: string[] | null
|
||||
Dedup?: boolean
|
||||
ProbeURL?: string
|
||||
ProbeInterval?: string
|
||||
/**
|
||||
* The egress EVERY node in this group dials its own server through — the same
|
||||
* binding `Node.Egress` gives one node, applied to the whole group. "" ⇒ the
|
||||
@@ -731,14 +862,6 @@ export interface RulesetStatus {
|
||||
rule_count: number
|
||||
}
|
||||
|
||||
/** A quick rule on/off bundle (config preset). */
|
||||
export interface Preset {
|
||||
Name: string
|
||||
Enabled: boolean
|
||||
Order?: number
|
||||
Target?: string
|
||||
}
|
||||
|
||||
/** A WAN-mode / failover conditional override (config profile). */
|
||||
export interface Profile {
|
||||
Name: string
|
||||
@@ -752,23 +875,8 @@ export interface Profile {
|
||||
// condition — so adding one SWITCHED OFF an otherwise working profile. Both were
|
||||
// deleted from the Go model; PUT decodes with DisallowUnknownFields, so sending
|
||||
// either key fails the whole write with 400.
|
||||
SchedDays?: string[] | null
|
||||
SchedStart?: string
|
||||
SchedEnd?: string
|
||||
/**
|
||||
* Minutes EAST of UTC that anchor the schedule's wall-clock times (Moscow =
|
||||
* 180, New York winter = −300). The router carries no IANA tzdata, so the
|
||||
* daemon evaluates the window at UTC+offset; the panel captures the editing
|
||||
* browser's offset whenever a schedule field is saved. 0/absent ⇒ UTC.
|
||||
* Known limitation: a fixed offset does not follow DST until re-saved.
|
||||
* (Replaces the deleted SchedTZ — an IANA name never resolved on the router,
|
||||
* so the promised local time was silently UTC; see model.go.)
|
||||
*/
|
||||
SchedUTCOffset?: number
|
||||
EnableRules?: string[] | null
|
||||
DisableRules?: string[] | null
|
||||
DefaultTarget?: string
|
||||
DefaultEgress?: string
|
||||
/** Per-profile override of the endpoint resolver (keyed by active WAN: SIM→yandex, WiFi→DoH). "" ⇒ no override (model.Profile.EndpointResolver, UCI `endpoint_resolver`). */
|
||||
EndpointResolver?: string
|
||||
}
|
||||
@@ -865,9 +973,17 @@ export interface Rule {
|
||||
Enabled: boolean
|
||||
Order: number
|
||||
Src?: string[] | null
|
||||
DstDomain?: string[] | null
|
||||
/**
|
||||
* WHERE the traffic is going — the rule's only destination matcher. Each entry
|
||||
* names a {@link Ruleset}; the rule matches when ANY of them matches.
|
||||
*
|
||||
* There is no inline domain or address list on a rule. `dst_domain`/`dst_ip`
|
||||
* were removed in schema v2, and `shaterd migrate` folds every existing one
|
||||
* into a generated `rule-<name>` ruleset, so a destination list is written and
|
||||
* edited in exactly one place and compiled once into a .srs that every rule
|
||||
* referencing it shares.
|
||||
*/
|
||||
DstRuleset?: string[] | null
|
||||
DstIP?: string[] | null
|
||||
DstPort?: string
|
||||
/**
|
||||
* Narrow the rule to one transport or one sniffed application protocol. A
|
||||
@@ -879,12 +995,19 @@ export interface Rule {
|
||||
Proto?: string // '' | tcp | udp | tls | http | quic | dns | stun | bittorrent | dtls | ssh | rdp | ntp
|
||||
Target?: string
|
||||
Egress?: string
|
||||
Kill?: string
|
||||
/**
|
||||
* Policy for when the target can't resolve at generate time (dead group,
|
||||
* broken chain, missing egress/node). The rule is always still emitted — its
|
||||
* traffic never falls through to the default route. ''/'default'/'closed' and
|
||||
* anything unrecognised block the traffic (fail-closed); 'open' is an explicit,
|
||||
* warned kill-switch bypass that sends it direct.
|
||||
*/
|
||||
Kill?: string // '' | default | closed | open
|
||||
SchedEnabled?: boolean
|
||||
SchedDays?: string[] | null
|
||||
SchedStart?: string
|
||||
SchedEnd?: string
|
||||
/** Minutes east of UTC anchoring SchedStart/SchedEnd/SchedDays — same contract as Profile.SchedUTCOffset. */
|
||||
/** Minutes east of UTC anchoring SchedStart/SchedEnd/SchedDays — the panel captures the editing browser's offset on save (the router has no tzdata). */
|
||||
SchedUTCOffset?: number
|
||||
}
|
||||
|
||||
@@ -958,7 +1081,8 @@ export interface Interface {
|
||||
|
||||
/** GET /api/devices row — a discovered LAN client merged with its config, if any. */
|
||||
export interface DiscoveredDevice {
|
||||
ip: string
|
||||
ip: string // primary address (most recent lease)
|
||||
ips: string[] // every known address (v4+v6, multiple leases), primary first
|
||||
mac: string
|
||||
hostname: string
|
||||
online: boolean
|
||||
@@ -988,7 +1112,6 @@ export interface Model {
|
||||
Devices?: Device[] | null
|
||||
Chains?: Chain[] | null
|
||||
Rulesets?: Ruleset[] | null
|
||||
Presets?: Preset[] | null
|
||||
Profiles?: Profile[] | null
|
||||
Inbounds?: Inbound[] | null
|
||||
DNSRules?: DNSRule[] | null
|
||||
@@ -1001,12 +1124,59 @@ export interface Model {
|
||||
|
||||
// --- transport --------------------------------------------------------------
|
||||
|
||||
/** True when the URL asks for the offline fixture backend (?mock or ?dev). */
|
||||
export const MOCK: boolean = (() => {
|
||||
// --- the offline fixture backend (dev builds only) ---------------------------
|
||||
|
||||
/**
|
||||
* True when the in-memory fixtures are serving this session instead of the
|
||||
* daemon. ALWAYS false in a production build — see {@link initMockBackend}.
|
||||
*
|
||||
* A live binding, not a constant: it is decided once during boot, before the
|
||||
* first render, and every importer sees the same value for the whole session.
|
||||
*/
|
||||
export let MOCK = false
|
||||
|
||||
/** The loaded fixture module. `null` unless a dev build was asked for `?mock`. */
|
||||
let fixtures: typeof import('./mock') | null = null
|
||||
|
||||
/**
|
||||
* Load the fixture backend, if this build has one and the URL asks for it.
|
||||
* Call ONCE from the entry point and await it before the first render — the
|
||||
* pages read {@link MOCK} while they render, so flipping it afterwards would
|
||||
* leave a half-mocked screen.
|
||||
*
|
||||
* Two gates, and the order matters. `import.meta.env.DEV` is folded to a literal
|
||||
* `false` by Vite at build time, so in a production build the whole body is
|
||||
* unreachable, `import('./mock')` is tree-shaken out of the module graph, and the
|
||||
* fixtures are not in the emitted bundle AT ALL — not lazily, not behind a flag.
|
||||
* `vite.config.ts` fails the build if that ever stops being true.
|
||||
*
|
||||
* This is deliberately stronger than "hide the mock behind a query flag". The
|
||||
* flag was the bug: `?dev` on a production URL rendered an invented healthy
|
||||
* router — 119 of 122 nodes alive, "Protected" — with no request made and one
|
||||
* line of small print in the footer to say so. A person cannot audit a bundle;
|
||||
* the only honest guarantee is that the invented data is not in it.
|
||||
*/
|
||||
export async function initMockBackend(): Promise<boolean> {
|
||||
if (import.meta.env.DEV && mockRequested()) {
|
||||
fixtures = await import('./mock')
|
||||
MOCK = true
|
||||
}
|
||||
return MOCK
|
||||
}
|
||||
|
||||
/** Does the URL ask for the offline fixture backend (`?mock` or `?dev`)? */
|
||||
function mockRequested(): boolean {
|
||||
if (typeof location === 'undefined') return false
|
||||
const q = new URLSearchParams(location.search)
|
||||
return q.has('mock') || q.has('dev')
|
||||
})()
|
||||
}
|
||||
|
||||
/** The fixture backend, for the `MOCK ? … : …` branches below. Throws rather
|
||||
* than inventing data if it is ever reached without having been loaded. */
|
||||
function mock(): NonNullable<typeof fixtures> {
|
||||
if (!fixtures) throw new Error('mock backend not loaded — call initMockBackend() first')
|
||||
return fixtures
|
||||
}
|
||||
|
||||
/** A decoded response plus the raw Headers, for endpoints whose contract puts
|
||||
* pagination metadata outside the JSON body (see the stats log endpoints). */
|
||||
@@ -1055,33 +1225,54 @@ async function req<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
// --- endpoints --------------------------------------------------------------
|
||||
|
||||
export function getStatus(): Promise<Status> {
|
||||
return MOCK ? mock.getStatus() : req<Status>('api/status')
|
||||
return MOCK ? mock().getStatus() : req<Status>('api/status')
|
||||
}
|
||||
|
||||
export function getConfig(): Promise<Model> {
|
||||
return MOCK ? mock.getConfig() : req<Model>('api/config')
|
||||
export async function getConfig(): Promise<Model> {
|
||||
const m = await (MOCK ? mock().getConfig() : req<Model>('api/config'))
|
||||
// Every page reads the config, and the commit-confirm window's length is the
|
||||
// only thing needed to arm a countdown — so it is captured here once instead of
|
||||
// being threaded through eight pages. See pendingConfirm.ts.
|
||||
noteConfirmTimeout(m.Globals?.ConfirmTimeout)
|
||||
return m
|
||||
}
|
||||
|
||||
export function putConfig(m: Model): Promise<{ ok: boolean; applied: boolean }> {
|
||||
return MOCK
|
||||
? mock.putConfig(m)
|
||||
? mock().putConfig(m)
|
||||
: req('api/config', { method: 'PUT', body: JSON.stringify(m) })
|
||||
}
|
||||
|
||||
export function apply(): Promise<ApplyResult> {
|
||||
return MOCK ? mock.apply() : req<ApplyResult>('api/apply', { method: 'POST' })
|
||||
/**
|
||||
* POST /api/apply.
|
||||
*
|
||||
* The daemon arms an auto-rollback on EVERY successful apply that changed
|
||||
* something (panel/api.go handleApply → ArmRollback), whichever page's button was
|
||||
* pressed. Recording it here — the one place every one of those buttons goes
|
||||
* through — is what lets the countdown and the "Keep this config" control follow
|
||||
* the operator around the panel instead of living in the Apply page's local
|
||||
* state. See pendingConfirm.ts.
|
||||
*/
|
||||
export async function apply(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock().apply() : req<ApplyResult>('api/apply', { method: 'POST' }))
|
||||
if (!r.error && r.changed) armPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export function confirm(): Promise<ApplyResult> {
|
||||
return MOCK ? mock.confirm() : req<ApplyResult>('api/confirm', { method: 'POST' })
|
||||
export async function confirm(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock().confirm() : req<ApplyResult>('api/confirm', { method: 'POST' }))
|
||||
if (!r.error) clearPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export function rollback(): Promise<ApplyResult> {
|
||||
return MOCK ? mock.rollback() : req<ApplyResult>('api/rollback', { method: 'POST' })
|
||||
export async function rollback(): Promise<ApplyResult> {
|
||||
const r = await (MOCK ? mock().rollback() : req<ApplyResult>('api/rollback', { method: 'POST' }))
|
||||
if (!r.error) clearPendingConfirm()
|
||||
return r
|
||||
}
|
||||
|
||||
export function getStats(): Promise<Stats> {
|
||||
return MOCK ? mock.getStats() : req<Stats>('api/stats')
|
||||
return MOCK ? mock().getStats() : req<Stats>('api/stats')
|
||||
}
|
||||
|
||||
// --- daemon log download ------------------------------------------------------
|
||||
@@ -1133,7 +1324,7 @@ function saveBlob(blob: Blob, filename: string): void {
|
||||
*/
|
||||
export async function downloadLog(range: LogRange): Promise<void> {
|
||||
if (MOCK) {
|
||||
saveBlob(new Blob([mock.getLogText(range)], { type: 'text/plain' }), `shater-log-${range}.txt`)
|
||||
saveBlob(new Blob([mock().getLogText(range)], { type: 'text/plain' }), `shater-log-${range}.txt`)
|
||||
return
|
||||
}
|
||||
let res: Response
|
||||
@@ -1212,14 +1403,14 @@ function logPage<T>(env: { body: T[] | null; headers: Headers }): StatsLogPage<T
|
||||
/** GET /api/stats/log — one page of the DNS query log with its cursor metadata. */
|
||||
export function getStatsLogPage(q: StatsLogQuery = {}): Promise<StatsLogPage<QueryLogEntry>> {
|
||||
return MOCK
|
||||
? mock.getStatsLogPage(q)
|
||||
? mock().getStatsLogPage(q)
|
||||
: reqFull<QueryLogEntry[] | null>(`api/stats/log${statsLogQS(q)}`).then(logPage)
|
||||
}
|
||||
|
||||
/** GET /api/stats/conns — one page of the connection log with its cursor metadata. */
|
||||
export function getStatsConnsPage(q: StatsLogQuery = {}): Promise<StatsLogPage<ConnLogEntry>> {
|
||||
return MOCK
|
||||
? mock.getStatsConnsPage(q)
|
||||
? mock().getStatsConnsPage(q)
|
||||
: reqFull<ConnLogEntry[] | null>(`api/stats/conns${statsLogQS(q)}`).then(logPage)
|
||||
}
|
||||
|
||||
@@ -1227,18 +1418,73 @@ export function getStatsConnsPage(q: StatsLogQuery = {}): Promise<StatsLogPage<C
|
||||
* Rows only; callers that tail the stream want {@link getStatsLogPage} instead. */
|
||||
export function getStatsLog(q: number | StatsLogQuery = {}): Promise<QueryLogEntry[]> {
|
||||
const o: StatsLogQuery = typeof q === 'number' ? { limit: q } : q
|
||||
return MOCK ? mock.getStatsLog(o) : req<QueryLogEntry[]>(`api/stats/log${statsLogQS(o)}`)
|
||||
return MOCK ? mock().getStatsLog(o) : req<QueryLogEntry[]>(`api/stats/log${statsLogQS(o)}`)
|
||||
}
|
||||
|
||||
/** GET /api/stats/conns — the live connection-event log (device→dest), newest first. */
|
||||
export function getStatsConns(q: number | StatsLogQuery = {}): Promise<ConnLogEntry[]> {
|
||||
const o: StatsLogQuery = typeof q === 'number' ? { limit: q } : q
|
||||
return MOCK ? mock.getStatsConns(o) : req<ConnLogEntry[]>(`api/stats/conns${statsLogQS(o)}`)
|
||||
return MOCK ? mock().getStatsConns(o) : req<ConnLogEntry[]>(`api/stats/conns${statsLogQS(o)}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* One routing rule's reachability verdict — the rule analogue of
|
||||
* {@link ChainHealth}.used: a quiet note about the ROUTING CONFIG, never a health
|
||||
* signal.
|
||||
*
|
||||
* `unreachable` means the rule can NEVER take effect, whatever the traffic. Today
|
||||
* the daemon reports exactly one certain case, and it is a subtle one: a rule with
|
||||
* no conditions at all is not matched in sequence — it becomes the router's
|
||||
* default. Two such rules therefore retire each other, and the LAST one by Order
|
||||
* wins, so an earlier "default → direct" is dead even though it sorts first. A
|
||||
* condition-less rule never retires a rule that HAS conditions: those are matched
|
||||
* ahead of the default whatever their Order.
|
||||
*
|
||||
* `index` is the rule's position in GET /api/config's `Rules`, which is how a
|
||||
* verdict is matched to a row — rule names are not unique, and the config that
|
||||
* prompted this had two rules both called `default`. `name`/`order` are echoed so
|
||||
* a page holding a verdict fetched before an edit can check it still describes the
|
||||
* row it is about to badge, and drop it silently otherwise.
|
||||
*/
|
||||
export interface RuleReach {
|
||||
index: number
|
||||
name: string
|
||||
order: number
|
||||
unreachable: boolean
|
||||
/** The rule that supersedes this one; absent when `unreachable` is false. */
|
||||
shadowed_by?: string
|
||||
/** Its index in `Rules`, or -1 when there is none. */
|
||||
shadowed_by_index: number
|
||||
shadowed_by_order?: number
|
||||
/** Operator-facing sentence; absent when `unreachable` is false. */
|
||||
reason?: string
|
||||
/**
|
||||
* Whether the rule is IN FORCE right now — `Rule.Enabled` after the active WAN
|
||||
* profile's overrides. This is NOT `GET /api/config`'s `Enabled`: that one is
|
||||
* the desired state the page PUTs back, and on a router with profiles the two
|
||||
* legitimately disagree. Draw rows from this; keep the switch on the other.
|
||||
*/
|
||||
effective_enabled: boolean
|
||||
/** The active profile that CHANGED this rule's state; absent when none did. */
|
||||
overridden_by?: string
|
||||
/** Which way it went. Absent together with `overridden_by`. */
|
||||
override?: 'enabled' | 'disabled'
|
||||
}
|
||||
|
||||
/** GET /api/rules/reachability. `rules` is ALWAYS an array, one entry per rule in
|
||||
* the same order as GET /api/config's `Rules`. */
|
||||
export interface RulesReachability {
|
||||
rules: RuleReach[]
|
||||
}
|
||||
|
||||
/** GET /api/rules/reachability — which routing rules can never fire, and why. */
|
||||
export function getRulesReachability(): Promise<RulesReachability> {
|
||||
return MOCK ? mock().getRulesReachability() : req<RulesReachability>('api/rules/reachability')
|
||||
}
|
||||
|
||||
/** GET /api/ruleset/status — remote rule-set / blocklist freshness + rule counts. */
|
||||
export function getRulesetStatus(): Promise<RulesetStatus[]> {
|
||||
return MOCK ? mock.getRulesetStatus() : req<RulesetStatus[]>('api/ruleset/status')
|
||||
return MOCK ? mock().getRulesetStatus() : req<RulesetStatus[]>('api/ruleset/status')
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1249,7 +1495,7 @@ export function getRulesetStatus(): Promise<RulesetStatus[]> {
|
||||
*/
|
||||
export function updateRuleset(tag: string): Promise<RulesetStatus | { ok: boolean }> {
|
||||
return MOCK
|
||||
? mock.updateRuleset(tag)
|
||||
? mock().updateRuleset(tag)
|
||||
: req('api/ruleset/update', { method: 'POST', body: JSON.stringify({ tag }) })
|
||||
}
|
||||
|
||||
@@ -1277,7 +1523,7 @@ export interface RulesetCheck {
|
||||
*/
|
||||
export function checkRulesetCategory(source: string, category: string): Promise<RulesetCheck> {
|
||||
return MOCK
|
||||
? mock.checkRulesetCategory(source, category)
|
||||
? mock().checkRulesetCategory(source, category)
|
||||
: req<RulesetCheck>('api/ruleset/check', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source, category }),
|
||||
@@ -1306,18 +1552,18 @@ export interface RulesetCategories {
|
||||
*/
|
||||
export function getRulesetCategories(source: string): Promise<RulesetCategories> {
|
||||
return MOCK
|
||||
? mock.getRulesetCategories(source)
|
||||
? mock().getRulesetCategories(source)
|
||||
: req<RulesetCategories>(`api/ruleset/categories?source=${encodeURIComponent(source)}`)
|
||||
}
|
||||
|
||||
/** GET /api/devices — discovered LAN clients merged with per-device config. */
|
||||
export function getDevices(): Promise<DiscoveredDevice[]> {
|
||||
return MOCK ? mock.getDevices() : req<DiscoveredDevice[]>('api/devices')
|
||||
return MOCK ? mock().getDevices() : req<DiscoveredDevice[]>('api/devices')
|
||||
}
|
||||
|
||||
/** GET /api/interfaces — the router's UCI network interfaces for the egress picker. */
|
||||
export function getInterfaces(): Promise<Interface[]> {
|
||||
return MOCK ? mock.getInterfaces() : req<Interface[]>('api/interfaces')
|
||||
return MOCK ? mock().getInterfaces() : req<Interface[]>('api/interfaces')
|
||||
}
|
||||
|
||||
/** POST /api/session — exchange a single-use handoff token for a session cookie. */
|
||||
@@ -1353,25 +1599,10 @@ export function importWg(conf: string): Promise<{ uri: string; name: string }> {
|
||||
*/
|
||||
export function updateSubscription(name: string): Promise<{ added: number }> {
|
||||
return MOCK
|
||||
? mock.updateSubscription(name)
|
||||
? mock().updateSubscription(name)
|
||||
: req('api/subscription/update', { method: 'POST', body: JSON.stringify({ name }) })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/nodes/test — force a health probe of every node. The daemon runs it in
|
||||
* the background (singleton: a second POST while one is running is a no-op that
|
||||
* reports `{running:true}`); the normal /api/stats poll then surfaces each fresh
|
||||
* result. Resolves to `{started}` or `{running}`.
|
||||
*/
|
||||
export function postNodesTest(): Promise<NodeTestStart> {
|
||||
return MOCK ? mock.postNodesTest() : req<NodeTestStart>('api/nodes/test', { method: 'POST' })
|
||||
}
|
||||
|
||||
/** GET /api/nodes/test — progress of the current/last probe-all run. */
|
||||
export function getNodesTest(): Promise<NodeTestStatus> {
|
||||
return MOCK ? mock.getNodesTest() : req<NodeTestStatus>('api/nodes/test')
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/groups/health — per-group membership health (see {@link GroupHealth}).
|
||||
*
|
||||
@@ -1388,7 +1619,7 @@ export function getNodesTest(): Promise<NodeTestStatus> {
|
||||
export function getGroupsHealth(
|
||||
opts: { group?: string; members?: boolean } = {},
|
||||
): Promise<GroupsHealth> {
|
||||
if (MOCK) return mock.getGroupsHealth(opts)
|
||||
if (MOCK) return mock().getGroupsHealth(opts)
|
||||
const p = new URLSearchParams()
|
||||
if (opts.group) p.set('group', opts.group)
|
||||
if (opts.members) p.set('members', '1')
|
||||
@@ -1397,20 +1628,50 @@ export function getGroupsHealth(
|
||||
}
|
||||
|
||||
/**
|
||||
* One group's last test: which member the balancer picked, how fast it answered,
|
||||
* and what the internet saw as the source address.
|
||||
* What the OBSERVATORY measured for one group or chain — not a dial the panel
|
||||
* made.
|
||||
*
|
||||
* This shape used to come from a fresh connection opened on demand, straight at
|
||||
* the target. That was a lie on any router whose proxies are blocked when dialled
|
||||
* directly and work only as a hop behind a tunnel: the card reported dead for a
|
||||
* path that carries traffic all day. The daemon now has exactly one thing that
|
||||
* measures — the background observatory, which probes along the REAL dial path,
|
||||
* per-hop copies and all — and this endpoint reports what it found. There is no
|
||||
* second measurement anywhere, and the panel never opens a connection of its own.
|
||||
*
|
||||
* So read the fields as a READ, not as a test run: `ok` and `delay_ms` are the
|
||||
* observatory's verdict for the path traffic actually takes, and `tested_unix`
|
||||
* (router clock, seconds) is when the OBSERVATORY took that measurement — which
|
||||
* can be a few seconds before the refresh was asked for.
|
||||
*
|
||||
* `ok:true` with an EMPTY `exit_ip`/`exit_country` is a valid, successful result,
|
||||
* not a partial failure: the delay was measured but the exit address could not be
|
||||
* determined (the lookup service was unreachable, or the answer wasn't parseable).
|
||||
* Render it as a success with an unknown address — never as an error.
|
||||
*
|
||||
* `ok:false` ⇒ the test failed and `error` carries the human reason; every other
|
||||
* field is meaningless. `tested_unix` is the router's clock, in seconds.
|
||||
* Chains ride the same endpoint. For a chain row, `group` carries the CHAIN's
|
||||
* name and `selected` the node its last group hop picked ('' when the exit hop
|
||||
* isn't a group). Per-hop detail is a different read: {@link ChainHopHealth}.
|
||||
*
|
||||
* `ok:false` ⇒ there is no usable measurement and `error` carries the human
|
||||
* reason; every other field is meaningless. Four of those reasons are about the
|
||||
* observatory rather than the path, and must not be rendered as "your target is
|
||||
* broken":
|
||||
*
|
||||
* "not routed by any enabled rule, so nothing measures it — the observatory
|
||||
* only probes paths the rules use"
|
||||
* "the observatory has not reached this target yet — it refreshes on the
|
||||
* global probe interval"
|
||||
* "background probing is disabled, so there is nothing to measure this target
|
||||
* with"
|
||||
* "the observatory's probe through this path failed"
|
||||
*
|
||||
* Only the last one is a health finding. The first three say the measurement
|
||||
* does not exist, which is a different thing and a different fix.
|
||||
*/
|
||||
export interface GroupTestResult {
|
||||
group: string
|
||||
selected: string // the member node the group chose for this test
|
||||
group: string // group name — or a chain name for a chain row
|
||||
selected: string // the member node the group (or the chain's exit group) chose
|
||||
delay_ms: number
|
||||
exit_ip: string // may be '' even when ok
|
||||
exit_country: string // ISO code; may be '' even when ok
|
||||
@@ -1421,25 +1682,30 @@ export interface GroupTestResult {
|
||||
|
||||
/**
|
||||
* GET /api/groups/test — progress plus every result so far. `results` is ALWAYS
|
||||
* an array (never null); `done`/`total` count finished vs targeted groups while
|
||||
* `running` is true. Idle reads `{running:false}` with the last run's results
|
||||
* still attached, so a reload after a test still shows what it found.
|
||||
* an array (never null); `done`/`total` count finished vs targeted groups and
|
||||
* chains while `running` is true. Idle reads `{running:false}` with the last
|
||||
* run's results still attached, so a reload still shows what was last read.
|
||||
*
|
||||
* "Running" means the observatory is working through an out-of-turn refresh pass
|
||||
* over the named targets and this endpoint is collecting what it measures. It is
|
||||
* not the panel dialling anything.
|
||||
*/
|
||||
export interface GroupTestStatus {
|
||||
running: boolean
|
||||
done: number
|
||||
total: number
|
||||
/**
|
||||
* The group names THIS run covers. Always an array (never JSON null); absent
|
||||
* only on daemons older than the split.
|
||||
* The group and chain names THIS run covers. Always an array (never JSON
|
||||
* null); absent only on daemons older than the split.
|
||||
*
|
||||
* It is what makes `running` usable. On its own that flag says only "a group
|
||||
* test is happening somewhere", which is why pressing Test on one group used to
|
||||
* put "measuring…" on every card. The rule: show the in-progress indicator on
|
||||
* card g iff `running && scope.includes(g)`. A run started with a name carries
|
||||
* exactly that name; a run started with no name carries every group, and then
|
||||
* the indicator on every card is correct. The scope PERSISTS after the run
|
||||
* ends, so displayed results stay attributable to the cards they came from.
|
||||
* exactly that name; a run started with no name carries every group and
|
||||
* every chain, and then the indicator on every card is correct. The scope
|
||||
* PERSISTS after the run ends, so displayed results stay attributable to the
|
||||
* cards they came from.
|
||||
*/
|
||||
scope?: string[]
|
||||
results: GroupTestResult[]
|
||||
@@ -1455,18 +1721,24 @@ export interface GroupTestStart {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/groups/test — measure a group's delay and exit address. Pass a group
|
||||
* name to test one; pass nothing (or '') to test every group. Singleton: a second
|
||||
* call while a run is in flight resolves to `{started:false, reason:'already
|
||||
* running'}` rather than failing.
|
||||
* POST /api/groups/test — ask the observatory for an out-of-turn refresh pass,
|
||||
* then report what it measured. Pass a group or chain name to refresh one; pass
|
||||
* nothing (or '') for every group and every chain.
|
||||
*
|
||||
* It does NOT dial. The observatory is the only thing in the daemon that
|
||||
* measures anything, and it measures along the real dial path — so this is the
|
||||
* "don't wait for the next probe interval" button, not a second opinion. The
|
||||
* numbers it returns are the same numbers the cards are already showing, just
|
||||
* fresher. Singleton: a second call while a pass is in flight resolves to
|
||||
* `{started:false, reason:'already running'}` rather than failing.
|
||||
*/
|
||||
export function postGroupsTest(name = ''): Promise<GroupTestStart> {
|
||||
return MOCK
|
||||
? mock.postGroupsTest(name)
|
||||
? mock().postGroupsTest(name)
|
||||
: req<GroupTestStart>('api/groups/test', { method: 'POST', body: JSON.stringify({ name }) })
|
||||
}
|
||||
|
||||
/** GET /api/groups/test — progress + results of the current/last group test. */
|
||||
export function getGroupsTest(): Promise<GroupTestStatus> {
|
||||
return MOCK ? mock.getGroupsTest() : req<GroupTestStatus>('api/groups/test')
|
||||
return MOCK ? mock().getGroupsTest() : req<GroupTestStatus>('api/groups/test')
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/* Buttons — mono, uppercase. .btn is ghost; .btn.primary is solid orange. */
|
||||
/* Buttons — mono, uppercase. .btn is ghost; .btn.primary is solid orange;
|
||||
* .btn.crit is the solid-red destructive commit. */
|
||||
.btn {
|
||||
display: inline-block;
|
||||
padding: 7px 12px;
|
||||
@@ -30,3 +31,16 @@
|
||||
color: #fff;
|
||||
filter: brightness(1.05);
|
||||
}
|
||||
|
||||
/* Destructive commit. The fill is crit stepped a little toward black so white
|
||||
* label text clears 4.5:1 in BOTH themes — the raw --crit is bright enough in
|
||||
* dark mode to fall under it. Red here always means "this removes something". */
|
||||
.btn.crit {
|
||||
border-color: transparent;
|
||||
background: color-mix(in srgb, var(--crit) 88%, #000);
|
||||
color: #fff;
|
||||
}
|
||||
.btn.crit:hover {
|
||||
color: #fff;
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
import './Button.css'
|
||||
import { forwardRef } from 'react'
|
||||
import type { ButtonHTMLAttributes } from 'react'
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
/** `primary` is the solid-orange call to action; `ghost` is the default. */
|
||||
variant?: 'ghost' | 'primary'
|
||||
/**
|
||||
* `primary` is the solid-orange call to action; `crit` is the solid-red
|
||||
* destructive commit (delete, remove) — semantic crit, never the accent;
|
||||
* `ghost` is the default.
|
||||
*/
|
||||
variant?: 'ghost' | 'primary' | 'crit'
|
||||
}
|
||||
|
||||
export function Button({ variant = 'ghost', className, type, ...rest }: ButtonProps) {
|
||||
/** Ref-forwarding so a dialog can park focus on a specific button. */
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
||||
{ variant = 'ghost', className, type, ...rest },
|
||||
ref,
|
||||
) {
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
type={type ?? 'button'}
|
||||
className={['btn', variant === 'primary' ? 'primary' : '', className]
|
||||
.filter(Boolean)
|
||||
.join(' ')}
|
||||
className={['btn', variant === 'ghost' ? '' : variant, className].filter(Boolean).join(' ')}
|
||||
{...rest}
|
||||
/>
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,11 +1,49 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
/**
|
||||
* The panel's wall clock, in the SAME timezone as every timestamp under it.
|
||||
*
|
||||
* It used to read `getUTCHours()` and print "UTC", while `format.ts` renders every
|
||||
* log line, connection event and date through `toLocaleTimeString` — i.e. the
|
||||
* browser's zone. In Moscow that put two clocks three hours apart on one plate,
|
||||
* and the header was the one nobody could reconcile: the router's "started" time
|
||||
* read later than the current time while the uptime said it had been up for hours.
|
||||
*
|
||||
* So the clock follows the rest of the panel — local, and it SAYS which offset
|
||||
* that is, because a bare "12:41:07" beside a router in another zone is the
|
||||
* ambiguity that started this. The zone label is the browser's UTC offset, not an
|
||||
* abbreviation: "MSK"/"CEST" are not derivable everywhere, an offset always is.
|
||||
*
|
||||
* This is the BROWSER's clock, not the router's — the appliance has no RTC. Every
|
||||
* router-sourced instant in the panel is converted to this clock before it is
|
||||
* shown, which is what makes one label at the top honest for the whole page.
|
||||
*/
|
||||
function zoneLabel(d: Date): string {
|
||||
// getTimezoneOffset() is minutes WEST of UTC, so the sign is inverted.
|
||||
const min = -d.getTimezoneOffset()
|
||||
if (min === 0) return 'UTC'
|
||||
const sign = min < 0 ? '−' : '+'
|
||||
const a = Math.abs(min)
|
||||
const h = Math.floor(a / 60)
|
||||
const m = a % 60
|
||||
return `UTC${sign}${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`
|
||||
}
|
||||
|
||||
function format(d: Date): string {
|
||||
const p = (n: number) => String(n).padStart(2, '0')
|
||||
return `${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())} UTC`
|
||||
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())} ${zoneLabel(d)}`
|
||||
}
|
||||
|
||||
/** Live UTC readout, tabular digits, ticking once a second. */
|
||||
/** The full zone name, for the title — "Europe/Moscow" says more than "+3" does. */
|
||||
function zoneName(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Live local readout, tabular digits, ticking once a second. */
|
||||
export function Clock({ className }: { className?: string }) {
|
||||
const [now, setNow] = useState(() => format(new Date()))
|
||||
|
||||
@@ -14,5 +52,13 @@ export function Clock({ className }: { className?: string }) {
|
||||
return () => window.clearInterval(id)
|
||||
}, [])
|
||||
|
||||
return <span className={['clock', className].filter(Boolean).join(' ')}>{now}</span>
|
||||
const zone = zoneName()
|
||||
return (
|
||||
<span
|
||||
className={['clock', className].filter(Boolean).join(' ')}
|
||||
title={zone ? `Your device's clock — ${zone}. Every time in the panel is shown in this zone.` : undefined}
|
||||
>
|
||||
{now}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
/* <ConfirmDialog> — the safety interlock plate.
|
||||
*
|
||||
* This replaces the browser's native confirm dialog, which a browser can mute for
|
||||
* good ("prevent this page from creating additional dialogs"): after that it
|
||||
* returns false with no dialog at all, so every delete button in the panel goes
|
||||
* dead and silent with no way to recover short of a page reload. We draw the
|
||||
* plate ourselves, so nothing can suppress it.
|
||||
*
|
||||
* Faceplate language: a small rack module lifted off the panel — corner screws
|
||||
* (reused from Faceplate.css), an engraved label, a groove above the actions.
|
||||
* Destructive intent is carried by the crit semantic, never by the orange accent:
|
||||
* accent means "this control is active", crit means "this destroys something".
|
||||
*/
|
||||
|
||||
/* The veil is a fixed dark wash in both themes — a light scrim over a light
|
||||
* panel would not read as "the panel is out of reach". Follows the tokens.css
|
||||
* pattern: light base, dark via media query, data-theme overrides win both ways. */
|
||||
.cfm-scrim {
|
||||
--cfm-veil: rgba(33, 29, 21, 0.52);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.cfm-scrim {
|
||||
--cfm-veil: rgba(0, 0, 0, 0.66);
|
||||
}
|
||||
}
|
||||
:root[data-theme='light'] .cfm-scrim {
|
||||
--cfm-veil: rgba(33, 29, 21, 0.52);
|
||||
}
|
||||
:root[data-theme='dark'] .cfm-scrim {
|
||||
--cfm-veil: rgba(0, 0, 0, 0.66);
|
||||
}
|
||||
|
||||
.cfm-scrim {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 200;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
/* Short viewports: the plate scrolls with the veil instead of being clipped. */
|
||||
overflow-y: auto;
|
||||
padding: calc(var(--u, 8px) * 2);
|
||||
background: var(--cfm-veil);
|
||||
animation: cfm-veil-in 0.14s ease-out;
|
||||
}
|
||||
|
||||
.cfm-card {
|
||||
position: relative;
|
||||
width: min(32rem, 100%);
|
||||
max-height: calc(100dvh - var(--u, 8px) * 4);
|
||||
overflow-y: auto;
|
||||
padding: calc(var(--u, 8px) * 3.25);
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 12px;
|
||||
/* same brushed plate as <Faceplate>, one step brighter so it reads as lifted */
|
||||
background:
|
||||
repeating-linear-gradient(
|
||||
90deg,
|
||||
transparent 0 2px,
|
||||
color-mix(in srgb, var(--edge) 30%, transparent) 2px 3px
|
||||
),
|
||||
linear-gradient(180deg, var(--raised), color-mix(in srgb, var(--raised) 82%, var(--panel)));
|
||||
box-shadow:
|
||||
0 1px 0 var(--edge) inset,
|
||||
0 30px 60px -22px var(--shadow),
|
||||
0 4px 12px var(--shadow);
|
||||
animation: cfm-card-in 0.18s cubic-bezier(0.2, 0.7, 0.3, 1);
|
||||
}
|
||||
.cfm-card:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* `still` is set from usePrefersReducedMotion — the plate appears, it never
|
||||
* travels. (The global reduced-motion rule in tokens.css also neutralises the
|
||||
* duration; this keeps the intent explicit at the component.) */
|
||||
.cfm-scrim.still,
|
||||
.cfm-scrim.still .cfm-card {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
@keyframes cfm-veil-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes cfm-card-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.99);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- header: engraved label + state LED ---- */
|
||||
.cfm-hd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: calc(var(--u, 8px) * 1.5);
|
||||
}
|
||||
.cfm-label {
|
||||
flex: 1;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label-wide, 0.24em);
|
||||
color: var(--dim);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* ---- copy ---- */
|
||||
.cfm-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-weight: 700;
|
||||
font-size: 17px;
|
||||
line-height: 1.35;
|
||||
color: var(--ink);
|
||||
/* names can be long and unbroken — wrap rather than push the plate wide */
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.cfm-body {
|
||||
margin: calc(var(--u, 8px) * 1.5) 0 0;
|
||||
max-width: 52ch;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 13.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--dim);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* ---- action bar ---- */
|
||||
.cfm-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: calc(var(--u, 8px));
|
||||
margin-top: calc(var(--u, 8px) * 3);
|
||||
padding-top: calc(var(--u, 8px) * 2);
|
||||
border-top: 1px solid var(--groove);
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.cfm-card {
|
||||
padding: calc(var(--u, 8px) * 2.5);
|
||||
}
|
||||
.cfm-actions {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.cfm-actions .btn {
|
||||
flex: 1 1 auto;
|
||||
text-align: center;
|
||||
}
|
||||
/* screws crowd a small plate — drop them rather than collide with the copy */
|
||||
.cfm-card > .screw {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import './ConfirmDialog.css'
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useId,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Button } from './Button'
|
||||
import { Led } from './Led'
|
||||
import { usePrefersReducedMotion } from './usePrefersReducedMotion'
|
||||
|
||||
/**
|
||||
* How the confirming button is painted.
|
||||
*
|
||||
* crit — the action destroys something. Semantic crit, never the accent.
|
||||
* neutral — the action is a normal commit the operator should read first
|
||||
* (a warning before saving); the accent's call-to-action is correct.
|
||||
*/
|
||||
export type ConfirmTone = 'crit' | 'neutral'
|
||||
|
||||
export interface ConfirmOptions {
|
||||
/** Engraved eyebrow, e.g. "DELETE RULE". Names the operation, not the object. */
|
||||
label?: string
|
||||
/** The question. One line, ends in "?". */
|
||||
title: string
|
||||
/** The consequence — what changes on the router if this goes through. */
|
||||
body?: ReactNode
|
||||
/** Verb on the confirming button. Defaults to "Delete". */
|
||||
confirmLabel?: string
|
||||
/** Verb on the dismissing button. Defaults to "Cancel". */
|
||||
cancelLabel?: string
|
||||
/** Defaults to `crit` — the overwhelmingly common case is a delete. */
|
||||
tone?: ConfirmTone
|
||||
}
|
||||
|
||||
export interface ConfirmDialogProps extends ConfirmOptions {
|
||||
open: boolean
|
||||
/** Called exactly once per dialog, with the operator's answer. */
|
||||
onResolve: (confirmed: boolean) => void
|
||||
}
|
||||
|
||||
const FOCUSABLE =
|
||||
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
|
||||
|
||||
/**
|
||||
* The modal plate itself. Normally reached through `useConfirm()`; exported so a
|
||||
* page that wants to own the open state can render it directly.
|
||||
*
|
||||
* Keyboard contract:
|
||||
* - focus moves to Cancel on open, so a reflex Enter dismisses, never deletes;
|
||||
* - Tab / Shift+Tab cycle inside the plate and cannot reach the page behind it;
|
||||
* - Esc answers "no";
|
||||
* - on close, focus returns to whatever opened the dialog.
|
||||
*/
|
||||
export function ConfirmDialog({
|
||||
open,
|
||||
onResolve,
|
||||
label,
|
||||
title,
|
||||
body,
|
||||
confirmLabel = 'Delete',
|
||||
cancelLabel = 'Cancel',
|
||||
tone = 'crit',
|
||||
}: ConfirmDialogProps) {
|
||||
const titleId = useId()
|
||||
const bodyId = useId()
|
||||
const cardRef = useRef<HTMLDivElement>(null)
|
||||
const cancelRef = useRef<HTMLButtonElement>(null)
|
||||
const openerRef = useRef<HTMLElement | null>(null)
|
||||
const reduced = usePrefersReducedMotion()
|
||||
|
||||
// Take the page out of the tab order, park focus on Cancel, and hand focus
|
||||
// back to the opener when the plate goes away.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const opener = document.activeElement
|
||||
openerRef.current = opener instanceof HTMLElement ? opener : null
|
||||
|
||||
const prevOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
|
||||
// Cancel is the resting place: an Enter or a Space meant for the page lands
|
||||
// on "no". The destructive button is one Tab away, deliberately.
|
||||
;(cancelRef.current ?? cardRef.current)?.focus()
|
||||
|
||||
return () => {
|
||||
document.body.style.overflow = prevOverflow
|
||||
const back = openerRef.current
|
||||
openerRef.current = null
|
||||
if (back && document.contains(back)) back.focus()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
// Esc answers no; Tab is caged. Capture phase so a page-level key handler
|
||||
// never sees keys aimed at the dialog.
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onResolve(false)
|
||||
return
|
||||
}
|
||||
if (e.key !== 'Tab') return
|
||||
const card = cardRef.current
|
||||
if (!card) return
|
||||
const list = Array.from(card.querySelectorAll<HTMLElement>(FOCUSABLE))
|
||||
if (list.length === 0) {
|
||||
e.preventDefault()
|
||||
card.focus()
|
||||
return
|
||||
}
|
||||
const first = list[0]
|
||||
const last = list[list.length - 1]
|
||||
const active = document.activeElement as HTMLElement | null
|
||||
if (!active || !card.contains(active)) {
|
||||
e.preventDefault()
|
||||
;(e.shiftKey ? last : first).focus()
|
||||
} else if (e.shiftKey && active === first) {
|
||||
e.preventDefault()
|
||||
last.focus()
|
||||
} else if (!e.shiftKey && active === last) {
|
||||
e.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true)
|
||||
return () => document.removeEventListener('keydown', onKey, true)
|
||||
}, [open, onResolve])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
className={['cfm-scrim', reduced ? 'still' : ''].filter(Boolean).join(' ')}
|
||||
// A click on the field around the plate means "not now". Mousedown (not
|
||||
// click) so a text selection dragged out of the plate can't dismiss it.
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onResolve(false)
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={`cfm-card tone-${tone}`}
|
||||
ref={cardRef}
|
||||
tabIndex={-1}
|
||||
role="alertdialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={body != null ? bodyId : undefined}
|
||||
>
|
||||
<i className="screw tl" aria-hidden="true" />
|
||||
<i className="screw tr" aria-hidden="true" />
|
||||
<i className="screw bl" aria-hidden="true" />
|
||||
<i className="screw br" aria-hidden="true" />
|
||||
|
||||
{/* Lamp first, then the engraved label — the way a real panel reads, and
|
||||
it keeps the LED off the corner screw. */}
|
||||
<div className="cfm-hd">
|
||||
<Led variant={tone === 'crit' ? 'crit' : 'amber'} />
|
||||
<span className="cfm-label">{label ?? (tone === 'crit' ? 'Confirm delete' : 'Confirm')}</span>
|
||||
</div>
|
||||
|
||||
<h2 className="cfm-title" id={titleId}>
|
||||
{title}
|
||||
</h2>
|
||||
{body != null && (
|
||||
<p className="cfm-body" id={bodyId}>
|
||||
{body}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="cfm-actions">
|
||||
<Button ref={cancelRef} onClick={() => onResolve(false)}>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
<Button variant={tone === 'crit' ? 'crit' : 'primary'} onClick={() => onResolve(true)}>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
// ---- provider + hook --------------------------------------------------------
|
||||
|
||||
interface Request extends ConfirmOptions {
|
||||
id: number
|
||||
resolve: (v: boolean) => void
|
||||
}
|
||||
|
||||
const ConfirmCtx = createContext<((o: ConfirmOptions) => Promise<boolean>) | null>(null)
|
||||
|
||||
/**
|
||||
* Mount once at the app root. Everything below can then ask a question and await
|
||||
* the answer.
|
||||
*/
|
||||
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||
const [req, setReq] = useState<Request | null>(null)
|
||||
const pending = useRef<Request | null>(null)
|
||||
const seq = useRef(0)
|
||||
|
||||
const confirm = useCallback(
|
||||
(opts: ConfirmOptions) =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
// A second question while one is open answers the first with "no" rather
|
||||
// than leaving its promise — and its caller — hanging forever.
|
||||
pending.current?.resolve(false)
|
||||
seq.current += 1
|
||||
const next: Request = { ...opts, id: seq.current, resolve }
|
||||
pending.current = next
|
||||
setReq(next)
|
||||
}),
|
||||
[],
|
||||
)
|
||||
|
||||
const settle = useCallback((confirmed: boolean) => {
|
||||
const open = pending.current
|
||||
pending.current = null
|
||||
setReq(null)
|
||||
open?.resolve(confirmed)
|
||||
}, [])
|
||||
|
||||
// Teardown must not strand a caller mid-await.
|
||||
useEffect(
|
||||
() => () => {
|
||||
pending.current?.resolve(false)
|
||||
pending.current = null
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// A question belongs to the page that asked it. The provider outlives the
|
||||
// hash router, so a navigation would otherwise leave a stale plate floating
|
||||
// over a page it has nothing to do with — answer it "no" and clear it.
|
||||
useEffect(() => {
|
||||
const onNav = () => {
|
||||
if (pending.current) settle(false)
|
||||
}
|
||||
window.addEventListener('hashchange', onNav)
|
||||
return () => window.removeEventListener('hashchange', onNav)
|
||||
}, [settle])
|
||||
|
||||
return (
|
||||
<ConfirmCtx.Provider value={confirm}>
|
||||
{children}
|
||||
{req !== null && <ConfirmDialog key={req.id} open onResolve={settle} {...req} />}
|
||||
</ConfirmCtx.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the operator, get a definite answer:
|
||||
*
|
||||
* const confirm = useConfirm()
|
||||
* if (!(await confirm({ title: 'Delete rule "x"?', body: '…' }))) return
|
||||
*
|
||||
* The returned function is stable, so it is safe in a useCallback dep list. It
|
||||
* always settles — cancel, Esc, click-outside and teardown all resolve `false`;
|
||||
* only the confirming button resolves `true`.
|
||||
*
|
||||
* Name it `confirm` at the call site on purpose: the local binding shadows the
|
||||
* global one inside that component, so an accidental bare `confirm(...)` cannot
|
||||
* reach the suppressible native dialog.
|
||||
*/
|
||||
export function useConfirm(): (o: ConfirmOptions) => Promise<boolean> {
|
||||
const ctx = useContext(ConfirmCtx)
|
||||
if (!ctx) {
|
||||
// Loud on purpose. A fallback that quietly resolved false would rebuild the
|
||||
// exact bug this component exists to kill.
|
||||
throw new Error('useConfirm() needs <ConfirmProvider> above it (mounted in main.tsx)')
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -17,6 +17,8 @@ export { Button } from './Button'
|
||||
export type { ButtonProps } from './Button'
|
||||
export { Select } from './Select'
|
||||
export type { SelectProps, SelectOption } from './Select'
|
||||
export { ConfirmDialog, ConfirmProvider, useConfirm } from './ConfirmDialog'
|
||||
export type { ConfirmDialogProps, ConfirmOptions, ConfirmTone } from './ConfirmDialog'
|
||||
export { Clock } from './Clock'
|
||||
export { CatSuggest } from './CatSuggest'
|
||||
export { SrcPicker } from './SrcPicker'
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// findings.ts — which apply-time finding is shown where.
|
||||
//
|
||||
// Run with `npm test` (node's built-in test runner + native TypeScript
|
||||
// stripping; no test dependency is added to the SPA, which ships inside the
|
||||
// daemon binary).
|
||||
//
|
||||
// Two defects are pinned here.
|
||||
//
|
||||
// 1. THE TRUNCATION NOTE WAS UNREACHABLE. The daemon caps Status.warnings at 50
|
||||
// and overwrites the last slot with an `info` note counting what it dropped.
|
||||
// Overview filtered `info` away wholesale, and the settings-page route keys on
|
||||
// a section (`generate`) that no page owns — so the single line telling the
|
||||
// operator "you are not seeing all of it" reached no screen at all.
|
||||
//
|
||||
// 2. FINDINGS ABOUT AN ENTITY NEVER REACHED THAT ENTITY'S PAGE. The generator
|
||||
// drops a node it cannot build and names it; the Nodes page rendered that node
|
||||
// as an ordinary row with a green toggle, because it never read the findings.
|
||||
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
attentionFindings,
|
||||
entityFindings,
|
||||
findingsByName,
|
||||
sectionNotes,
|
||||
truncationNote,
|
||||
worstSeverity,
|
||||
} from './findings.ts'
|
||||
import type { StatusWarning } from './api.ts'
|
||||
|
||||
const crit = (section: string, name: string, message = 'broken'): StatusWarning => ({
|
||||
severity: 'critical',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
const warn = (section: string, name: string, message = 'degraded'): StatusWarning => ({
|
||||
severity: 'warning',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
const info = (section: string, name: string, message: string): StatusWarning => ({
|
||||
severity: 'info',
|
||||
section,
|
||||
name,
|
||||
message,
|
||||
})
|
||||
|
||||
/** Verbatim from apply/warnings.go finalizeWarnings. */
|
||||
const SUPPRESSED = info(
|
||||
'generate',
|
||||
'',
|
||||
'7 further warning(s) suppressed; run `logread -e shater` for the full list',
|
||||
)
|
||||
|
||||
// --- the truncation note ----------------------------------------------------
|
||||
|
||||
test('the truncation note is found, whatever else is in the list', () => {
|
||||
const note = truncationNote([crit('rule', 'a'), warn('node', 'b'), SUPPRESSED])
|
||||
assert.notEqual(note, null)
|
||||
assert.match(note!.message, /7 further warning/)
|
||||
})
|
||||
|
||||
test('a whole list has no truncation note', () => {
|
||||
assert.equal(truncationNote([crit('rule', 'a'), warn('node', 'b')]), null)
|
||||
assert.equal(truncationNote([]), null)
|
||||
assert.equal(truncationNote(undefined), null)
|
||||
})
|
||||
|
||||
test('an ordinary info note is not mistaken for the truncation note', () => {
|
||||
const notes = [info('untunnelable', 'block', 'Ping and traceroute do not work…')]
|
||||
assert.equal(truncationNote(notes), null)
|
||||
})
|
||||
|
||||
test('the truncation note is kept out of the settings-page notes it would pollute', () => {
|
||||
const all = [info('generate', '', 'cache: moved to /overlay'), SUPPRESSED]
|
||||
const notes = sectionNotes(all, 'generate')
|
||||
assert.equal(notes.length, 1)
|
||||
assert.match(notes[0].message, /cache:/)
|
||||
})
|
||||
|
||||
test('the attention list still carries only critical and warning', () => {
|
||||
const all = [crit('rule', 'a'), warn('node', 'b'), info('untunnelable', 'block', 'x'), SUPPRESSED]
|
||||
const attention = attentionFindings(all)
|
||||
assert.equal(attention.length, 2)
|
||||
assert.ok(attention.every((w) => w.severity !== 'info'))
|
||||
})
|
||||
|
||||
// --- per-entity findings ----------------------------------------------------
|
||||
|
||||
test('a page takes only the sections it owns', () => {
|
||||
const all = [
|
||||
crit('node', 'tokyo-01', 'parse share-link: bad scheme (skipped)'),
|
||||
warn('subscription', 'qomar', 'fetch failed'),
|
||||
crit('rule', 'default', 'never applies'),
|
||||
info('generate', '', 'cache: x'),
|
||||
]
|
||||
const mine = entityFindings(all, ['node', 'subscription'])
|
||||
assert.deepEqual(
|
||||
mine.map((w) => w.name),
|
||||
['tokyo-01', 'qomar'],
|
||||
)
|
||||
})
|
||||
|
||||
test('entity findings never include info notes', () => {
|
||||
const all = [info('node', 'tokyo-01', 'just a note'), SUPPRESSED]
|
||||
assert.equal(entityFindings(all, ['node', 'generate']).length, 0)
|
||||
})
|
||||
|
||||
test('findings index by name, and global (unnamed) ones are left out', () => {
|
||||
const all = [
|
||||
crit('node', 'tokyo-01', 'first'),
|
||||
warn('node', 'tokyo-01', 'second'),
|
||||
crit('node', '', 'global to the section'),
|
||||
]
|
||||
const byName = findingsByName(entityFindings(all, ['node']))
|
||||
assert.equal(byName.size, 1)
|
||||
assert.equal(byName.get('tokyo-01')!.length, 2)
|
||||
})
|
||||
|
||||
test('one lamp per row takes the loudest severity', () => {
|
||||
assert.equal(worstSeverity([warn('node', 'a'), crit('node', 'a')]), 'critical')
|
||||
assert.equal(worstSeverity([warn('node', 'a')]), 'warning')
|
||||
assert.equal(worstSeverity([]), null)
|
||||
})
|
||||
+91
-2
@@ -6,7 +6,8 @@
|
||||
//
|
||||
// critical / warning — something needs attention: a protection promise is
|
||||
// broken, or something you configured isn't in effect. These belong on
|
||||
// Overview, where the operator looks first.
|
||||
// Overview, where the operator looks first — and, when they name an entity,
|
||||
// ALSO on the page that owns that entity (see `entityFindings`).
|
||||
//
|
||||
// info — a statement ABOUT the configuration, not a problem. It never clears,
|
||||
// because nothing is wrong: it is simply describing a choice that was made.
|
||||
@@ -16,9 +17,49 @@
|
||||
// page that never goes away and never asks for anything trains people to skim
|
||||
// the list — which is exactly how a real critical finding gets missed. Anything
|
||||
// standing in the findings list should be something you could act on.
|
||||
//
|
||||
// The one exception is carved out below: the daemon's own note that it dropped
|
||||
// findings to fit the cap. It is `info` by severity and unactionable by nature,
|
||||
// and it is the single most important line in the list, because it is the list
|
||||
// telling you it is not the whole list.
|
||||
|
||||
import type { StatusWarning } from './api'
|
||||
|
||||
/**
|
||||
* The daemon's truncation disclosure, verbatim from apply/warnings.go
|
||||
* finalizeWarnings:
|
||||
*
|
||||
* "%d further warning(s) suppressed; run `logread -e shater` for the full list"
|
||||
*
|
||||
* Matched on the stable clause rather than the whole sentence so a reworded tail
|
||||
* still registers. If this ever stops matching, the failure mode is a list that
|
||||
* silently claims to be complete — which is why `truncationNote` is tested.
|
||||
*/
|
||||
const SUPPRESSED_RE = /further warning\(s\) suppressed/
|
||||
|
||||
/**
|
||||
* The daemon's "this list is incomplete" note, or null when the list is whole.
|
||||
*
|
||||
* Status.warnings is capped at 50, sorted critical-first, and the last slot is
|
||||
* REPLACED by an `info` note counting what was dropped. That note therefore
|
||||
* arrives on the one channel the panel filtered away wholesale: `info` never
|
||||
* reached Overview, and the settings-page route (`sectionNotes`) keys on
|
||||
* section `generate`, which no page owns. So the single line saying "there are
|
||||
* findings you are not being shown" was the only one guaranteed to be invisible.
|
||||
*
|
||||
* Callers must render this WITH the attention list, not instead of it.
|
||||
*/
|
||||
export function truncationNote(warnings: StatusWarning[] | undefined): StatusWarning | null {
|
||||
return (
|
||||
(warnings ?? []).find((w) => w.severity === 'info' && SUPPRESSED_RE.test(w.message)) ?? null
|
||||
)
|
||||
}
|
||||
|
||||
/** Is this the truncation disclosure rather than an ordinary note? */
|
||||
function isTruncationNote(w: StatusWarning): boolean {
|
||||
return w.severity === 'info' && SUPPRESSED_RE.test(w.message)
|
||||
}
|
||||
|
||||
/** Findings that need attention — the Overview list. Info notes are excluded. */
|
||||
export function attentionFindings(warnings: StatusWarning[] | undefined): StatusWarning[] {
|
||||
return (warnings ?? []).filter((w) => w.severity === 'critical' || w.severity === 'warning')
|
||||
@@ -29,10 +70,58 @@ export function attentionFindings(warnings: StatusWarning[] | undefined): Status
|
||||
* (e.g. `untunnelable` → the Networks page's "Other traffic" section). Only info:
|
||||
* a critical/warning is an attention item and stays on Overview, so it can't be
|
||||
* quietly buried on a settings page instead.
|
||||
*
|
||||
* The truncation note is excluded: it is about the LIST, not about any section,
|
||||
* and it has its own home beside the list ({@link truncationNote}).
|
||||
*/
|
||||
export function sectionNotes(
|
||||
warnings: StatusWarning[] | undefined,
|
||||
section: string,
|
||||
): StatusWarning[] {
|
||||
return (warnings ?? []).filter((w) => w.severity === 'info' && w.section === section)
|
||||
return (warnings ?? []).filter(
|
||||
(w) => w.severity === 'info' && w.section === section && !isTruncationNote(w),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The attention findings about entities ONE page owns — for that page to show
|
||||
* beside the entities themselves.
|
||||
*
|
||||
* Overview is where you look when you already suspect something; a page like
|
||||
* Nodes is where you look when you don't. The generator drops a node it cannot
|
||||
* build — an unparseable share link, a WireGuard key materialised twice — and
|
||||
* says so by name ("node \"x\": parse share-link: … (skipped)"), yet that node
|
||||
* kept rendering as an ordinary row with a green toggle, because the page never
|
||||
* read the findings at all. The switch says on; the engine has no such outbound.
|
||||
*
|
||||
* This does NOT move anything off Overview: the same finding appears in both
|
||||
* places, which is correct — one list is "what is wrong with this router", the
|
||||
* other is "what is wrong with this node".
|
||||
*/
|
||||
export function entityFindings(
|
||||
warnings: StatusWarning[] | undefined,
|
||||
sections: readonly string[],
|
||||
): StatusWarning[] {
|
||||
const want = new Set(sections)
|
||||
return attentionFindings(warnings).filter((w) => want.has(w.section))
|
||||
}
|
||||
|
||||
/** Index attention findings by entity name, for badging a row directly. Entries
|
||||
* with an empty `name` are global to their section and are left out. */
|
||||
export function findingsByName(findings: StatusWarning[]): Map<string, StatusWarning[]> {
|
||||
const out = new Map<string, StatusWarning[]>()
|
||||
for (const f of findings) {
|
||||
if (!f.name) continue
|
||||
const list = out.get(f.name)
|
||||
if (list) list.push(f)
|
||||
else out.set(f.name, [f])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** The loudest severity in a set — for a row badge that has room for one lamp. */
|
||||
export function worstSeverity(findings: StatusWarning[]): 'critical' | 'warning' | null {
|
||||
if (findings.some((f) => f.severity === 'critical')) return 'critical'
|
||||
if (findings.length > 0) return 'warning'
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -77,6 +77,39 @@ export function fmtDateTime(unix: number): string {
|
||||
return d && t ? `${d}, ${t}` : d || t
|
||||
}
|
||||
|
||||
// --- remote-list freshness ---------------------------------------------------
|
||||
// A url/geo-sourced list re-fetches on a cadence and the engine reports when it
|
||||
// last pulled (GET /api/ruleset/status). Routing shows this for rule-sets and DNS
|
||||
// shows it for blocklists, so the two readings live here and cannot drift apart.
|
||||
|
||||
/** "updated 3h ago" / "never updated" for a remote list's last fetch (RFC3339). */
|
||||
export function relFetch(iso: string): string {
|
||||
if (!iso) return 'never updated'
|
||||
const t = Date.parse(iso)
|
||||
if (Number.isNaN(t)) return 'never updated'
|
||||
const s = Math.max(0, Math.floor((Date.now() - t) / 1000))
|
||||
if (s < 45) return 'updated just now'
|
||||
const m = Math.floor(s / 60)
|
||||
if (m < 60) return `updated ${m}m ago`
|
||||
const h = Math.floor(m / 60)
|
||||
if (h < 24) return `updated ${h}h ago`
|
||||
const d = Math.floor(h / 24)
|
||||
return `updated ${d}d ago`
|
||||
}
|
||||
|
||||
/** "every 24h" for an auto-update cadence in seconds ("" when there is none). */
|
||||
export function everyLabel(sec: number): string {
|
||||
if (!sec || sec <= 0) return ''
|
||||
if (sec % 3600 === 0) {
|
||||
const h = sec / 3600
|
||||
if (h < 48) return `every ${h}h`
|
||||
if (sec % 86400 === 0) return `every ${sec / 86400}d`
|
||||
return `every ${h}h`
|
||||
}
|
||||
if (sec % 60 === 0) return `every ${sec / 60}m`
|
||||
return `every ${sec}s`
|
||||
}
|
||||
|
||||
/**
|
||||
* A coarse "how long until / since" reading for a unix deadline, relative to now.
|
||||
*
|
||||
|
||||
+26
-5
@@ -2,12 +2,33 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './tokens.css'
|
||||
import { App } from './App'
|
||||
import { initMockBackend } from './api'
|
||||
import { ConfirmProvider } from './components'
|
||||
|
||||
const rootEl = document.getElementById('root')
|
||||
if (!rootEl) throw new Error('#root not found')
|
||||
|
||||
createRoot(rootEl).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
// Settle the fixture question BEFORE the first render: pages read `MOCK` while
|
||||
// they render, so a backend that arrives afterwards would paint half a screen
|
||||
// from the daemon and half from fixtures. In a production build this resolves
|
||||
// immediately and to `false` — the fixtures are not in the bundle to load (see
|
||||
// api.ts initMockBackend and the assertNoMockFixtures plugin in vite.config.ts).
|
||||
function mount() {
|
||||
// ConfirmProvider sits ABOVE <App> so it survives App's early returns (the
|
||||
// unauth / no-link plates) — useConfirm() can never find itself without a host.
|
||||
createRoot(rootEl!).render(
|
||||
<StrictMode>
|
||||
<ConfirmProvider>
|
||||
<App />
|
||||
</ConfirmProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
}
|
||||
|
||||
// A fixture module that fails to load is a broken dev checkout, not a reason to
|
||||
// hand the operator a blank plate — mount anyway and let the shell report that it
|
||||
// cannot reach a daemon, which by then is the truth.
|
||||
void initMockBackend().then(mount, (e) => {
|
||||
console.error('mock backend failed to load; continuing against the real API', e)
|
||||
mount()
|
||||
})
|
||||
|
||||
+381
-150
@@ -6,7 +6,7 @@
|
||||
// state mutates in-memory so the Apply / Confirm / Rollback flow is exercisable.
|
||||
//
|
||||
// Type-only imports from api.ts (erased at build) keep this free of a runtime cycle.
|
||||
import type { ApplyResult, ConnLogEntry, DiscoveredDevice, GroupHealth, GroupMemberHealth, GroupsHealth, GroupTestResult, GroupTestStart, GroupTestStatus, Interface, Model, NodeTestStart, NodeTestStatus, QueryLogEntry, RulesetCategories, RulesetCheck, RulesetStatus, Stats, StatsLogPage, StatsLogQuery, Status, StatusWarning } from './api'
|
||||
import type { ApplyResult, ChainHealth, ChainHopHealth, ConnLogEntry, DiscoveredDevice, GroupHealth, GroupMemberHealth, GroupsHealth, GroupTestResult, GroupTestStart, GroupTestStatus, Interface, Model, Profile, QueryLogEntry, RuleReach, RulesReachability, RulesetCategories, RulesetCheck, RulesetStatus, Stats, StatsLogPage, StatsLogQuery, Status, StatusWarning, Traffic } from './api'
|
||||
|
||||
let armed = false // a pending commit-confirm auto-rollback
|
||||
let hasLastGood = false // a predecessor config exists to roll back to (post-apply)
|
||||
@@ -26,9 +26,6 @@ const CONFIG: Model = {
|
||||
EndpointResolver: '',
|
||||
ProbeURL: 'https://www.gstatic.com/generate_204',
|
||||
ProbeInterval: '60s',
|
||||
// '' = the engine's default tick (every 10 s), NOT off. Left blank on purpose
|
||||
// so `?mock` shows the recommended state and the placeholder that says so.
|
||||
SweepInterval: '',
|
||||
SchemaVersion: 2,
|
||||
// Points at the iface-driven profile below, so `?mock` lands in the WAN-watcher
|
||||
// AUTO-PIN state (not a manual override): the plate must say the router pins this
|
||||
@@ -39,7 +36,7 @@ const CONFIG: Model = {
|
||||
Untunnelable: new URLSearchParams(typeof location === 'undefined' ? '' : location.search).get('untun') ?? 'block',
|
||||
DNSIntercept: true, // force ALL LAN plaintext DNS (:53) through the engine
|
||||
BlockDoH: false, // block known public DoH resolvers so clients fall back to plaintext :53
|
||||
GroupHealth: true, // background group-member health sweep + Targets health stats (default on)
|
||||
GroupHealth: true, // observatory: background probing of used groups/chains + Targets health stats (default on)
|
||||
StatsRingSize: 500, // fixed cap — shows the "limit" rendering (500 rows)
|
||||
StatsTimelineMinutes: 0, // 0 ⇒ "Unlimited" rendering + memory warning
|
||||
StatsMaxDomains: 5000, // fixed cap — shows the "limit" rendering (5000)
|
||||
@@ -132,6 +129,25 @@ const CONFIG: Model = {
|
||||
{ Name: 'via-tunnel', Source: 'subscription', Subscription: 'primary', Strategy: 'leastping', Egress: 'awg' },
|
||||
{ Name: 'fallback', Source: 'subscription', Subscription: 'backup', Strategy: 'roundrobin', Egress: '' },
|
||||
],
|
||||
// Three chains, one per state the hop readout has to render.
|
||||
Chains: [
|
||||
// The owner's real production shape: leave through a WAN interface, cross an
|
||||
// AmneziaWG node, then three subscription groups in series. The leading
|
||||
// `egress:` is NOT a numbered hop — the daemon lifts it into hop 1's entry
|
||||
// detour — so this reports FOUR hops, and hop 3 is dead while its neighbours
|
||||
// answer. That single red notch in the middle of a live path is the entire
|
||||
// reason per-hop health exists, so `?mock` must show it at a glance.
|
||||
{
|
||||
Name: 'ewan-wg-subs',
|
||||
Hops: ['egress:wan', 'node:home-wg', 'group:auto', 'group:stealth', 'group:via-tunnel'],
|
||||
},
|
||||
// Used, but the observatory hasn't come round yet — every hop untested. Not
|
||||
// dead and not healthy: the state the panel most easily renders as a fault.
|
||||
{ Name: 'sub-fresh', Hops: ['node:home-wg', 'group:fallback'] },
|
||||
// No enabled rule targets it, so the observatory skips it entirely and the
|
||||
// daemon never materialises its hops: `used:false` and NO `hops` key.
|
||||
{ Name: 'relay', Hops: ['egress:awg', 'group:auto'] },
|
||||
],
|
||||
Egresses: [
|
||||
{ Name: 'wan', Type: 'interface', Interface: 'wan' },
|
||||
// An AmneziaWG tunnel — the whole point of a group-level egress binding.
|
||||
@@ -145,7 +161,20 @@ const CONFIG: Model = {
|
||||
Rules: [
|
||||
{ Name: 'block-ads', Enabled: true, Order: 10, DstRuleset: ['ad-hosts'], Target: 'block' },
|
||||
{ Name: 'ru-bypass', Enabled: true, Order: 20, DstRuleset: ['ru-inside'], Target: 'direct' },
|
||||
// These two are what make the chains USED — the observatory probes only the
|
||||
// paths an enabled rule can reach, so without them every chain card would
|
||||
// read "not routed" and the hop rail would never appear in `?mock`. Kept
|
||||
// ABOVE the condition-less rule at Order 40, which would otherwise swallow
|
||||
// everything below it and mark them "never applies".
|
||||
{ Name: 'media-via-chain', Enabled: true, Order: 22, DstRuleset: ['yt-geosite'], Target: 'chain:ewan-wg-subs' },
|
||||
{ Name: 'spare-via-chain', Enabled: true, Order: 24, DstRuleset: ['ad-hosts'], Target: 'chain:sub-fresh' },
|
||||
{ Name: 'private-direct', Enabled: true, Order: 30, DstRuleset: ['private-nets'], Target: 'direct' },
|
||||
// A SECOND condition-less rule, above the real default. It reads like a working
|
||||
// rule and does nothing: a rule with no conditions becomes the router's default,
|
||||
// and the last such rule by Order wins — so this one never applies. It is in the
|
||||
// fixture on purpose, to exercise the "never applies" badge; the field config
|
||||
// that prompted it had two rules BOTH named `default` (orders 20 and 100).
|
||||
{ Name: 'default-bypass', Enabled: true, Order: 40, Target: 'direct' },
|
||||
{ Name: 'default-tunnel', Enabled: true, Order: 900, Target: 'group:auto' },
|
||||
],
|
||||
// Named match-lists a rule points DstRuleset at. url + geosite + geoip are remote
|
||||
@@ -165,6 +194,7 @@ const CONFIG: Model = {
|
||||
// to an official remote list; the others are the usual url / inline lists.
|
||||
Blocklists: [
|
||||
{ Name: 'StevenBlack', Enabled: true, Source: 'url', URL: 'https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts', Response: 'nxdomain', UpdateInterval: '24h' },
|
||||
{ Name: 'oisd-basic', Enabled: true, Source: 'url', URL: 'https://big.oisd.nl/domainswild', Response: 'nxdomain', UpdateInterval: '24h' },
|
||||
{ Name: 'telegram-block', Enabled: false, Source: 'geosite', Categories: ['telegram'], Response: 'nxdomain', UpdateInterval: '24h' },
|
||||
],
|
||||
Resolvers: [
|
||||
@@ -240,20 +270,14 @@ const CONFIG: Model = {
|
||||
Enabled: true,
|
||||
Priority: 20,
|
||||
MatchIface: ['wan1'],
|
||||
SchedDays: [],
|
||||
EnableRules: ['default-tunnel'],
|
||||
DisableRules: ['block-ads', 'ru-bypass', 'private-direct'],
|
||||
DefaultTarget: 'group:auto',
|
||||
},
|
||||
{
|
||||
Name: 'evening-direct',
|
||||
Enabled: true,
|
||||
Priority: 10,
|
||||
MatchIface: [],
|
||||
SchedDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
|
||||
SchedStart: '19:00',
|
||||
SchedEnd: '23:00',
|
||||
DefaultTarget: 'direct',
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -300,8 +324,116 @@ const RULESET_STATUS: RulesetStatus[] = [
|
||||
rule_count: 903,
|
||||
},
|
||||
{ tag: 'rs-ru-geoip-ru', name: 'ru-geoip', category: 'ru', kind: 'ruleset', remote: true, last_updated: '', interval_seconds: 86_400, rule_count: 0 },
|
||||
// Blocklists report through the same endpoint under `bl-<name>`, which the DNS
|
||||
// page never asked for — so a list that has NEVER been fetched still read
|
||||
// "filtering". StevenBlack is that case here; oisd-basic is the healthy one, so
|
||||
// both readings are exercisable offline.
|
||||
{ tag: 'bl-StevenBlack', name: 'StevenBlack', category: '', kind: 'blocklist', remote: true, last_updated: '', interval_seconds: 86_400, rule_count: 0 },
|
||||
{
|
||||
tag: 'bl-oisd-basic',
|
||||
name: 'oisd-basic',
|
||||
category: '',
|
||||
kind: 'blocklist',
|
||||
remote: true,
|
||||
last_updated: new Date(Date.now() - 6 * 3600_000).toISOString(),
|
||||
interval_seconds: 86_400,
|
||||
rule_count: 218_431,
|
||||
},
|
||||
// Disabled in CONFIG, so the row reads "off" whatever this says — it exists to
|
||||
// prove the row does not start claiming things the moment a status appears.
|
||||
{ tag: 'bl-telegram-block-telegram', name: 'telegram-block', category: 'telegram', kind: 'blocklist', remote: true, last_updated: '', interval_seconds: 86_400, rule_count: 0 },
|
||||
]
|
||||
|
||||
/** GET /api/rules/reachability. Mirrors the daemon's analysis over CONFIG.Rules:
|
||||
* a rule with no conditions is the router's default, and the LAST such rule by
|
||||
* Order wins — every earlier one can never apply. It reads the live CONFIG so
|
||||
* edits made in `?mock` keep the badge honest.
|
||||
*
|
||||
* It also mirrors model.ResolveActiveProfile + ApplyProfileRuleOverrides, because
|
||||
* `effective_enabled` is the whole point of the endpoint: CONFIG's `mobile-uplink`
|
||||
* is active and both enables and disables rules, so `?mock` shows the same
|
||||
* desired-vs-effective split the field config does. */
|
||||
export async function getRulesReachability(): Promise<RulesReachability> {
|
||||
await wait(60)
|
||||
const rules = CONFIG.Rules ?? []
|
||||
|
||||
// A pin naming an existing, ENABLED profile wins outright. Otherwise auto-select:
|
||||
// highest Priority among enabled profiles, ties by Name, skipping any with an
|
||||
// iface condition (the WAN watcher owns those and expresses its verdict as the pin).
|
||||
const profiles = CONFIG.Profiles ?? []
|
||||
const pinned = String(CONFIG.Globals?.ActiveProfile ?? '').trim()
|
||||
let prof: Profile | null = profiles.find((p) => p.Enabled && p.Name === pinned) ?? null
|
||||
if (!prof) {
|
||||
for (const p of profiles) {
|
||||
if (!p.Enabled || (p.MatchIface ?? []).length > 0) continue
|
||||
const pp = p.Priority ?? 0
|
||||
const bp = prof?.Priority ?? 0
|
||||
if (!prof || pp > bp || (pp === bp && p.Name < prof.Name)) prof = p
|
||||
}
|
||||
}
|
||||
// Enable first, then Disable, so a name in both ends up disabled (Disable wins).
|
||||
const effective = rules.map((r) => Boolean(r.Enabled))
|
||||
if (prof) {
|
||||
const force = (names: string[] | null | undefined, on: boolean) => {
|
||||
for (const raw of names ?? []) {
|
||||
const n = raw.trim()
|
||||
rules.forEach((r, i) => {
|
||||
if (r.Name === n) effective[i] = on
|
||||
})
|
||||
}
|
||||
}
|
||||
force(prof.EnableRules, true)
|
||||
force(prof.DisableRules, false)
|
||||
}
|
||||
const activeProfile = prof
|
||||
|
||||
const out: RuleReach[] = rules.map((r, index) => ({
|
||||
index,
|
||||
name: String(r.Name ?? ''),
|
||||
order: Number(r.Order ?? 0),
|
||||
unreachable: false,
|
||||
shadowed_by_index: -1,
|
||||
effective_enabled: effective[index],
|
||||
// Annotate only where the profile actually FLIPPED the outcome — a profile that
|
||||
// disables an already-off rule has overridden nothing the operator can see.
|
||||
...(activeProfile && effective[index] !== Boolean(r.Enabled)
|
||||
? {
|
||||
overridden_by: activeProfile.Name,
|
||||
override: effective[index] ? ('enabled' as const) : ('disabled' as const),
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
const conditionless = (r: (typeof rules)[number]): boolean =>
|
||||
!(r.Src ?? []).length &&
|
||||
!(r.DstRuleset ?? []).length &&
|
||||
!String(r.DstPort ?? '').trim() &&
|
||||
!String(r.Proto ?? '').trim()
|
||||
const target = (r: (typeof rules)[number]): string =>
|
||||
String(r.Target ?? '').trim() || (r.Egress ? `egress:${String(r.Egress).trim()}` : '')
|
||||
const defaults = rules
|
||||
.map((r, index) => ({ r, index }))
|
||||
// The EFFECTIVE flag, not the configured one: a rule the active profile
|
||||
// switched off is not in force and cannot retire anything (model's
|
||||
// RuleReachability runs over the effective set for the same reason).
|
||||
.filter(({ r, index }) => effective[index] && conditionless(r) && target(r))
|
||||
.sort((a, b) => Number(a.r.Order ?? 0) - Number(b.r.Order ?? 0) || a.index - b.index)
|
||||
const winner = defaults[defaults.length - 1]
|
||||
if (winner) {
|
||||
for (const { index } of defaults.slice(0, -1)) {
|
||||
out[index].unreachable = true
|
||||
out[index].shadowed_by = String(winner.r.Name ?? '')
|
||||
out[index].shadowed_by_index = winner.index
|
||||
out[index].shadowed_by_order = Number(winner.r.Order ?? 0)
|
||||
out[index].reason =
|
||||
`this rule has no conditions, so it sets the default for all traffic — but rule ` +
|
||||
`"${winner.r.Name}" (order ${winner.r.Order}) has none either and comes after it, so ` +
|
||||
`"${target(winner.r)}" is the default the router uses and this rule's target ` +
|
||||
`"${target(rules[index])}" is never applied`
|
||||
}
|
||||
}
|
||||
return { rules: out }
|
||||
}
|
||||
|
||||
export async function getRulesetStatus(): Promise<RulesetStatus[]> {
|
||||
await wait(90)
|
||||
return RULESET_STATUS.map((r) => ({ ...r }))
|
||||
@@ -363,7 +495,20 @@ export async function getRulesetCategories(source: string): Promise<RulesetCateg
|
||||
// ?mock&warn=1 → a full warning set (critical + warning + info) on top
|
||||
// ?mock&ks=open → healthy plane but a FAIL-OPEN kill-switch, which is what
|
||||
// makes the untunnelable policy inert (F8 case 4)
|
||||
function mockPlane(): { plane: 'full' | 'hold' | 'none'; engine: boolean; killSwitch: string } {
|
||||
// ?mock&traffic=… → with the plane FULL, where the traffic actually ends up:
|
||||
// split | direct | blocked | blackout | unknown. `direct` is
|
||||
// the field case the readout used to call "Protected" (one
|
||||
// rule, `default → direct`); `unknown` is a daemon too old to
|
||||
// report. Default: tunnel.
|
||||
// ?mock&plane=unreported → a daemon that sends NO `plane` field. The panel then
|
||||
// knows nothing about what is installed, which is the state
|
||||
// the Kill-switch module used to render as a green "ARMED"
|
||||
// (`undefined !== 'none'` is true).
|
||||
function mockPlane(): {
|
||||
plane: 'full' | 'hold' | 'none' | undefined
|
||||
engine: boolean
|
||||
killSwitch: string
|
||||
} {
|
||||
const q = typeof location === 'undefined' ? '' : location.search
|
||||
const params = new URLSearchParams(q)
|
||||
const killSwitch = params.get('ks') === 'open' ? 'open' : 'closed'
|
||||
@@ -371,9 +516,34 @@ function mockPlane(): { plane: 'full' | 'hold' | 'none'; engine: boolean; killSw
|
||||
if (p === 'hold') return { plane: 'hold', engine: false, killSwitch: 'closed' }
|
||||
if (p === 'none') return { plane: 'none', engine: false, killSwitch }
|
||||
if (p === 'open') return { plane: 'none', engine: false, killSwitch: 'open' }
|
||||
if (p === 'unreported') return { plane: undefined, engine: true, killSwitch }
|
||||
return { plane: 'full', engine: true, killSwitch }
|
||||
}
|
||||
|
||||
// The daemon's verdict on where traffic goes (apply.Status.traffic). Only
|
||||
// meaningful with the plane installed: with the engine down there is no running
|
||||
// config to judge, and the daemon reports the unknown/zero value — so do the same
|
||||
// here rather than leaving a stale "tunnel" behind a dead engine.
|
||||
function mockTraffic(plane: 'full' | 'hold' | 'none' | undefined): Traffic | undefined {
|
||||
if (plane !== 'full') return { verdict: '', default: '', tunnel_rules: 0 }
|
||||
const params = new URLSearchParams(typeof location === 'undefined' ? '' : location.search)
|
||||
switch (params.get('traffic')) {
|
||||
case 'split':
|
||||
return { verdict: 'split', default: 'direct', tunnel_rules: 3 }
|
||||
case 'direct':
|
||||
return { verdict: 'direct', default: 'direct', tunnel_rules: 0 }
|
||||
case 'blocked':
|
||||
return { verdict: 'blocked', default: 'block', tunnel_rules: 2 }
|
||||
case 'blackout':
|
||||
return { verdict: 'blocked', default: 'block', tunnel_rules: 0 }
|
||||
case 'unknown':
|
||||
// A daemon that predates the field sends no `traffic` at all.
|
||||
return undefined
|
||||
default:
|
||||
return { verdict: 'tunnel', default: 'auto', tunnel_rules: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
const MOCK_WARNINGS: StatusWarning[] = [
|
||||
{
|
||||
severity: 'critical',
|
||||
@@ -399,6 +569,29 @@ const MOCK_WARNINGS: StatusWarning[] = [
|
||||
name: 'fakeip-pool',
|
||||
message: 'fake-IP resolver cannot be used as a fallback; the failover chain was not built',
|
||||
},
|
||||
// Two findings the generator attributes to a NODE by name — the class that the
|
||||
// Nodes page never showed, leaving a node the engine threw away rendered as an
|
||||
// ordinary row with a green toggle. Both name real fixture nodes so the row
|
||||
// badge, the collapsed-bucket "N flagged" count and the per-row strip all fire.
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'node',
|
||||
name: 'fi-trojan',
|
||||
message: 'parse share-link: unsupported scheme "trojan+ws" (skipped)',
|
||||
},
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'node',
|
||||
name: 'home-wg',
|
||||
message:
|
||||
'this WireGuard node is materialised twice in the engine config — as "home-wg" and as "group-stealth-m1-home-wg" — and traffic can reach both. A WireGuard peer keeps ONE session per public key, so two devices built from one private key evict each other continuously and NEITHER tunnel passes traffic. Only "home-wg" is kept; everything that routed through "group-stealth-m1-home-wg" is fail-closed (blocked) instead of leaving over the plain WAN',
|
||||
},
|
||||
{
|
||||
severity: 'warning',
|
||||
section: 'subscription',
|
||||
name: 'backup',
|
||||
message: 'fetch failed: dial tcp 203.0.113.9:443: i/o timeout — serving the nodes cached earlier',
|
||||
},
|
||||
{
|
||||
severity: 'info',
|
||||
section: 'generate',
|
||||
@@ -407,6 +600,19 @@ const MOCK_WARNINGS: StatusWarning[] = [
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* The daemon's truncation disclosure, exactly as apply/warnings.go writes it when
|
||||
* the published set overflows the 50-entry cap. Served under `?mock&trunc` so the
|
||||
* "this list is incomplete" rendering is exercisable — it used to be dropped
|
||||
* wholesale by the panel's `info` filter and reached no screen at all.
|
||||
*/
|
||||
const MOCK_TRUNCATION: StatusWarning = {
|
||||
severity: 'info',
|
||||
section: 'generate',
|
||||
name: '',
|
||||
message: '7 further warning(s) suppressed; run `logread -e shater` for the full list',
|
||||
}
|
||||
|
||||
/**
|
||||
* The standing `untunnelable` note the daemon reports. It is INFO, never a
|
||||
* problem: it states a correct, chosen configuration. Two shapes, mirroring the
|
||||
@@ -453,9 +659,12 @@ function mockWarnings(killSwitch: string): StatusWarning[] {
|
||||
const params = new URLSearchParams(q)
|
||||
const mode = (CONFIG.Globals as { Untunnelable?: string }).Untunnelable ?? 'block'
|
||||
const notes = untunnelableNote(mode, killSwitch)
|
||||
// `?trunc` adds the daemon's "the published list is capped" disclosure, which
|
||||
// it appends IN PLACE OF the last entry it had room for.
|
||||
const trunc = params.has('trunc') ? [{ ...MOCK_TRUNCATION }] : []
|
||||
// A degraded plane always comes with the findings that explain it.
|
||||
if (params.has('warn') || params.get('plane')) {
|
||||
return [...MOCK_WARNINGS.map((w) => ({ ...w })), ...notes]
|
||||
if (params.has('warn') || params.get('plane') || trunc.length > 0) {
|
||||
return [...MOCK_WARNINGS.map((w) => ({ ...w })), ...notes, ...trunc]
|
||||
}
|
||||
return notes
|
||||
}
|
||||
@@ -476,6 +685,7 @@ export async function getStatus(): Promise<Status> {
|
||||
can_rollback: armed || hasLastGood,
|
||||
engine_running: engine,
|
||||
plane,
|
||||
traffic: mockTraffic(plane),
|
||||
warnings: mockWarnings(killSwitch),
|
||||
// Process uptime. Anchored to when this tab loaded plus a fixed head start, so
|
||||
// the reading ticks forward across polls exactly like the real daemon's does.
|
||||
@@ -861,11 +1071,13 @@ export async function getStatsConnsPage(q: StatsLogQuery = {}): Promise<StatsLog
|
||||
// derives them the same way — otherwise managing a device in `?mock` would leave the
|
||||
// discovery row stubbornly claiming the opposite. Includes lan + guest networks.
|
||||
const MOCK_HOSTS: ReadonlyArray<Omit<DiscoveredDevice, 'configured' | 'name' | 'blockCount'>> = [
|
||||
{ ip: '192.168.1.20', mac: 'a4:83:e7:11:22:33', hostname: 'macbook-max', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.31', mac: 'f0:18:98:aa:bb:cc', hostname: 'iphone-lena', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.42', mac: '3c:22:fb:44:55:66', hostname: 'ipad-kids', online: true, state: 'idle', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.55', mac: 'dc:a6:32:77:88:99', hostname: 'tv-livingroom', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '10.20.0.14', mac: 'b8:27:eb:aa:00:11', hostname: '', online: false, state: 'offline', network: 'guest', iface: 'br-guest' },
|
||||
// Dual-stacked (v4 lease + link-local v6) — exercises the merged-row display:
|
||||
// one card, primary IP prominent, the extra address as a secondary chip.
|
||||
{ ip: '192.168.1.20', ips: ['192.168.1.20', 'fe80::a683:e7ff:fe11:2233'], mac: 'a4:83:e7:11:22:33', hostname: 'macbook-max', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.31', ips: ['192.168.1.31'], mac: 'f0:18:98:aa:bb:cc', hostname: 'iphone-lena', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.42', ips: ['192.168.1.42'], mac: '3c:22:fb:44:55:66', hostname: 'ipad-kids', online: true, state: 'idle', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '192.168.1.55', ips: ['192.168.1.55'], mac: 'dc:a6:32:77:88:99', hostname: 'tv-livingroom', online: true, state: 'online', network: 'lan', iface: 'br-lan' },
|
||||
{ ip: '10.20.0.14', ips: ['10.20.0.14'], mac: 'b8:27:eb:aa:00:11', hostname: '', online: false, state: 'offline', network: 'guest', iface: 'br-guest' },
|
||||
]
|
||||
|
||||
export async function getDevices(): Promise<DiscoveredDevice[]> {
|
||||
@@ -906,9 +1118,8 @@ export async function getInterfaces(): Promise<Interface[]> {
|
||||
//
|
||||
// The fixture is a real member LIST per group, not four hand-written counters:
|
||||
// the counters are derived from it, so the daemon's invariants (tested ==
|
||||
// alive+dead, alive+dead+untested == total) hold by construction and cannot drift
|
||||
// as the mock probe-all run flips members. Between them the four groups cover
|
||||
// every state the panel has to render:
|
||||
// alive+dead, alive+dead+untested == total) hold by construction and cannot
|
||||
// drift. Between them the four groups cover every state the panel has to render:
|
||||
//
|
||||
// auto 298 members, 122 measured — 119 alive / 3 dead, 176 untested.
|
||||
// The ordinary case: healthy, with a real dead finding AND a large
|
||||
@@ -918,11 +1129,9 @@ export async function getInterfaces(): Promise<Interface[]> {
|
||||
// via-tunnel the same subscription `auto` draws from, dialled through `awg` —
|
||||
// and 0 of 6 alive through it. Two groups, one node set, two
|
||||
// verdicts: the entire reason health is reported per group.
|
||||
// fallback 24 members, NOTHING measured. Neither healthy nor broken — the
|
||||
// state that invites a measurement instead of raising an alarm.
|
||||
//
|
||||
// `?mock&nodetest=1` starts the page with a probe-all already in flight, so the
|
||||
// running/progress rendering is reachable without racing a click.
|
||||
// fallback 24 members, NOTHING measured, and `used:false` — no enabled rule
|
||||
// routes through it, so the observatory never probes it. The card
|
||||
// renders the quiet "unused" note instead of health counters.
|
||||
|
||||
/** City pool for synthesised member names — the real feed looks like this. */
|
||||
const MEMBER_CITIES = [
|
||||
@@ -941,40 +1150,42 @@ interface HealthShape {
|
||||
dead: number
|
||||
/** true ⇒ members are per-group egress copies (health measured through it). */
|
||||
bound: boolean
|
||||
/** An enabled rule reaches this group (GroupHealth.used). false ⇒ the
|
||||
* observatory skips it and its members stay untested. */
|
||||
used: boolean
|
||||
type: string
|
||||
/** Node name the group routes through right now; '' when it hasn't picked. */
|
||||
selectedIndex: number | null
|
||||
}
|
||||
|
||||
const HEALTH_SHAPE: Record<string, HealthShape> = {
|
||||
auto: { total: 298, alive: 119, dead: 3, bound: false, type: 'urltest', selectedIndex: 1 },
|
||||
stealth: { total: 2, alive: 2, dead: 0, bound: true, type: 'urltest', selectedIndex: 0 },
|
||||
'via-tunnel': { total: 6, alive: 0, dead: 6, bound: true, type: 'urltest', selectedIndex: null },
|
||||
fallback: { total: 24, alive: 0, dead: 0, bound: false, type: 'urltest', selectedIndex: null },
|
||||
auto: { total: 298, alive: 119, dead: 3, bound: false, used: true, type: 'urltest', selectedIndex: 1 },
|
||||
stealth: { total: 2, alive: 2, dead: 0, bound: true, used: true, type: 'urltest', selectedIndex: 0 },
|
||||
'via-tunnel': { total: 6, alive: 0, dead: 6, bound: true, used: true, type: 'urltest', selectedIndex: null },
|
||||
fallback: { total: 24, alive: 0, dead: 0, bound: false, used: false, type: 'urltest', selectedIndex: null },
|
||||
}
|
||||
|
||||
/**
|
||||
* `?mock&bias=1|2|3` reproduces the optimistic-ratio defect the owner hit on the
|
||||
* live router, on `auto` — 298 members, the same size he reported — and walks it
|
||||
* through the three states the rendering has to tell apart.
|
||||
* `?mock&bias=1|2` reproduces the optimistic-ratio defect the owner hit on the
|
||||
* live router, on `auto` — 298 members, the same size he reported.
|
||||
*
|
||||
* The mechanism: a group writes an entry when a member answers and DELETES it when
|
||||
* one doesn't, so until the background sweep has been over the group its history
|
||||
* holds nothing but successes. `11 / 11 alive` was that, not health.
|
||||
* The mechanism: a group's own probes write an entry when a member answers and
|
||||
* DELETE it when one doesn't, so until the daemon's board has a failure on
|
||||
* record the history holds nothing but successes. `11 / 11 alive` was that,
|
||||
* not health.
|
||||
*
|
||||
* bias=1 → 11 alive, 0 dead, 287 unchecked, sweep mid-first-pass → NO RATIO
|
||||
* bias=2 → 111 alive, 74 dead, 113 unchecked, sweep mid-first-pass → ratio (a
|
||||
* failure is on record, so something is writing both outcomes)
|
||||
* bias=3 → the same counts with a completed pass → ratio
|
||||
* bias=1 → 11 alive, 0 dead, 287 unchecked → NO RATIO (one-sided sample)
|
||||
* bias=2 → 111 alive, 74 dead, 113 unchecked → ratio (a failure is on record,
|
||||
* so something is writing both outcomes)
|
||||
*
|
||||
* Read 1 → 2 → 3 in order: the reading must get MORE PRECISE, never "good, then
|
||||
* Read 1 → 2 in order: the reading must get MORE PRECISE, never "good, then
|
||||
* suddenly bad".
|
||||
*/
|
||||
const BIAS_STAGE =
|
||||
typeof location === 'undefined' ? null : new URLSearchParams(location.search).get('bias')
|
||||
if (BIAS_STAGE === '1') {
|
||||
HEALTH_SHAPE.auto = { ...HEALTH_SHAPE.auto, alive: 11, dead: 0 }
|
||||
} else if (BIAS_STAGE === '2' || BIAS_STAGE === '3') {
|
||||
} else if (BIAS_STAGE === '2') {
|
||||
HEALTH_SHAPE.auto = { ...HEALTH_SHAPE.auto, alive: 111, dead: 74 }
|
||||
}
|
||||
|
||||
@@ -1000,13 +1211,13 @@ function buildMembers(group: string, shape: HealthShape): GroupMemberHealth[] {
|
||||
return out
|
||||
}
|
||||
|
||||
/** Live member state, keyed by group name. Mutated by the mock probe-all run. */
|
||||
/** Live member state, keyed by group name. */
|
||||
const GROUP_MEMBERS = new Map<string, GroupMemberHealth[]>(
|
||||
Object.entries(HEALTH_SHAPE).map(([g, s]) => [g, buildMembers(g, s)]),
|
||||
)
|
||||
|
||||
/** Derive one group's summary from its member list — never hand-written, so the
|
||||
* daemon's counter invariants hold no matter what the probe-all run did. */
|
||||
* daemon's counter invariants hold by construction. */
|
||||
function summarise(group: string, members: GroupMemberHealth[]): GroupHealth {
|
||||
const shape = HEALTH_SHAPE[group]
|
||||
let alive = 0
|
||||
@@ -1024,6 +1235,7 @@ function summarise(group: string, members: GroupMemberHealth[]): GroupHealth {
|
||||
group,
|
||||
type: shape?.type ?? 'urltest',
|
||||
bound: shape?.bound ?? false,
|
||||
used: shape?.used ?? true,
|
||||
selected: sel != null && members[sel] ? members[sel].node : '',
|
||||
total: members.length,
|
||||
tested: alive + dead,
|
||||
@@ -1050,88 +1262,70 @@ function healthList(): GroupHealth[] {
|
||||
return (CONFIG.Groups ?? []).map((g) => summarise(g.Name, GROUP_MEMBERS.get(g.Name) ?? []))
|
||||
}
|
||||
|
||||
// Mock "Test all nodes" probe-all: a run that advances a batch of members per GET
|
||||
// poll so the progress readout and — the point of the run — untested members
|
||||
// turning into a real alive/dead verdict are both exercisable offline.
|
||||
let nodeTest: NodeTestStatus = { running: false, done: 0, total: 0 }
|
||||
/** Members still to be measured by the in-flight run, as [group, index]. */
|
||||
let nodeTestQueue: Array<[string, number]> = []
|
||||
|
||||
function startNodeTest(): void {
|
||||
nodeTestQueue = []
|
||||
for (const [group, members] of GROUP_MEMBERS) {
|
||||
members.forEach((_, i) => nodeTestQueue.push([group, i]))
|
||||
}
|
||||
nodeTest = { running: true, done: 0, total: nodeTestQueue.length }
|
||||
}
|
||||
|
||||
/** Advance the run by one poll's worth of probes, flipping untested members to a
|
||||
* verdict. Roughly 1 in 12 comes back dead, so the numbers move believably. */
|
||||
function advanceNodeTest(): void {
|
||||
if (!nodeTest.running) return
|
||||
const batch = Math.max(1, Math.round(nodeTest.total / 14))
|
||||
for (let n = 0; n < batch; n++) {
|
||||
const next = nodeTestQueue.shift()
|
||||
if (!next) break
|
||||
const [group, i] = next
|
||||
const m = GROUP_MEMBERS.get(group)?.[i]
|
||||
if (m) {
|
||||
// A bound group stays dead through its tunnel — measuring it again does not
|
||||
// make it work, and pretending otherwise would hide the case the feature
|
||||
// exists to show.
|
||||
const dead = HEALTH_SHAPE[group]?.bound && HEALTH_SHAPE[group]?.alive === 0 ? true : i % 12 === 7
|
||||
m.state = dead ? 'dead' : 'alive'
|
||||
m.delay_ms = dead ? 0 : 38 + ((i * 37) % 460)
|
||||
m.age_seconds = 1 + (i % 5)
|
||||
}
|
||||
nodeTest = { ...nodeTest, done: nodeTest.done + 1 }
|
||||
}
|
||||
if (nodeTestQueue.length === 0) nodeTest = { ...nodeTest, running: false }
|
||||
}
|
||||
|
||||
// ?mock&nodetest=1 lands straight in the running state (see the note above). This
|
||||
// is the HEALTH run — global by nature, so the panel must render it as ONE
|
||||
// indicator in the section header and never as a per-card badge.
|
||||
if (typeof location !== 'undefined' && new URLSearchParams(location.search).has('nodetest')) {
|
||||
startNodeTest()
|
||||
}
|
||||
|
||||
/**
|
||||
* The background sweep's progress, as GET /api/groups/health reports it.
|
||||
* Per-hop health, keyed by chain name — what the observatory measured at each
|
||||
* position of the path, in WIRE order.
|
||||
*
|
||||
* `cycles` is the field with teeth: 0 means the sweep has not been everywhere yet,
|
||||
* so "not measured" is simply "not reached". Once it is ≥ 1 the sweep HAS been
|
||||
* everywhere, and anything still unmeasured lost a reading it used to have.
|
||||
* `ewan-wg-subs` is the fixture that matters, and it encodes the ORDERED WALK.
|
||||
* Hop 1 is the WireGuard node and answers; hop 2 is a subscription group whose
|
||||
* copies answer THROUGH it — 119 of 122 tested alive, which is the reading only a
|
||||
* per-hop probe can produce, since the same members are dialled differently on
|
||||
* their own card. Hop 3 is a group whose members all time out at that position,
|
||||
* and the walk STOPS there: hop 4 is dialled through hop 3, so it was never
|
||||
* dialled at all. It comes back `untested` with `blocked_by` naming hop 3, its
|
||||
* counters zeroed, and `selected` still set — the wrapper has a pick, nothing
|
||||
* crossed it to measure. A dead hop with a live hop under it is not in this
|
||||
* fixture because the daemon can no longer produce one.
|
||||
*
|
||||
* ?mock&sweep=first → mid first pass (cycles 0)
|
||||
* ?mock&sweep=off → sweep disabled; nothing fills in on its own
|
||||
* `sub-fresh` is used but never yet reached: every hop untested, nothing dead,
|
||||
* no block — the other reason a lamp is unlit, and the one that fixes itself.
|
||||
* `relay` is absent from this map on purpose — an unused chain is never
|
||||
* materialised, so the daemon sends no `hops` key at all, which is "nothing
|
||||
* measured", not "no hops".
|
||||
*/
|
||||
function mockSweep(): { enabled: boolean; cursor: number; total: number; cycles: number } {
|
||||
const mode = typeof location === 'undefined' ? null : new URLSearchParams(location.search).get('sweep')
|
||||
if (mode === 'off') return { enabled: false, cursor: 0, total: 0, cycles: 0 }
|
||||
if (mode === 'first') return { enabled: true, cursor: 184, total: 707, cycles: 0 }
|
||||
// The bias walkthrough drives the sweep too: stages 1 and 2 are mid-first-pass
|
||||
// (the cursor advances between them, exactly as the live router's did), stage 3
|
||||
// has completed one. See BIAS_STAGE.
|
||||
if (BIAS_STAGE === '1') return { enabled: true, cursor: 312, total: 896, cycles: 0 }
|
||||
if (BIAS_STAGE === '2') return { enabled: true, cursor: 696, total: 896, cycles: 0 }
|
||||
if (BIAS_STAGE === '3') return { enabled: true, cursor: 148, total: 896, cycles: 1 }
|
||||
return { enabled: true, cursor: 184, total: 707, cycles: 3 }
|
||||
const CHAIN_HOPS: Record<string, ChainHopHealth[]> = {
|
||||
'ewan-wg-subs': [
|
||||
{ index: 1, tag: 'chain-ewan-wg-subs-h1', kind: 'node', exit: false, state: 'alive', delay_ms: 41, age_seconds: 22, selected: '', total: 1, tested: 1, alive: 1, dead: 0, untested: 0 },
|
||||
{ index: 2, tag: 'chain-ewan-wg-subs-h2', kind: 'group', exit: false, state: 'alive', delay_ms: 96, age_seconds: 18, selected: '🇳🇱 Amsterdam-01', total: 298, tested: 122, alive: 119, dead: 3, untested: 176 },
|
||||
{ index: 3, tag: 'chain-ewan-wg-subs-h3', kind: 'group', exit: false, state: 'dead', delay_ms: 0, age_seconds: 15, selected: '', total: 2, tested: 2, alive: 0, dead: 2, untested: 0 },
|
||||
{ index: 4, tag: 'chain-ewan-wg-subs-h4', kind: 'group', exit: true, state: 'untested', delay_ms: 0, age_seconds: -1, selected: '🇸🇬 Singapore-09', total: 6, tested: 0, alive: 0, dead: 0, untested: 6, blocked_by: { index: 3, tag: 'chain-ewan-wg-subs-h3' } },
|
||||
],
|
||||
'sub-fresh': [
|
||||
{ index: 1, tag: 'chain-sub-fresh-h1', kind: 'node', exit: false, state: 'untested', delay_ms: 0, age_seconds: -1, selected: '', total: 1, tested: 0, alive: 0, dead: 0, untested: 1 },
|
||||
{ index: 2, tag: 'chain-sub-fresh-h2', kind: 'group', exit: true, state: 'untested', delay_ms: 0, age_seconds: -1, selected: '', total: 24, tested: 0, alive: 0, dead: 0, untested: 24 },
|
||||
],
|
||||
}
|
||||
|
||||
/** Per-chain reachability plus per-hop health for the Targets page. `used` is the
|
||||
* chain analogue of healthList's field; `hops` is OMITTED (never null, never []),
|
||||
* exactly like the daemon, for a chain the engine never materialised. A stopped
|
||||
* engine reports no chains at all. */
|
||||
function chainHealthList(): ChainHealth[] {
|
||||
if (!mockPlane().engine) return []
|
||||
return (CONFIG.Chains ?? []).map((c) => {
|
||||
const hops = CHAIN_HOPS[c.Name]
|
||||
const h: ChainHealth = { name: c.Name, used: chainUsed(c.Name) }
|
||||
if (hops) h.hops = hops.map((x) => ({ ...x }))
|
||||
return h
|
||||
})
|
||||
}
|
||||
|
||||
/** A chain is "used" when some enabled routing rule (or Final, or a DNS detour)
|
||||
* targets `chain:<name>` — the same reachability the daemon's observatory derives.
|
||||
* Two of the mock's rules do (`media-via-chain` → ewan-wg-subs, `spare-via-chain`
|
||||
* → sub-fresh), so those two chains read used=true and get a hop rail; `relay`
|
||||
* is targeted by nothing and reads used=false, which is the unused note. */
|
||||
function chainUsed(name: string): boolean {
|
||||
const target = `chain:${name}`
|
||||
return (CONFIG.Rules ?? []).some(
|
||||
(r) => r.Enabled !== false && (r.Target === target),
|
||||
)
|
||||
}
|
||||
|
||||
export async function getGroupsHealth(
|
||||
opts: { group?: string; members?: boolean } = {},
|
||||
): Promise<GroupsHealth> {
|
||||
await wait(70)
|
||||
advanceNodeTest()
|
||||
const base: Omit<GroupsHealth, 'groups'> = {
|
||||
node_test_running: nodeTest.running,
|
||||
node_test_done: nodeTest.done,
|
||||
node_test_total: nodeTest.total,
|
||||
// The daemon's background sweep, on by default — it is what lets the panel
|
||||
// promise that untested members resolve without anyone pressing anything.
|
||||
sweep: mockSweep(),
|
||||
}
|
||||
if (opts.group) {
|
||||
const members = GROUP_MEMBERS.get(opts.group)
|
||||
// A stopped engine has no groups at all, so every name is a 404 — the same
|
||||
@@ -1141,21 +1335,20 @@ export async function getGroupsHealth(
|
||||
throw new ApiErrorLike(404, 'no such group in the running engine')
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
groups: [{ ...summarise(opts.group, members), members: members.map((m) => ({ ...m })) }],
|
||||
}
|
||||
}
|
||||
const groups = healthList()
|
||||
if (opts.members) {
|
||||
return {
|
||||
...base,
|
||||
groups: groups.map((g) => ({
|
||||
...g,
|
||||
members: (GROUP_MEMBERS.get(g.group) ?? []).map((m) => ({ ...m })),
|
||||
})),
|
||||
chains: chainHealthList(),
|
||||
}
|
||||
}
|
||||
return { ...base, groups }
|
||||
return { groups, chains: chainHealthList() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1173,29 +1366,23 @@ class ApiErrorLike extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export async function postNodesTest(): Promise<NodeTestStart> {
|
||||
await wait(60)
|
||||
if (nodeTest.running) return { running: true }
|
||||
startNodeTest()
|
||||
return { started: true }
|
||||
}
|
||||
|
||||
export async function getNodesTest(): Promise<NodeTestStatus> {
|
||||
await wait(60)
|
||||
advanceNodeTest()
|
||||
// The constant the daemon publishes (api.ts NODE_TEST_SCOPE, spelled inline
|
||||
// because this module may only import TYPES from api.ts): this run is GLOBAL and
|
||||
// can never be attributed to one group's card.
|
||||
return { ...nodeTest, scope: 'all_nodes' }
|
||||
}
|
||||
|
||||
// Mock group test. Deliberately covers every state the UI has to render, one per
|
||||
// group, so a single offline run exercises all of them:
|
||||
// auto → ok WITH an exit address
|
||||
// stealth → ok WITHOUT one (delay measured, address undeterminable) — a
|
||||
// SUCCESS, and the case the UI most easily gets wrong
|
||||
// fallback → a failure carrying a human reason
|
||||
// Results land one per GET poll, so the running/progress state is visible too.
|
||||
// Mock refresh results. The endpoint no longer dials anything: it asks the
|
||||
// observatory to measure out of turn and reports what the observatory found, so
|
||||
// every row here is a READ of a background measurement. Deliberately covers every
|
||||
// state the UI has to render, one per target, so a single offline run exercises
|
||||
// all of them:
|
||||
// auto → ok WITH an exit address
|
||||
// stealth → ok WITHOUT one (delay measured, address undeterminable) — a
|
||||
// SUCCESS, and the case the UI most easily gets wrong
|
||||
// ewan-wg-subs → the chain: same wire shape, `group` carries the CHAIN's name
|
||||
// and `selected` the node its exit hop picked
|
||||
// via-tunnel → the one honest health FAILURE: a probe that ran and failed
|
||||
// fallback,
|
||||
// relay → not routed at all, so no measurement exists to report
|
||||
// sub-fresh → routed, but the observatory hasn't come round yet
|
||||
// The last three are absence of measurement, not a broken target, and the copy
|
||||
// has to keep them apart. Results land one per GET poll, so the running/progress
|
||||
// state is visible too.
|
||||
const GROUP_TEST_SHAPE: Record<string, Omit<GroupTestResult, 'group' | 'tested_unix'>> = {
|
||||
auto: {
|
||||
selected: 'nl-reality-2',
|
||||
@@ -1213,23 +1400,60 @@ const GROUP_TEST_SHAPE: Record<string, Omit<GroupTestResult, 'group' | 'tested_u
|
||||
ok: true,
|
||||
error: '',
|
||||
},
|
||||
// Dead through its tunnel, exactly as its membership health says — the exit
|
||||
// test and the member health tell the same story about the same group.
|
||||
// The chain, and the pairing that makes the whole feature worth building. A
|
||||
// chain is one series path, so with hop 3 dead the end-to-end probe is never
|
||||
// even attempted — the daemon stops walking there. This row and the hop rail
|
||||
// therefore have to tell one story, not two: both name hop 3, and neither
|
||||
// offers hop 4 as a second suspect. Note the row does NOT say "the probe
|
||||
// failed" — no probe of this chain's exit ran at all — which is why the daemon
|
||||
// has a separate message for it.
|
||||
'ewan-wg-subs': {
|
||||
selected: '',
|
||||
delay_ms: 0,
|
||||
exit_ip: '',
|
||||
exit_country: '',
|
||||
ok: false,
|
||||
error:
|
||||
'hop 3 of this chain was probed and did not answer, so nothing reaches the exit through it — fix that hop first',
|
||||
},
|
||||
// The one real health failure in the fixture: the observatory's probe ran along
|
||||
// this path and did not come back.
|
||||
'via-tunnel': {
|
||||
selected: '',
|
||||
delay_ms: 0,
|
||||
exit_ip: '',
|
||||
exit_country: '',
|
||||
ok: false,
|
||||
error: 'no member answered through egress awg (6 of 6 timed out)',
|
||||
error: 'the observatory’s probe through this path failed',
|
||||
},
|
||||
// Not a health verdict — nothing routes here, so no measurement of it exists.
|
||||
fallback: {
|
||||
selected: '',
|
||||
delay_ms: 0,
|
||||
exit_ip: '',
|
||||
exit_country: '',
|
||||
ok: false,
|
||||
error: 'no reachable node in the group (all 3 members timed out)',
|
||||
error:
|
||||
'not routed by any enabled rule, so nothing measures it — the observatory only probes paths the rules use',
|
||||
},
|
||||
relay: {
|
||||
selected: '',
|
||||
delay_ms: 0,
|
||||
exit_ip: '',
|
||||
exit_country: '',
|
||||
ok: false,
|
||||
error:
|
||||
'not routed by any enabled rule, so nothing measures it — the observatory only probes paths the rules use',
|
||||
},
|
||||
// Routed, materialised, simply not reached yet. Untested is not dead.
|
||||
'sub-fresh': {
|
||||
selected: '',
|
||||
delay_ms: 0,
|
||||
exit_ip: '',
|
||||
exit_country: '',
|
||||
ok: false,
|
||||
error:
|
||||
'the observatory has not reached this target yet — it refreshes on the global probe interval',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1251,9 +1475,13 @@ let groupTestPinned = false
|
||||
export async function postGroupsTest(name = ''): Promise<GroupTestStart> {
|
||||
await wait(60)
|
||||
if (groupTest.running) return { started: false, reason: 'already running' }
|
||||
const all = (CONFIG.Groups ?? []).map((g) => g.Name)
|
||||
// Empty name = every group AND every chain, exactly like the daemon.
|
||||
const all = [
|
||||
...(CONFIG.Groups ?? []).map((g) => g.Name),
|
||||
...(CONFIG.Chains ?? []).map((c) => c.Name),
|
||||
]
|
||||
const targets = name ? all.filter((g) => g === name) : all
|
||||
if (targets.length === 0) return { started: false, reason: `no group named “${name}”` }
|
||||
if (targets.length === 0) return { started: false, reason: `no group or chain named “${name}”` }
|
||||
groupTestQueue = [...targets]
|
||||
groupTestPinned = false
|
||||
groupTest = {
|
||||
@@ -1302,7 +1530,10 @@ export async function getGroupsTest(): Promise<GroupTestStatus> {
|
||||
if (typeof location !== 'undefined') {
|
||||
const want = new URLSearchParams(location.search).get('grouptest')
|
||||
if (want) {
|
||||
const all = (CONFIG.Groups ?? []).map((g) => g.Name)
|
||||
const all = [
|
||||
...(CONFIG.Groups ?? []).map((g) => g.Name),
|
||||
...(CONFIG.Chains ?? []).map((c) => c.Name),
|
||||
]
|
||||
const targets = want === 'all' || want === '1' ? all : all.filter((g) => g === want)
|
||||
if (targets.length > 0) {
|
||||
groupTestQueue = [...targets]
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
/* Alerts section (rendered on Settings) — inherits the Faceplate tokens and the
|
||||
* shared page chrome from App.css (.toast, .mono). Every rule below is a
|
||||
* one-to-one copy of the DNS.css rule the markup used before the section moved
|
||||
* here, renamed `dns-*` → `alr-*` so nothing collides. Orange stays an accent. */
|
||||
|
||||
/* ---- section shell (matches the Settings group plates one-to-one) ---- */
|
||||
.alr-section {
|
||||
margin-top: calc(var(--u, 8px) * 3.5);
|
||||
}
|
||||
.alr-sec-hd {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--groove);
|
||||
}
|
||||
.alr-sec-title {
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-sec-count {
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-sec-note {
|
||||
margin: 10px 2px 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.55;
|
||||
color: var(--dim);
|
||||
max-width: 56ch;
|
||||
}
|
||||
|
||||
/* ---- add form ---- */
|
||||
.alr-add {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
}
|
||||
.alr-add-top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.alr-input {
|
||||
min-width: 0;
|
||||
padding: 9px 12px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
letter-spacing: 0.02em;
|
||||
box-shadow: 0 1px 2px var(--shadow) inset;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.alr-input::placeholder {
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-input:focus-visible {
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.alr-input:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.alr-input--name {
|
||||
flex: 0 1 14rem;
|
||||
}
|
||||
|
||||
/* segmented type picker */
|
||||
.alr-seg {
|
||||
display: inline-flex;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
overflow: hidden;
|
||||
background: var(--sink);
|
||||
}
|
||||
.alr-seg-btn {
|
||||
padding: 8px 14px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.alr-seg-btn + .alr-seg-btn {
|
||||
border-left: 1px solid var(--groove);
|
||||
}
|
||||
.alr-seg-btn.on {
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
.alr-seg-btn:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.alr-resp {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.alr-resp-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-select {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 7px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
letter-spacing: 0.04em;
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-select:focus-visible {
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.alr-add-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-field-err {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--crit);
|
||||
}
|
||||
|
||||
/* ---- rows ---- */
|
||||
.alr-rows {
|
||||
list-style: none;
|
||||
margin: calc(var(--u, 8px) * 2) 0 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.alr-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: calc(var(--u, 8px) * 1.5);
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
var(--raised),
|
||||
color-mix(in srgb, var(--raised) 82%, var(--panel))
|
||||
);
|
||||
box-shadow: 0 1px 0 var(--edge) inset;
|
||||
}
|
||||
.alr-row-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.alr-row-l1 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-row-name {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--ink);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 24ch;
|
||||
}
|
||||
.alr-row-l2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 11.5px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.alr-row-detail {
|
||||
color: var(--dim);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 40ch;
|
||||
}
|
||||
|
||||
/* badge — groove-bordered, not orange (accent stays reserved) */
|
||||
.alr-badge {
|
||||
display: inline-block;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 5px;
|
||||
background: color-mix(in srgb, var(--sink) 60%, transparent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: var(--dim);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.alr-badge--accent {
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--groove));
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.alr-masked {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--faint);
|
||||
text-transform: uppercase;
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.alr-del {
|
||||
flex: none;
|
||||
padding: 6px 12px;
|
||||
font-size: 10.5px;
|
||||
}
|
||||
|
||||
/* ---- empty plate ---- */
|
||||
.alr-empty {
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
padding: calc(var(--u, 8px) * 3);
|
||||
border: 1px dashed var(--groove);
|
||||
border-radius: 9px;
|
||||
background: color-mix(in srgb, var(--raised) 55%, transparent);
|
||||
text-align: center;
|
||||
}
|
||||
.alr-empty-title {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-empty-body {
|
||||
margin: 8px auto 0;
|
||||
max-width: 48ch;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: var(--dim);
|
||||
}
|
||||
|
||||
/* ---- loading skeleton ---- */
|
||||
.alr-skel {
|
||||
height: 62px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(90deg, var(--raised), var(--sink), var(--raised));
|
||||
background-size: 200% 100%;
|
||||
animation: alr-skel-shift 1.4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes alr-skel-shift {
|
||||
from {
|
||||
background-position: 200% 0;
|
||||
}
|
||||
to {
|
||||
background-position: -200% 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* the per-row delivery picker sits inline in the row */
|
||||
.alr-detour {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-detour-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
.alr-detour-select {
|
||||
max-width: 22rem;
|
||||
}
|
||||
|
||||
/* current delivery-path readout on the row */
|
||||
.alr-path {
|
||||
color: var(--faint);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.alr-path[data-active='on'] {
|
||||
color: var(--dim);
|
||||
}
|
||||
.alr-path-name {
|
||||
color: var(--led-on);
|
||||
font-weight: 600;
|
||||
}
|
||||
.alr-path[data-missing='y'] .alr-path-name {
|
||||
color: var(--amber);
|
||||
}
|
||||
.alr-path-flag {
|
||||
color: var(--amber);
|
||||
}
|
||||
|
||||
/* alert delivery: deliver-via picker + fallback toggle + caution note */
|
||||
.alr-delivery {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 20px;
|
||||
}
|
||||
.alr-fallback {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-fallback-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* the per-row delivery controls sit inline in the row (like .alr-detour) */
|
||||
.alr-ctl {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-note {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--amber);
|
||||
max-width: 56ch;
|
||||
}
|
||||
.alr-note--row {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* alert event checkboxes */
|
||||
.alr-events {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.alr-event {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--fp-text, inherit);
|
||||
cursor: pointer;
|
||||
}
|
||||
.alr-event input {
|
||||
accent-color: var(--fp-accent, currentColor);
|
||||
}
|
||||
|
||||
/* ---- responsive ---- */
|
||||
@media (max-width: 640px) {
|
||||
.alr-row {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.alr-row-main {
|
||||
flex-basis: calc(100% - 90px);
|
||||
}
|
||||
.alr-del {
|
||||
margin-left: auto;
|
||||
}
|
||||
.alr-input--name {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.alr-detour {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
/* A <select> won't shrink below its widest option unless it's allowed to:
|
||||
without min-width:0 the long detour labels push the page into a horizontal
|
||||
scroll at 390px. Let them fill the row and clip instead. */
|
||||
.alr-detour-select,
|
||||
.alr-resp .alr-select {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.alr-resp {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
.alr-ctl {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.alr-skel {
|
||||
animation: none;
|
||||
}
|
||||
.alr-input,
|
||||
.alr-seg-btn {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
import './Alerts.css'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import { Button, Toggle, useConfirm } from '../components'
|
||||
import type { Alert, Model } from '../api'
|
||||
|
||||
// The Alerts section — out-of-band notifications (Telegram bot / webhook) for
|
||||
// kill-switch trips, apply failures, new devices and subscription expiry. It
|
||||
// lived at the bottom of the DNS page, which is the last place an operator
|
||||
// looking for "tell me when the tunnel dies" would think to look; it now renders
|
||||
// as a group on Settings. The component owns no I/O: every mutation goes through
|
||||
// the `onSave` prop so Settings keeps a single dirty banner and a single toast.
|
||||
//
|
||||
// NOTE on duplication: the detour helpers below (DetourCatalog, canonDetour,
|
||||
// detourValues, describeDetour, DetourSelect) plus asArray / uniqueName /
|
||||
// maskUrl / EmptyPlate are deliberate copies of the ones in DNS.tsx. DNS keeps
|
||||
// its own for resolvers and DNS rules; extracting a shared module would couple
|
||||
// two pages that otherwise share nothing, and that refactor is out of scope
|
||||
// here. If a third consumer ever appears, promote them then.
|
||||
|
||||
// ---- local Model extension --------------------------------------------------
|
||||
|
||||
/** The Model with the Alerts slice surfaced (index-signature passthrough). */
|
||||
type AlertsModel = Model & { Alerts?: Alert[] | null }
|
||||
|
||||
/**
|
||||
* Every event the daemon actually sends. A retired health-probe event was left
|
||||
* out on purpose: nothing ever fired it, so a channel that subscribed to it would
|
||||
* just stay quiet forever — the one failure mode an alert must not have. Only
|
||||
* events with a live firing path are offered here.
|
||||
*/
|
||||
const ALERT_EVENTS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: 'killswitch', label: 'Kill-switch' },
|
||||
{ id: 'apply_fail', label: 'Apply failure' },
|
||||
{ id: 'new_device', label: 'New device' },
|
||||
{ id: 'sub_expiry', label: 'Subscription expiring' },
|
||||
]
|
||||
|
||||
// Shown when an alert routes through a detour with no direct fallback — the exact
|
||||
// case where a tunnel-down alert could fail to send. The user asked for this.
|
||||
const VIA_NO_FALLBACK_NOTE =
|
||||
'A kill-switch/tunnel-down alert may not send if it routes through the affected tunnel — enable fallback.'
|
||||
|
||||
// ---- helpers (copies of DNS.tsx — see the header note) ----------------------
|
||||
|
||||
const asArray = <T,>(a: T[] | null | undefined): T[] => (a ? a : [])
|
||||
|
||||
const HTTP_RE = /^https?:\/\//i
|
||||
|
||||
/** A remote URL often carries a token in its query/path — show host only. */
|
||||
function maskUrl(url: string): { host: string; masked: boolean } {
|
||||
try {
|
||||
const u = new URL(url)
|
||||
return { host: u.host, masked: u.search !== '' || u.pathname.replace(/\/+$/, '') !== '' }
|
||||
} catch {
|
||||
return { host: url || '—', masked: false }
|
||||
}
|
||||
}
|
||||
|
||||
function uniqueName(base: string, taken: Set<string>): string {
|
||||
const seed = base.trim() || 'alert'
|
||||
if (!taken.has(seed)) return seed
|
||||
let i = 2
|
||||
while (taken.has(`${seed}-${i}`)) i++
|
||||
return `${seed}-${i}`
|
||||
}
|
||||
|
||||
/** The live targets an alert's delivery can be pinned to (the picker). */
|
||||
interface DetourCatalog {
|
||||
groups: string[]
|
||||
chains: string[]
|
||||
egresses: { name: string; type: string }[]
|
||||
nodes: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a stored `Via` to a picker option value. Empty/`direct` ⇒
|
||||
* `direct`; already-prefixed values (`group:`/`chain:`/`egress:`/`node:`) pass
|
||||
* through; a bare legacy name is resolved against the catalog so a still-valid
|
||||
* setup isn't mislabelled; anything unresolved is kept verbatim (shown stale).
|
||||
*/
|
||||
function canonDetour(raw: string | undefined, cat: DetourCatalog): string {
|
||||
const d = (raw ?? '').trim()
|
||||
if (!d || d.toLowerCase() === 'direct') return 'direct'
|
||||
if (/^(node|group|chain|egress):/i.test(d)) return d
|
||||
if (cat.egresses.some((e) => e.name === d)) return `egress:${d}`
|
||||
if (cat.groups.includes(d)) return `group:${d}`
|
||||
if (cat.chains.includes(d)) return `chain:${d}`
|
||||
if (cat.nodes.includes(d)) return `node:${d}`
|
||||
return d
|
||||
}
|
||||
|
||||
/** Every valid option value for a catalog, including `direct`. */
|
||||
function detourValues(cat: DetourCatalog): Set<string> {
|
||||
const s = new Set<string>(['direct'])
|
||||
for (const g of cat.groups) s.add(`group:${g}`)
|
||||
for (const c of cat.chains) s.add(`chain:${c}`)
|
||||
for (const e of cat.egresses) s.add(`egress:${e.name}`)
|
||||
for (const n of cat.nodes) s.add(`node:${n}`)
|
||||
return s
|
||||
}
|
||||
|
||||
/** Describe a canonical detour value for the row readout. */
|
||||
function describeDetour(
|
||||
canon: string,
|
||||
cat: DetourCatalog,
|
||||
valid: Set<string>,
|
||||
): { direct: boolean; prefix: string; name: string; missing: boolean } {
|
||||
if (canon === 'direct') return { direct: true, prefix: '', name: '', missing: false }
|
||||
const i = canon.indexOf(':')
|
||||
const kind = i === -1 ? '' : canon.slice(0, i)
|
||||
const name = i === -1 ? canon : canon.slice(i + 1)
|
||||
const missing = !valid.has(canon)
|
||||
let prefix = 'via'
|
||||
if (kind === 'group') prefix = 'via group'
|
||||
else if (kind === 'chain') prefix = 'via chain'
|
||||
else if (kind === 'node') prefix = 'via node'
|
||||
else if (kind === 'egress') {
|
||||
const eg = cat.egresses.find((e) => e.name === name)
|
||||
prefix = eg?.type === 'interface' ? 'via interface' : 'via egress'
|
||||
}
|
||||
return { direct: false, prefix, name, missing }
|
||||
}
|
||||
|
||||
// ---- section ----------------------------------------------------------------
|
||||
|
||||
export function AlertsSection({
|
||||
config,
|
||||
busy,
|
||||
loading,
|
||||
onSave,
|
||||
}: {
|
||||
/** Full desired-state model; null until it has loaded. */
|
||||
config: Model | null
|
||||
/** A save/apply is in flight — controls lock. */
|
||||
busy: boolean
|
||||
/** The config is still loading — show a skeleton row. */
|
||||
loading: boolean
|
||||
/** Persist the whole next model; resolves true on success (Settings' `save`). */
|
||||
onSave: (next: Model, okMsg: string) => Promise<boolean>
|
||||
}): JSX.Element {
|
||||
const confirm = useConfirm()
|
||||
const model = config as AlertsModel | null
|
||||
const alerts = useMemo<Alert[]>(() => asArray(model?.Alerts), [model])
|
||||
|
||||
// Alerts route through Direct/group/node/egress only (no chains) — the contract
|
||||
// vocabulary for Alert.Via. Built straight from the Model with chains dropped.
|
||||
const alertCatalog = useMemo<DetourCatalog>(
|
||||
() => ({
|
||||
groups: asArray(config?.Groups).map((g) => g.Name),
|
||||
chains: [],
|
||||
egresses: asArray(config?.Egresses).map((e) => ({ name: e.Name, type: e.Type })),
|
||||
nodes: asArray(config?.Nodes).map((n) => n.Name),
|
||||
}),
|
||||
[config],
|
||||
)
|
||||
const alertValid = useMemo(() => detourValues(alertCatalog), [alertCatalog])
|
||||
|
||||
const alertNames = useMemo(() => new Set(alerts.map((a) => a.Name)), [alerts])
|
||||
const alertsOn = alerts.filter((a) => a.Enabled).length
|
||||
|
||||
// ---- mutations — all writes go through onSave -----------------------------
|
||||
const addAlert = useCallback(
|
||||
(draft: Alert): Promise<boolean> => {
|
||||
if (!model) return Promise.resolve(false)
|
||||
const taken = new Set(alerts.map((a) => a.Name))
|
||||
const a: Alert = { ...draft, Name: uniqueName(draft.Name, taken) }
|
||||
return onSave({ ...model, Alerts: [...alerts, a] }, `Added ${a.Name}`)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const toggleAlert = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!model) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Enabled: on } : a))
|
||||
void onSave({ ...model, Alerts: next }, `${next[idx].Name} ${on ? 'enabled' : 'disabled'}`)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const removeAlert = useCallback(
|
||||
async (idx: number) => {
|
||||
if (!model) return
|
||||
const target = alerts[idx]
|
||||
const ok = await confirm({
|
||||
label: 'Delete alert',
|
||||
title: `Delete alert “${target.Name}”?`,
|
||||
body: 'This removes it from the config.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = alerts.filter((_, i) => i !== idx)
|
||||
void onSave({ ...model, Alerts: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[model, alerts, onSave, confirm],
|
||||
)
|
||||
|
||||
const setAlertVia = useCallback(
|
||||
(idx: number, v: string) => {
|
||||
if (!model) return
|
||||
const via = v === 'direct' ? '' : v
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Via: via || undefined } : a))
|
||||
void onSave(
|
||||
{ ...model, Alerts: next },
|
||||
via ? `${next[idx].Name} delivers via ${via}` : `${next[idx].Name} delivers direct`,
|
||||
)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
const setAlertFallback = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!model) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Fallback: on || undefined } : a))
|
||||
void onSave(
|
||||
{ ...model, Alerts: next },
|
||||
`${next[idx].Name} direct fallback ${on ? 'on' : 'off'}`,
|
||||
)
|
||||
},
|
||||
[model, alerts, onSave],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="alr-section" aria-label="Alerts">
|
||||
<header className="alr-sec-hd">
|
||||
<h2 className="alr-sec-title">Alerts</h2>
|
||||
<span className="alr-sec-count mono">
|
||||
{alertsOn} / {alerts.length} on
|
||||
</span>
|
||||
</header>
|
||||
<p className="alr-sec-note">
|
||||
Out-of-band notifications. Delivered <strong>direct to the internet</strong> by default — so a
|
||||
kill-switch or engine-down alert still reaches you when the proxy is down. You can route one
|
||||
through a group, node or egress instead, with a direct fallback if that detour fails.
|
||||
</p>
|
||||
|
||||
<AddAlertForm
|
||||
busy={busy}
|
||||
disabled={!config}
|
||||
taken={alertNames}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onAdd={addAlert}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<ul className="alr-rows" aria-hidden="true">
|
||||
<li className="alr-skel" />
|
||||
</ul>
|
||||
) : alerts.length === 0 ? (
|
||||
<EmptyPlate
|
||||
title="No alerts"
|
||||
body="Add a Telegram bot or a webhook above to get notified when the kill-switch trips, a new device joins, or an apply fails."
|
||||
/>
|
||||
) : (
|
||||
<ul className="alr-rows">
|
||||
{alerts.map((a, i) => (
|
||||
<AlertRow
|
||||
key={`${a.Name}-${i}`}
|
||||
alert={a}
|
||||
busy={busy}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onToggle={(on) => toggleAlert(i, on)}
|
||||
onVia={(v) => setAlertVia(i, v)}
|
||||
onFallback={(on) => setAlertFallback(i, on)}
|
||||
onDelete={() => removeAlert(i)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- alert add form + row ----------------------------------------------------
|
||||
|
||||
function AddAlertForm({
|
||||
busy,
|
||||
disabled,
|
||||
taken,
|
||||
catalog,
|
||||
valid,
|
||||
onAdd,
|
||||
}: {
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
taken: Set<string>
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onAdd: (a: Alert) => Promise<boolean>
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [type, setType] = useState<'telegram' | 'webhook'>('telegram')
|
||||
const [token, setToken] = useState('')
|
||||
const [chatId, setChatId] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [events, setEvents] = useState<string[]>(['killswitch'])
|
||||
const [via, setVia] = useState('direct')
|
||||
const [fallback, setFallback] = useState(false)
|
||||
const [err, setErr] = useState<string | null>(null)
|
||||
|
||||
const reset = () => {
|
||||
setName('')
|
||||
setType('telegram')
|
||||
setToken('')
|
||||
setChatId('')
|
||||
setUrl('')
|
||||
setEvents(['killswitch'])
|
||||
setVia('direct')
|
||||
setFallback(false)
|
||||
}
|
||||
|
||||
const toggleEvent = (id: string) =>
|
||||
setEvents((prev) => (prev.includes(id) ? prev.filter((e) => e !== id) : [...prev, id]))
|
||||
|
||||
const submit = async () => {
|
||||
const nm = name.trim()
|
||||
if (!nm) {
|
||||
setErr('Give the alert a name.')
|
||||
return
|
||||
}
|
||||
if (taken.has(nm)) {
|
||||
setErr(`An alert named “${nm}” already exists.`)
|
||||
return
|
||||
}
|
||||
if (type === 'telegram') {
|
||||
if (!token.trim() || !chatId.trim()) {
|
||||
setErr('Telegram needs a bot token and a chat ID.')
|
||||
return
|
||||
}
|
||||
} else if (!HTTP_RE.test(url.trim())) {
|
||||
setErr('Enter an http(s):// webhook URL.')
|
||||
return
|
||||
}
|
||||
if (events.length === 0) {
|
||||
setErr('Pick at least one event to notify on.')
|
||||
return
|
||||
}
|
||||
setErr(null)
|
||||
const routed = via !== 'direct'
|
||||
const routing = { Via: routed ? via : undefined, Fallback: routed && fallback ? true : undefined }
|
||||
const draft: Alert =
|
||||
type === 'telegram'
|
||||
? { Name: nm, Enabled: true, Type: 'telegram', Token: token.trim(), ChatID: chatId.trim(), Events: events, ...routing }
|
||||
: { Name: nm, Enabled: true, Type: 'webhook', URL: url.trim(), Events: events, ...routing }
|
||||
const ok = await onAdd(draft)
|
||||
if (ok) reset()
|
||||
}
|
||||
|
||||
const routed = via !== 'direct'
|
||||
|
||||
return (
|
||||
<form
|
||||
className="alr-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void submit()
|
||||
}}
|
||||
>
|
||||
<div className="alr-add-top">
|
||||
<input
|
||||
className="alr-input alr-input--name"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Alert name"
|
||||
aria-label="Alert name"
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<div className="alr-seg" role="group" aria-label="Alert type">
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'telegram' ? 'alr-seg-btn on' : 'alr-seg-btn'}
|
||||
aria-pressed={type === 'telegram'}
|
||||
onClick={() => setType('telegram')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Telegram
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'webhook' ? 'alr-seg-btn on' : 'alr-seg-btn'}
|
||||
aria-pressed={type === 'webhook'}
|
||||
onClick={() => setType('webhook')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Webhook
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{type === 'telegram' ? (
|
||||
<>
|
||||
<input
|
||||
className="alr-input"
|
||||
type="password"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Bot token (kept secret)"
|
||||
aria-label="Telegram bot token"
|
||||
value={token}
|
||||
onChange={(e) => {
|
||||
setToken(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<input
|
||||
className="alr-input"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Chat ID (e.g. -1001234567890)"
|
||||
aria-label="Telegram chat ID"
|
||||
value={chatId}
|
||||
onChange={(e) => {
|
||||
setChatId(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<input
|
||||
className="alr-input"
|
||||
type="text"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="https://hooks.example.com/…"
|
||||
aria-label="Webhook URL"
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<fieldset className="alr-events" aria-label="Events to notify on">
|
||||
{ALERT_EVENTS.map((ev) => (
|
||||
<label key={ev.id} className="alr-event">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={events.includes(ev.id)}
|
||||
onChange={() => toggleEvent(ev.id)}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<span>{ev.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className="alr-delivery">
|
||||
<label className="alr-resp">
|
||||
<span className="alr-resp-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={via}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={disabled}
|
||||
ariaLabel="Deliver alert via"
|
||||
onChange={setVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="alr-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={setFallback}
|
||||
label={fallback ? 'Disable direct fallback' : 'Enable direct fallback'}
|
||||
disabled={busy || disabled || !routed}
|
||||
/>
|
||||
<span className="alr-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
{routed && !fallback && (
|
||||
<p className="alr-note" role="note">
|
||||
{VIA_NO_FALLBACK_NOTE}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="alr-add-actions">
|
||||
{err && (
|
||||
<p className="alr-field-err" role="alert">
|
||||
{err}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" variant="primary" disabled={busy || disabled}>
|
||||
{busy ? 'Saving…' : 'Add alert'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertRow({
|
||||
alert,
|
||||
busy,
|
||||
catalog,
|
||||
valid,
|
||||
onToggle,
|
||||
onVia,
|
||||
onFallback,
|
||||
onDelete,
|
||||
}: {
|
||||
alert: Alert
|
||||
busy: boolean
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onToggle: (on: boolean) => void
|
||||
onVia: (v: string) => void
|
||||
onFallback: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
// Never render the token/URL in clear — show a masked descriptor only.
|
||||
const detail = useMemo(() => {
|
||||
if (alert.Type === 'telegram') {
|
||||
return { text: `chat ${alert.ChatID || '—'}`, masked: !!alert.Token }
|
||||
}
|
||||
const { host, masked } = maskUrl(alert.URL ?? '')
|
||||
return { text: host, masked: masked || !!alert.URL }
|
||||
}, [alert.Type, alert.ChatID, alert.Token, alert.URL])
|
||||
|
||||
const events = asArray(alert.Events)
|
||||
const canon = useMemo(() => canonDetour(alert.Via, catalog), [alert.Via, catalog])
|
||||
const route = useMemo(() => describeDetour(canon, catalog, valid), [canon, catalog, valid])
|
||||
const routed = canon !== 'direct'
|
||||
const fallback = alert.Fallback ?? false
|
||||
|
||||
return (
|
||||
<li className="alr-row">
|
||||
<Toggle
|
||||
pressed={alert.Enabled}
|
||||
onChange={onToggle}
|
||||
label={`${alert.Enabled ? 'Disable' : 'Enable'} alert ${alert.Name}`}
|
||||
disabled={busy}
|
||||
/>
|
||||
<div className="alr-row-main">
|
||||
<div className="alr-row-l1">
|
||||
<span className="alr-row-name">{alert.Name}</span>
|
||||
<span className="alr-badge">{alert.Type}</span>
|
||||
{events.map((e) => (
|
||||
<span key={e} className="alr-badge alr-badge--accent">
|
||||
{e}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="alr-row-l2 mono">
|
||||
<span className="alr-row-detail">{detail.text}</span>
|
||||
{detail.masked && (
|
||||
<span className="alr-masked" title="Secret is stored but hidden here">
|
||||
secret hidden
|
||||
</span>
|
||||
)}
|
||||
{route.direct ? (
|
||||
<span className="alr-path">direct</span>
|
||||
) : (
|
||||
<span className="alr-path" data-active="on" data-missing={route.missing ? 'y' : undefined}>
|
||||
{route.prefix} <strong className="alr-path-name">{route.name}</strong>
|
||||
{route.missing && <span className="alr-path-flag"> (missing)</span>}
|
||||
{fallback ? ' · +direct fallback' : ' · no fallback'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{routed && !fallback && <p className="alr-note alr-note--row">{VIA_NO_FALLBACK_NOTE}</p>}
|
||||
</div>
|
||||
<div className="alr-ctl">
|
||||
<label className="alr-detour">
|
||||
<span className="alr-detour-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={canon}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={false}
|
||||
ariaLabel={`Deliver alert ${alert.Name} via`}
|
||||
onChange={onVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="alr-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={onFallback}
|
||||
label={`${fallback ? 'Disable' : 'Enable'} direct fallback for ${alert.Name}`}
|
||||
disabled={busy || !routed}
|
||||
/>
|
||||
<span className="alr-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
<Button
|
||||
className="alr-del"
|
||||
onClick={onDelete}
|
||||
disabled={busy}
|
||||
aria-label={`Delete alert ${alert.Name}`}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** The live delivery picker: option list built from the Model's targets. */
|
||||
function DetourSelect({
|
||||
value,
|
||||
catalog,
|
||||
valid,
|
||||
busy,
|
||||
disabled,
|
||||
ariaLabel,
|
||||
onChange,
|
||||
directLabel = 'Direct (no proxy)',
|
||||
}: {
|
||||
value: string // canonical value
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
ariaLabel: string
|
||||
onChange: (v: string) => void
|
||||
directLabel?: string
|
||||
}) {
|
||||
const missing = value !== 'direct' && !valid.has(value)
|
||||
return (
|
||||
<select
|
||||
className="alr-select alr-detour-select"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={busy || disabled}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<option value="direct">{directLabel}</option>
|
||||
{catalog.groups.length > 0 && (
|
||||
<optgroup label="Groups">
|
||||
{catalog.groups.map((g) => (
|
||||
<option key={g} value={`group:${g}`}>
|
||||
Group {g} (balancer)
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.chains.length > 0 && (
|
||||
<optgroup label="Chains">
|
||||
{catalog.chains.map((c) => (
|
||||
<option key={c} value={`chain:${c}`}>
|
||||
Chain {c}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.egresses.length > 0 && (
|
||||
<optgroup label="Interfaces / egresses">
|
||||
{catalog.egresses.map((e) => (
|
||||
<option key={e.name} value={`egress:${e.name}`}>
|
||||
Interface/egress {e.name}
|
||||
{e.type ? ` (${e.type})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.nodes.length > 0 && (
|
||||
<optgroup label="Nodes">
|
||||
{catalog.nodes.map((n) => (
|
||||
<option key={n} value={`node:${n}`}>
|
||||
Node {n}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{missing && <option value={value}>{value} (missing)</option>}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyPlate({ title, body }: { title: string; body: string }) {
|
||||
return (
|
||||
<div className="alr-empty">
|
||||
<span className="alr-empty-title mono">{title}</span>
|
||||
<p className="alr-empty-body">{body}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+108
-53
@@ -11,6 +11,8 @@ import {
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { Globals, Status } from '../api'
|
||||
import { engineReadout, killSwitchReadout } from '../planeState'
|
||||
import { onPendingConfirmExpire, usePendingConfirm } from '../pendingConfirm'
|
||||
|
||||
// Short, readable config hash — drops the "sha256:" prefix like the footer does.
|
||||
function short(hash: string): string {
|
||||
@@ -25,13 +27,6 @@ function msg(e: unknown): string {
|
||||
|
||||
type Busy = 'apply' | 'confirm' | 'rollback' | null
|
||||
|
||||
/** A pending commit-confirm window: the daemon has armed an auto-rollback. */
|
||||
interface Armed {
|
||||
total: number // the ConfirmTimeout the window started with
|
||||
remaining: number // seconds left before the daemon reverts
|
||||
appliedHash: string // the hash that went live on apply (the "after" of apply)
|
||||
}
|
||||
|
||||
type ActionKind = 'apply' | 'confirm' | 'rollback' | 'expire'
|
||||
interface ActionResult {
|
||||
kind: ActionKind
|
||||
@@ -57,7 +52,11 @@ export default function Apply() {
|
||||
const [configError, setConfigError] = useState<string | null>(null)
|
||||
|
||||
const [busy, setBusy] = useState<Busy>(null)
|
||||
const [armed, setArmed] = useState<Armed | null>(null)
|
||||
// The armed window is app-wide state, not this page's: it is recorded by the
|
||||
// api layer on every apply and survives a reload. Keeping it local is what made
|
||||
// refreshing this tab lose both the countdown and the only button that could
|
||||
// stop it. See pendingConfirm.ts.
|
||||
const armed = usePendingConfirm()
|
||||
const [result, setResult] = useState<ActionResult | null>(null)
|
||||
const [confirmingRollback, setConfirmingRollback] = useState(false)
|
||||
|
||||
@@ -104,32 +103,64 @@ export default function Apply() {
|
||||
void loadConfig()
|
||||
}, [loadConfig])
|
||||
|
||||
// ---- commit-confirm countdown: a calm 1s numeric tick, effect-scoped so the
|
||||
// timer is always cleared on unmount / confirm / rollback (no leaked intervals) ----
|
||||
// The window running out does NOT mean the daemon rolled back.
|
||||
//
|
||||
// apply.ArmRollback captures the data-plane generation when it arms, and on
|
||||
// expiry it compares. If anything re-applied the plane in between — another
|
||||
// panel apply, SIGHUP, a hotplug or the once-a-minute cron reconcile, the WAN
|
||||
// profile auto-switch — it disarms and KEEPS the running config, logging "NOT
|
||||
// rolling back" and nothing else. That is the common case on a production
|
||||
// router, and this page used to print "daemon auto-rolled back to last-good
|
||||
// config" for it: a confident report of an event that did not happen, with a
|
||||
// hash pair underneath that quietly said "unchanged".
|
||||
//
|
||||
// The panel cannot see which branch ran — the daemon says so only in its log.
|
||||
// So it reports the one thing it CAN observe, the live config hash, and waits
|
||||
// for the revert to land before reading it (a rollback is a full re-apply and
|
||||
// does not complete the instant the timer fires).
|
||||
const liveHashRef = useRef('')
|
||||
liveHashRef.current = status?.hash ?? ''
|
||||
useEffect(() => {
|
||||
if (!armed) return
|
||||
if (armed.remaining <= 0) {
|
||||
// Window elapsed — the daemon reverts to last-good on its own. Observe it.
|
||||
const before = armed.appliedHash
|
||||
setArmed(null)
|
||||
flash('Auto-rolled back')
|
||||
let cancelled = false
|
||||
const off = onPendingConfirmExpire(() => {
|
||||
const before = liveHashRef.current
|
||||
flash('Confirm window elapsed')
|
||||
setResult({
|
||||
kind: 'expire',
|
||||
tone: 'warn',
|
||||
text: 'Confirm window elapsed. Reading what the daemon did…',
|
||||
before,
|
||||
after: before,
|
||||
})
|
||||
void (async () => {
|
||||
const after = (await refreshStatus())?.hash ?? ''
|
||||
let after = before
|
||||
for (let i = 0; i < 4 && !cancelled; i++) {
|
||||
await new Promise((r) => window.setTimeout(r, 1500))
|
||||
if (cancelled) return
|
||||
after = (await refreshStatus())?.hash ?? after
|
||||
if (after !== before) break
|
||||
}
|
||||
if (cancelled) return
|
||||
setResult({
|
||||
kind: 'expire',
|
||||
tone: 'warn',
|
||||
text: 'Confirm window elapsed — daemon auto-rolled back to last-good config.',
|
||||
text:
|
||||
after !== before
|
||||
? 'Confirm window elapsed and the live config changed — the daemon reverted to its last-good config.'
|
||||
: 'Confirm window elapsed and the live config has not changed, so this config is still running. ' +
|
||||
'The daemon only reverts if nothing else re-applied the data plane while the window was open; ' +
|
||||
'otherwise it stands down and keeps what is live. Which one happened is in the daemon log — ' +
|
||||
'download it from Settings, or run `logread -e shater`.',
|
||||
before,
|
||||
after,
|
||||
})
|
||||
})()
|
||||
return
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
off()
|
||||
}
|
||||
const id = window.setTimeout(() => {
|
||||
setArmed((a) => (a ? { ...a, remaining: a.remaining - 1 } : a))
|
||||
}, 1000)
|
||||
return () => window.clearTimeout(id)
|
||||
}, [armed, flash, refreshStatus])
|
||||
}, [flash, refreshStatus])
|
||||
|
||||
const confirmWindow = globals?.ConfirmTimeout ?? 0
|
||||
|
||||
@@ -146,8 +177,9 @@ export default function Apply() {
|
||||
return
|
||||
}
|
||||
const after = (await refreshStatus())?.hash ?? before
|
||||
// The window itself was recorded by api.apply(); this branch only writes the
|
||||
// readout for it.
|
||||
if (r.changed && confirmWindow > 0) {
|
||||
setArmed({ total: confirmWindow, remaining: confirmWindow, appliedHash: after })
|
||||
setResult({
|
||||
kind: 'apply',
|
||||
tone: 'good',
|
||||
@@ -179,7 +211,8 @@ export default function Apply() {
|
||||
const doConfirm = useCallback(async () => {
|
||||
const before = status?.hash ?? ''
|
||||
setBusy('confirm')
|
||||
setArmed(null) // stop the countdown immediately; confirm cancels the auto-rollback
|
||||
// api.confirm() clears the shared window on success — the countdown stops the
|
||||
// moment the daemon agrees, not the moment we asked.
|
||||
try {
|
||||
const r = await apiConfirm()
|
||||
if (r.error) {
|
||||
@@ -208,7 +241,7 @@ export default function Apply() {
|
||||
const before = status?.hash ?? ''
|
||||
setConfirmingRollback(false)
|
||||
setBusy('rollback')
|
||||
setArmed(null) // rolling back also cancels any pending confirm window
|
||||
// api.rollback() clears the shared window on success (rolling back ends it).
|
||||
try {
|
||||
const r = await apiRollback()
|
||||
if (r.error) {
|
||||
@@ -237,19 +270,37 @@ export default function Apply() {
|
||||
}, [status, flash, refreshStatus])
|
||||
|
||||
// ---- derived display state (mirrors Overview's LED semantics) ----
|
||||
const killArmed = globals ? globals.KillSwitch === 'closed' : false
|
||||
const engineVariant: LedVariant = !status
|
||||
? 'off'
|
||||
: status.running && status.active
|
||||
? 'on'
|
||||
: status.running
|
||||
? 'amber'
|
||||
: 'crit'
|
||||
const dataVariant: LedVariant = status?.table ? 'on' : status?.running ? 'amber' : 'off'
|
||||
//
|
||||
// The LIVE kill-switch wins over the saved one, exactly as on Overview: this row
|
||||
// is a status readout, and the config on disk can already differ from what is
|
||||
// installed. Falls back to the config only while /api/status is unread.
|
||||
const killArmed = (status?.kill_switch ?? globals?.KillSwitch ?? 'closed') === 'closed'
|
||||
// Whether that setting is actually installed — same three-plus-unknown reading
|
||||
// as Overview, so the two pages cannot disagree about the same router.
|
||||
const kill = killSwitchReadout(status, globals?.KillSwitch)
|
||||
const killWord =
|
||||
kill.state === 'open'
|
||||
? 'open'
|
||||
: kill.state === 'armed'
|
||||
? 'fail-closed'
|
||||
: kill.state === 'inert'
|
||||
? 'closed · not in effect'
|
||||
: 'closed · not reported'
|
||||
// Every engine mark on this page comes from ONE reading, and that reading is
|
||||
// able to say "stopped" — see planeState.engineState for why `status.running`
|
||||
// could not. This page is where someone lands when the network is down; three
|
||||
// green lamps here were the difference between "I broke it" and "nothing broke".
|
||||
const engine = engineReadout(status)
|
||||
const engineVariant: LedVariant = engine.variant
|
||||
// No nft table means there is no data plane at all. Under a fail-closed switch
|
||||
// that is a leak (crit); under an open one it is the documented choice (amber).
|
||||
// It used to go amber whenever `running` was true — i.e. always — and unlit
|
||||
// otherwise, so the one state worth shouting about had no colour of its own.
|
||||
const dataVariant: LedVariant = status?.table ? 'on' : !status ? 'off' : killArmed ? 'crit' : 'amber'
|
||||
const configVariant: LedVariant = status?.enabled ? 'on' : 'amber'
|
||||
|
||||
const liveHash = short(status?.hash ?? '')
|
||||
const pct = armed ? Math.max(0, Math.round((armed.remaining / armed.total) * 100)) : 0
|
||||
const pct = armed ? Math.max(0, Math.round((armed.remaining / armed.pending.total) * 100)) : 0
|
||||
|
||||
// Only offer rollback when the daemon says one would revert something: an armed
|
||||
// commit-confirm snapshot, or an engine last-good predecessor. When false there
|
||||
@@ -264,9 +315,7 @@ export default function Apply() {
|
||||
label="Engine"
|
||||
variant={engineVariant}
|
||||
pulse={engineVariant === 'on'}
|
||||
value={
|
||||
!status ? 'checking…' : status.running ? (status.active ? 'active' : 'idle') : 'stopped'
|
||||
}
|
||||
value={engine.word}
|
||||
/>
|
||||
<StatusPip
|
||||
label="Config"
|
||||
@@ -278,11 +327,7 @@ export default function Apply() {
|
||||
variant={dataVariant}
|
||||
value={status?.table ? 'nft installed' : 'no table'}
|
||||
/>
|
||||
<StatusPip
|
||||
label="Kill-switch"
|
||||
variant={killArmed ? 'on' : 'amber'}
|
||||
value={killArmed ? 'fail-closed' : 'open'}
|
||||
/>
|
||||
<StatusPip label="Kill-switch" variant={kill.variant} value={killWord} />
|
||||
</div>
|
||||
|
||||
{statusError && (
|
||||
@@ -310,9 +355,13 @@ export default function Apply() {
|
||||
unit="· sha256"
|
||||
led={{ variant: configVariant }}
|
||||
rows={[
|
||||
{ k: 'engine', v: status?.running ? 'running' : 'stopped', hot: !status?.running },
|
||||
{ k: 'data plane', v: status?.table ? 'nft installed' : 'no table' },
|
||||
{ k: 'kill-switch', v: killArmed ? 'fail-closed' : 'open', hot: !killArmed },
|
||||
{ k: 'engine', v: engine.word, hot: engineVariant === 'crit' },
|
||||
{
|
||||
k: 'data plane',
|
||||
v: status?.table ? 'nft installed' : 'no table',
|
||||
hot: dataVariant === 'crit',
|
||||
},
|
||||
{ k: 'kill-switch', v: killWord, hot: kill.variant === 'crit' || !killArmed },
|
||||
]}
|
||||
/>
|
||||
<Module
|
||||
@@ -325,7 +374,7 @@ export default function Apply() {
|
||||
}
|
||||
led={{ variant: engineVariant }}
|
||||
rows={[
|
||||
{ k: 'state', v: !status ? 'checking…' : status.active ? 'active' : 'idle' },
|
||||
{ k: 'state', v: engine.word, hot: engineVariant === 'crit' },
|
||||
{ k: 'config', v: status?.enabled ? 'enabled' : 'disabled' },
|
||||
{ k: 'schema', v: globals ? `v${globals.SchemaVersion}` : '—' },
|
||||
]}
|
||||
@@ -362,9 +411,13 @@ export default function Apply() {
|
||||
</div>
|
||||
<div className="cc-info">
|
||||
<p className="cc-copy">
|
||||
Applied config <span className="mono">{short(armed.appliedHash)}</span> is live but
|
||||
not yet kept. Confirm to keep it — otherwise the daemon rolls back to the last-good
|
||||
config when the timer hits zero.
|
||||
{/* The live hash IS the applied one while a window is open — that
|
||||
is what "live but not kept" means — so the readout survives a
|
||||
reload instead of depending on what this tab remembers. */}
|
||||
Applied config <span className="mono">{liveHash}</span> is live but not yet kept.
|
||||
Confirm to keep it. At zero the daemon rolls back to the last-good config — unless
|
||||
something else re-applies the data plane first, in which case it stands down and
|
||||
keeps whatever is live.
|
||||
</p>
|
||||
<div className="cc-bar" aria-hidden="true">
|
||||
<span className="cc-bar-fill" style={{ width: `${pct}%` }} />
|
||||
@@ -481,7 +534,9 @@ function labelFor(kind: ActionKind): string {
|
||||
case 'rollback':
|
||||
return 'Rollback'
|
||||
case 'expire':
|
||||
return 'Auto-rollback'
|
||||
// NOT "Auto-rollback": on expiry the daemon either reverts or stands down,
|
||||
// and this page cannot tell which. Name the event it did observe.
|
||||
return 'Window elapsed'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+80
-68
@@ -387,6 +387,79 @@
|
||||
.dns-row-state[data-active='on'] {
|
||||
color: var(--led-on);
|
||||
}
|
||||
/* A list that is switched on but has nothing loaded is not "off" and is certainly
|
||||
not "filtering" — warn semantics, the same amber the badges use. */
|
||||
.dns-row-state[data-active='warn'] {
|
||||
color: var(--amber);
|
||||
}
|
||||
|
||||
/* ---- remote-list freshness (mirrors the rule-set rows on Routing) ---- */
|
||||
.dns-row-sync {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.dns-sync-fresh {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
color: var(--dim);
|
||||
}
|
||||
.dns-sync-fresh[data-never='y'] {
|
||||
color: var(--amber);
|
||||
}
|
||||
.dns-sync-every,
|
||||
.dns-sync-rules {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: 0.02em;
|
||||
color: var(--faint);
|
||||
}
|
||||
.dns-sync-every::before {
|
||||
content: '↻ ';
|
||||
}
|
||||
.dns-sync-update {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border: 1px solid var(--accent-soft);
|
||||
border-radius: 5px;
|
||||
background: var(--raised);
|
||||
color: var(--accent);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label);
|
||||
text-transform: uppercase;
|
||||
cursor: pointer;
|
||||
transition: color 0.12s, border-color 0.12s, background 0.12s;
|
||||
}
|
||||
.dns-sync-update:hover:not(:disabled) {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||
}
|
||||
.dns-sync-update:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.dns-sync-update:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.dns-sync-spin {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border: 2px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
border-top-color: var(--accent);
|
||||
border-radius: 50%;
|
||||
animation: dns-sync-spin 0.7s linear infinite;
|
||||
}
|
||||
@keyframes dns-sync-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* badge — groove-bordered, not orange (accent stays reserved) */
|
||||
.dns-badge {
|
||||
@@ -575,80 +648,19 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* alert delivery: deliver-via picker + fallback toggle + caution note */
|
||||
.dns-alert-delivery {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 20px;
|
||||
}
|
||||
.dns-fallback {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dns-fallback-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-label, 0.18em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* the per-alert-row delivery controls sit inline in the row (like .dns-detour) */
|
||||
.dns-alert-ctl {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.dns-alert-note {
|
||||
margin: 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--amber);
|
||||
max-width: 56ch;
|
||||
}
|
||||
.dns-alert-note--row {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.dns-alert-ctl {
|
||||
flex-basis: 100%;
|
||||
order: 3;
|
||||
}
|
||||
}
|
||||
|
||||
/* alert event checkboxes */
|
||||
.dns-events {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.dns-event {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--fp-text, inherit);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dns-event input {
|
||||
accent-color: var(--fp-accent, currentColor);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dns-skel {
|
||||
animation: none;
|
||||
}
|
||||
/* No spin under reduced motion — the static ring + "Updating…" label carry it. */
|
||||
.dns-sync-spin {
|
||||
animation: none;
|
||||
border-top-color: color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
}
|
||||
.dns-chip,
|
||||
.dns-input,
|
||||
.dns-seg-btn {
|
||||
.dns-seg-btn,
|
||||
.dns-sync-update {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
+237
-499
@@ -1,8 +1,16 @@
|
||||
import './DNS.css'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button, CatSuggest, Led, SrcPicker, Toggle } from '../components'
|
||||
import { apply as apiApply, getConfig, putConfig, ApiError } from '../api'
|
||||
import type { Alert, DNSRule, Model, Resolver } from '../api'
|
||||
import { Button, CatSuggest, Led, SrcPicker, Toggle, useConfirm } from '../components'
|
||||
import {
|
||||
apply as apiApply,
|
||||
getConfig,
|
||||
getRulesetStatus,
|
||||
putConfig,
|
||||
updateRuleset as apiUpdateRuleset,
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { DNSRule, Model, Resolver, RulesetStatus } from '../api'
|
||||
import { everyLabel, relFetch } from '../format'
|
||||
|
||||
// The DNS / Blocklists page is a thin editor over the desired-state Model —
|
||||
// exactly like Nodes.tsx. Every edit rewrites the relevant slice in-place, PUTs
|
||||
@@ -52,28 +60,9 @@ type GlobalsX = Model['Globals'] & { DNSFilter?: boolean }
|
||||
type DNSModel = Model & {
|
||||
Blocklists?: Blocklist[] | null
|
||||
Allowlists?: Allowlist[] | null
|
||||
Alerts?: Alert[] | null
|
||||
DNSRules?: DNSRule[] | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Every event the daemon actually sends. A retired health-probe event was left
|
||||
* out on purpose: nothing ever fired it, so a channel that subscribed to it would
|
||||
* just stay quiet forever — the one failure mode an alert must not have. Only
|
||||
* events with a live firing path are offered here.
|
||||
*/
|
||||
const ALERT_EVENTS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: 'killswitch', label: 'Kill-switch' },
|
||||
{ id: 'apply_fail', label: 'Apply failure' },
|
||||
{ id: 'new_device', label: 'New device' },
|
||||
{ id: 'sub_expiry', label: 'Subscription expiring' },
|
||||
]
|
||||
|
||||
// Shown when an alert routes through a detour with no direct fallback — the exact
|
||||
// case where a tunnel-down alert could fail to send. The user asked for this.
|
||||
const VIA_NO_FALLBACK_NOTE =
|
||||
'A kill-switch/tunnel-down alert may not send if it routes through the affected tunnel — enable fallback.'
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
const asArray = <T,>(a: T[] | null | undefined): T[] => (a ? a : [])
|
||||
@@ -220,6 +209,7 @@ function describeDetour(
|
||||
// ---- page ------------------------------------------------------------------
|
||||
|
||||
export default function DNS() {
|
||||
const confirm = useConfirm()
|
||||
const [config, setConfig] = useState<DNSModel | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
|
||||
@@ -301,7 +291,6 @@ export default function DNS() {
|
||||
const blocklists = useMemo(() => asArray(config?.Blocklists), [config])
|
||||
const allowlists = useMemo(() => asArray(config?.Allowlists), [config])
|
||||
const resolvers = useMemo<Resolver[]>(() => asArray(config?.Resolvers), [config])
|
||||
const alerts = useMemo<Alert[]>(() => asArray(config?.Alerts), [config])
|
||||
// Ascending Order — the engine evaluates DNS rules first-match, so the list is
|
||||
// shown and edited in the order it actually runs.
|
||||
const dnsRules = useMemo<DNSRule[]>(
|
||||
@@ -309,6 +298,68 @@ export default function DNS() {
|
||||
[config],
|
||||
)
|
||||
|
||||
// ---- did the lists actually LOAD? -----------------------------------------
|
||||
//
|
||||
// A blocklist row said "filtering" whenever the list and the master switch were
|
||||
// both on. Neither of those is evidence that anything is being blocked: a
|
||||
// url/geosite list is fetched by the engine, the daemon treats a failed fetch as
|
||||
// a CRITICAL apply finding, and the row went on saying "filtering" through it.
|
||||
// The Routing page had already been given this reading for rule-sets — the same
|
||||
// endpoint, the same tags (`bl-<name>` / `al-<name>`) — and the DNS page never
|
||||
// asked. Slow poll: lists refresh on a ~24h cadence, so 15s only has to catch a
|
||||
// manual Update-now. Grouped by NAME because a geosite list with N categories
|
||||
// reports N records.
|
||||
const [listStatus, setListStatus] = useState<Map<string, RulesetStatus[]>>(new Map())
|
||||
const [updatingLists, setUpdatingLists] = useState<Set<string>>(new Set())
|
||||
const loadListStatus = useCallback(async () => {
|
||||
try {
|
||||
const all = await getRulesetStatus()
|
||||
const m = new Map<string, RulesetStatus[]>()
|
||||
for (const s of all) {
|
||||
if (s.kind !== 'blocklist' && s.kind !== 'allowlist') continue
|
||||
const key = `${s.kind}:${s.name}`
|
||||
const arr = m.get(key)
|
||||
if (arr) arr.push(s)
|
||||
else m.set(key, [s])
|
||||
}
|
||||
setListStatus(m)
|
||||
} catch {
|
||||
// Engine stopped or an older daemon — keep the last reading. The row falls
|
||||
// back to "load not reported", which claims nothing either way.
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
void loadListStatus()
|
||||
const id = window.setInterval(() => void loadListStatus(), 15000)
|
||||
return () => window.clearInterval(id)
|
||||
}, [loadListStatus])
|
||||
|
||||
const updateList = useCallback(
|
||||
async (kind: 'blocklist' | 'allowlist', name: string) => {
|
||||
const key = `${kind}:${name}`
|
||||
setUpdatingLists((prev) => new Set(prev).add(key))
|
||||
try {
|
||||
// One geo list can hold several categories, each its own engine tag.
|
||||
const recs = listStatus.get(key) ?? []
|
||||
const tags = recs.length
|
||||
? recs.map((r) => r.tag)
|
||||
: [`${kind === 'blocklist' ? 'bl' : 'al'}-${name}`]
|
||||
for (const tag of tags) await apiUpdateRuleset(tag)
|
||||
await loadListStatus()
|
||||
flash(`${name} refreshed`)
|
||||
} catch (e) {
|
||||
flash(`Refresh failed — ${errText(e)}`)
|
||||
} finally {
|
||||
setUpdatingLists((prev) => {
|
||||
const next = new Set(prev)
|
||||
next.delete(key)
|
||||
return next
|
||||
})
|
||||
}
|
||||
},
|
||||
[listStatus, loadListStatus, flash],
|
||||
)
|
||||
|
||||
const blOn = blocklists.filter((b) => b.Enabled).length
|
||||
const alOn = allowlists.filter((a) => a.Enabled).length
|
||||
const blNames = useMemo(() => new Set(blocklists.map((b) => b.Name)), [blocklists])
|
||||
@@ -422,15 +473,19 @@ export default function DNS() {
|
||||
)
|
||||
|
||||
const removeBlocklist = useCallback(
|
||||
(idx: number) => {
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = blocklists[idx]
|
||||
if (!window.confirm(`Delete blocklist “${target.Name}”? This removes it from the config.`))
|
||||
return
|
||||
const ok = await confirm({
|
||||
label: 'Delete blocklist',
|
||||
title: `Delete blocklist “${target.Name}”?`,
|
||||
body: 'This removes it from the config.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = blocklists.filter((_, i) => i !== idx)
|
||||
void save({ ...config, Blocklists: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[config, blocklists, save],
|
||||
[config, blocklists, save, confirm],
|
||||
)
|
||||
|
||||
// ---- allowlist mutations --------------------------------------------------
|
||||
@@ -457,15 +512,19 @@ export default function DNS() {
|
||||
)
|
||||
|
||||
const removeAllowlist = useCallback(
|
||||
(idx: number) => {
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = allowlists[idx]
|
||||
if (!window.confirm(`Delete allowlist “${target.Name}”? This removes it from the config.`))
|
||||
return
|
||||
const ok = await confirm({
|
||||
label: 'Delete allowlist',
|
||||
title: `Delete allowlist “${target.Name}”?`,
|
||||
body: 'This removes it from the config.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = allowlists.filter((_, i) => i !== idx)
|
||||
void save({ ...config, Allowlists: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[config, allowlists, save],
|
||||
[config, allowlists, save, confirm],
|
||||
)
|
||||
|
||||
// ---- resolver mutations ---------------------------------------------------
|
||||
@@ -491,15 +550,58 @@ export default function DNS() {
|
||||
[config, resolvers, save],
|
||||
)
|
||||
|
||||
/**
|
||||
* Delete a resolver, saying what it was still wired into.
|
||||
*
|
||||
* The three GLOBAL slots (default, fallback, endpoint) are cleared here, because
|
||||
* a global pointing at nothing is never what anyone meant. The DNS RULES are a
|
||||
* different matter: each one is a decision about which queries go where, and
|
||||
* silently deleting or repointing them would change where a device's DNS goes
|
||||
* without saying so. So they are named instead and left alone — the dialog is
|
||||
* where the operator finds out they exist, which is precisely what this page
|
||||
* used to skip: it cleared the two globals without a word and never mentioned
|
||||
* the rules at all.
|
||||
*/
|
||||
const removeResolver = useCallback(
|
||||
(idx: number) => {
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = resolvers[idx]
|
||||
if (!window.confirm(`Delete resolver “${target.Name}”? This removes it from the config.`))
|
||||
return
|
||||
const next = resolvers.filter((_, i) => i !== idx)
|
||||
// Don't leave default/fallback pointing at a resolver that no longer exists.
|
||||
const g = { ...config.Globals }
|
||||
const slots: string[] = []
|
||||
if (g.ResolverDefault === target.Name) slots.push('the default resolver')
|
||||
if (g.ResolverFallback === target.Name) slots.push('the fallback resolver')
|
||||
if (g.EndpointResolver === target.Name) slots.push('the endpoint resolver')
|
||||
const usedBy = dnsRules.filter((r) => r.Resolver === target.Name)
|
||||
|
||||
const parts: string[] = []
|
||||
if (slots.length > 0) {
|
||||
parts.push(
|
||||
`It is ${slots.join(' and ')} — ${
|
||||
slots.length === 1 ? 'that slot is' : 'those slots are'
|
||||
} cleared, so DNS falls back to the engine's built-in resolution.`,
|
||||
)
|
||||
}
|
||||
if (usedBy.length === 1) {
|
||||
parts.push(
|
||||
`One DNS rule still sends queries to it (order ${usedBy[0].Order}). It is left as it is and will have nowhere to resolve — repoint it before you apply.`,
|
||||
)
|
||||
} else if (usedBy.length > 1) {
|
||||
parts.push(
|
||||
`${usedBy.length} DNS rules still send queries to it (orders ${usedBy
|
||||
.map((r) => r.Order)
|
||||
.join(', ')}). They are left as they are and will have nowhere to resolve — repoint them before you apply.`,
|
||||
)
|
||||
}
|
||||
if (parts.length === 0) parts.push('Nothing else in the config points at it.')
|
||||
|
||||
const ok = await confirm({
|
||||
label: 'Delete resolver',
|
||||
title: `Delete resolver “${target.Name}”?`,
|
||||
body: parts.join(' '),
|
||||
})
|
||||
if (!ok) return
|
||||
const next = resolvers.filter((_, i) => i !== idx)
|
||||
// Don't leave default/fallback/endpoint pointing at a resolver that's gone.
|
||||
const cleared: string[] = []
|
||||
if (g.ResolverDefault === target.Name) {
|
||||
g.ResolverDefault = ''
|
||||
@@ -509,12 +611,16 @@ export default function DNS() {
|
||||
g.ResolverFallback = ''
|
||||
cleared.push('fallback')
|
||||
}
|
||||
if (g.EndpointResolver === target.Name) {
|
||||
g.EndpointResolver = ''
|
||||
cleared.push('endpoint')
|
||||
}
|
||||
const msg = cleared.length
|
||||
? `Deleted ${target.Name} — cleared ${cleared.join(' & ')}`
|
||||
: `Deleted ${target.Name}`
|
||||
void save({ ...config, Globals: g, Resolvers: next }, msg)
|
||||
},
|
||||
[config, resolvers, save],
|
||||
[config, resolvers, dnsRules, save, confirm],
|
||||
)
|
||||
|
||||
const setResolverDefault = useCallback(
|
||||
@@ -578,84 +684,21 @@ export default function DNS() {
|
||||
)
|
||||
|
||||
const removeDNSRule = useCallback(
|
||||
(idx: number) => {
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = dnsRules[idx]
|
||||
if (!window.confirm(`Delete this DNS rule? Matching queries fall back to the default resolver.`))
|
||||
return
|
||||
const ok = await confirm({
|
||||
label: 'Delete DNS rule',
|
||||
title: 'Delete this DNS rule?',
|
||||
body: 'Matching queries fall back to the default resolver.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = dnsRules.filter((_, i) => i !== idx)
|
||||
void save({ ...config, DNSRules: next }, `Deleted DNS rule → ${target.Resolver}`)
|
||||
},
|
||||
[config, dnsRules, save],
|
||||
[config, dnsRules, save, confirm],
|
||||
)
|
||||
|
||||
// ---- alert mutations ------------------------------------------------------
|
||||
const addAlert = useCallback(
|
||||
(draft: Alert): Promise<boolean> => {
|
||||
if (!config) return Promise.resolve(false)
|
||||
const taken = new Set(alerts.map((a) => a.Name))
|
||||
const a: Alert = { ...draft, Name: uniqueName(draft.Name, taken) }
|
||||
return save({ ...config, Alerts: [...alerts, a] }, `Added ${a.Name}`)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const toggleAlert = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!config) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Enabled: on } : a))
|
||||
void save({ ...config, Alerts: next }, `${next[idx].Name} ${on ? 'enabled' : 'disabled'}`)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const removeAlert = useCallback(
|
||||
(idx: number) => {
|
||||
if (!config) return
|
||||
const target = alerts[idx]
|
||||
if (!window.confirm(`Delete alert “${target.Name}”? This removes it from the config.`)) return
|
||||
const next = alerts.filter((_, i) => i !== idx)
|
||||
void save({ ...config, Alerts: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const setAlertVia = useCallback(
|
||||
(idx: number, v: string) => {
|
||||
if (!config) return
|
||||
const via = v === 'direct' ? '' : v
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Via: via || undefined } : a))
|
||||
void save(
|
||||
{ ...config, Alerts: next },
|
||||
via ? `${next[idx].Name} delivers via ${via}` : `${next[idx].Name} delivers direct`,
|
||||
)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
const setAlertFallback = useCallback(
|
||||
(idx: number, on: boolean) => {
|
||||
if (!config) return
|
||||
const next = alerts.map((a, i) => (i === idx ? { ...a, Fallback: on || undefined } : a))
|
||||
void save(
|
||||
{ ...config, Alerts: next },
|
||||
`${next[idx].Name} direct fallback ${on ? 'on' : 'off'}`,
|
||||
)
|
||||
},
|
||||
[config, alerts, save],
|
||||
)
|
||||
|
||||
// Alerts route through Direct/group/node/egress only (no chains) — the contract
|
||||
// vocabulary for Alert.Via. Reuse the resolver detour catalog with chains dropped.
|
||||
const alertCatalog = useMemo<DetourCatalog>(
|
||||
() => ({ ...detourCatalog, chains: [] }),
|
||||
[detourCatalog],
|
||||
)
|
||||
const alertValid = useMemo(() => detourValues(alertCatalog), [alertCatalog])
|
||||
|
||||
const alertNames = useMemo(() => new Set(alerts.map((a) => a.Name)), [alerts])
|
||||
const alertsOn = alerts.filter((a) => a.Enabled).length
|
||||
|
||||
const loading = config === null && loadError === null
|
||||
|
||||
return (
|
||||
@@ -883,8 +926,11 @@ export default function DNS() {
|
||||
categories={b.Categories}
|
||||
response={b.Response}
|
||||
filterOn={dnsFilterOn}
|
||||
statuses={listStatus.get(`blocklist:${b.Name}`) ?? null}
|
||||
updating={updatingLists.has(`blocklist:${b.Name}`)}
|
||||
busy={busy}
|
||||
onToggle={(on) => toggleBlocklist(i, on)}
|
||||
onUpdateNow={() => void updateList('blocklist', b.Name)}
|
||||
onDelete={() => removeBlocklist(i)}
|
||||
/>
|
||||
))}
|
||||
@@ -942,9 +988,13 @@ export default function DNS() {
|
||||
url={a.URL}
|
||||
path={a.Path}
|
||||
entries={a.Entries}
|
||||
categories={a.Categories}
|
||||
filterOn={dnsFilterOn}
|
||||
statuses={listStatus.get(`allowlist:${a.Name}`) ?? null}
|
||||
updating={updatingLists.has(`allowlist:${a.Name}`)}
|
||||
busy={busy}
|
||||
onToggle={(on) => toggleAllowlist(i, on)}
|
||||
onUpdateNow={() => void updateList('allowlist', a.Name)}
|
||||
onDelete={() => removeAllowlist(i)}
|
||||
/>
|
||||
))}
|
||||
@@ -1069,57 +1119,6 @@ export default function DNS() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ---- 5. ALERTS ---- */}
|
||||
<div className="dns-section" aria-label="Alerts">
|
||||
<header className="dns-sec-hd">
|
||||
<h2 className="dns-sec-title">Alerts</h2>
|
||||
<span className="dns-sec-count mono">
|
||||
{alertsOn} / {alerts.length} on
|
||||
</span>
|
||||
</header>
|
||||
<p className="dns-sec-note">
|
||||
Out-of-band notifications. Delivered <strong>direct to the internet</strong> by default — so a
|
||||
kill-switch or engine-down alert still reaches you when the proxy is down. You can route one
|
||||
through a group, node or egress instead, with a direct fallback if that detour fails.
|
||||
</p>
|
||||
|
||||
<AddAlertForm
|
||||
busy={busy}
|
||||
disabled={!config}
|
||||
taken={alertNames}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onAdd={addAlert}
|
||||
/>
|
||||
|
||||
{loading ? (
|
||||
<ul className="dns-rows" aria-hidden="true">
|
||||
<li className="dns-skel" />
|
||||
</ul>
|
||||
) : alerts.length === 0 ? (
|
||||
<EmptyPlate
|
||||
title="No alerts"
|
||||
body="Add a Telegram bot or a webhook above to get notified when the kill-switch trips, a new device joins, or an apply fails."
|
||||
/>
|
||||
) : (
|
||||
<ul className="dns-rows">
|
||||
{alerts.map((a, i) => (
|
||||
<AlertRow
|
||||
key={`${a.Name}-${i}`}
|
||||
alert={a}
|
||||
busy={busy}
|
||||
catalog={alertCatalog}
|
||||
valid={alertValid}
|
||||
onToggle={(on) => toggleAlert(i, on)}
|
||||
onVia={(v) => setAlertVia(i, v)}
|
||||
onFallback={(on) => setAlertFallback(i, on)}
|
||||
onDelete={() => removeAlert(i)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{toast && (
|
||||
<div className="toast" role="status">
|
||||
{toast}
|
||||
@@ -1129,342 +1128,6 @@ export default function DNS() {
|
||||
)
|
||||
}
|
||||
|
||||
// ---- alert add form + row --------------------------------------------------
|
||||
|
||||
function AddAlertForm({
|
||||
busy,
|
||||
disabled,
|
||||
taken,
|
||||
catalog,
|
||||
valid,
|
||||
onAdd,
|
||||
}: {
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
taken: Set<string>
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onAdd: (a: Alert) => Promise<boolean>
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [type, setType] = useState<'telegram' | 'webhook'>('telegram')
|
||||
const [token, setToken] = useState('')
|
||||
const [chatId, setChatId] = useState('')
|
||||
const [url, setUrl] = useState('')
|
||||
const [events, setEvents] = useState<string[]>(['killswitch'])
|
||||
const [via, setVia] = useState('direct')
|
||||
const [fallback, setFallback] = useState(false)
|
||||
const [err, setErr] = useState<string | null>(null)
|
||||
|
||||
const reset = () => {
|
||||
setName('')
|
||||
setType('telegram')
|
||||
setToken('')
|
||||
setChatId('')
|
||||
setUrl('')
|
||||
setEvents(['killswitch'])
|
||||
setVia('direct')
|
||||
setFallback(false)
|
||||
}
|
||||
|
||||
const toggleEvent = (id: string) =>
|
||||
setEvents((prev) => (prev.includes(id) ? prev.filter((e) => e !== id) : [...prev, id]))
|
||||
|
||||
const submit = async () => {
|
||||
const nm = name.trim()
|
||||
if (!nm) {
|
||||
setErr('Give the alert a name.')
|
||||
return
|
||||
}
|
||||
if (taken.has(nm)) {
|
||||
setErr(`An alert named “${nm}” already exists.`)
|
||||
return
|
||||
}
|
||||
if (type === 'telegram') {
|
||||
if (!token.trim() || !chatId.trim()) {
|
||||
setErr('Telegram needs a bot token and a chat ID.')
|
||||
return
|
||||
}
|
||||
} else if (!HTTP_RE.test(url.trim())) {
|
||||
setErr('Enter an http(s):// webhook URL.')
|
||||
return
|
||||
}
|
||||
if (events.length === 0) {
|
||||
setErr('Pick at least one event to notify on.')
|
||||
return
|
||||
}
|
||||
setErr(null)
|
||||
const routed = via !== 'direct'
|
||||
const routing = { Via: routed ? via : undefined, Fallback: routed && fallback ? true : undefined }
|
||||
const draft: Alert =
|
||||
type === 'telegram'
|
||||
? { Name: nm, Enabled: true, Type: 'telegram', Token: token.trim(), ChatID: chatId.trim(), Events: events, ...routing }
|
||||
: { Name: nm, Enabled: true, Type: 'webhook', URL: url.trim(), Events: events, ...routing }
|
||||
const ok = await onAdd(draft)
|
||||
if (ok) reset()
|
||||
}
|
||||
|
||||
const routed = via !== 'direct'
|
||||
|
||||
return (
|
||||
<form
|
||||
className="dns-add"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
void submit()
|
||||
}}
|
||||
>
|
||||
<div className="dns-add-top">
|
||||
<input
|
||||
className="dns-input dns-input--name"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Alert name"
|
||||
aria-label="Alert name"
|
||||
value={name}
|
||||
onChange={(e) => {
|
||||
setName(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<div className="dns-seg" role="group" aria-label="Alert type">
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'telegram' ? 'dns-seg-btn on' : 'dns-seg-btn'}
|
||||
aria-pressed={type === 'telegram'}
|
||||
onClick={() => setType('telegram')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Telegram
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={type === 'webhook' ? 'dns-seg-btn on' : 'dns-seg-btn'}
|
||||
aria-pressed={type === 'webhook'}
|
||||
onClick={() => setType('webhook')}
|
||||
disabled={busy || disabled}
|
||||
>
|
||||
Webhook
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{type === 'telegram' ? (
|
||||
<>
|
||||
<input
|
||||
className="dns-input"
|
||||
type="password"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Bot token (kept secret)"
|
||||
aria-label="Telegram bot token"
|
||||
value={token}
|
||||
onChange={(e) => {
|
||||
setToken(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<input
|
||||
className="dns-input"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="Chat ID (e.g. -1001234567890)"
|
||||
aria-label="Telegram chat ID"
|
||||
value={chatId}
|
||||
onChange={(e) => {
|
||||
setChatId(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<input
|
||||
className="dns-input"
|
||||
type="text"
|
||||
inputMode="url"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
placeholder="https://hooks.example.com/…"
|
||||
aria-label="Webhook URL"
|
||||
value={url}
|
||||
onChange={(e) => {
|
||||
setUrl(e.target.value)
|
||||
if (err) setErr(null)
|
||||
}}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
)}
|
||||
|
||||
<fieldset className="dns-events" aria-label="Events to notify on">
|
||||
{ALERT_EVENTS.map((ev) => (
|
||||
<label key={ev.id} className="dns-event">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={events.includes(ev.id)}
|
||||
onChange={() => toggleEvent(ev.id)}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<span>{ev.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
|
||||
<div className="dns-alert-delivery">
|
||||
<label className="dns-resp">
|
||||
<span className="dns-resp-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={via}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={disabled}
|
||||
ariaLabel="Deliver alert via"
|
||||
onChange={setVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="dns-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={setFallback}
|
||||
label={fallback ? 'Disable direct fallback' : 'Enable direct fallback'}
|
||||
disabled={busy || disabled || !routed}
|
||||
/>
|
||||
<span className="dns-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
{routed && !fallback && (
|
||||
<p className="dns-alert-note" role="note">
|
||||
{VIA_NO_FALLBACK_NOTE}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="dns-add-actions">
|
||||
{err && (
|
||||
<p className="dns-field-err" role="alert">
|
||||
{err}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" variant="primary" disabled={busy || disabled}>
|
||||
{busy ? 'Saving…' : 'Add alert'}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function AlertRow({
|
||||
alert,
|
||||
busy,
|
||||
catalog,
|
||||
valid,
|
||||
onToggle,
|
||||
onVia,
|
||||
onFallback,
|
||||
onDelete,
|
||||
}: {
|
||||
alert: Alert
|
||||
busy: boolean
|
||||
catalog: DetourCatalog
|
||||
valid: Set<string>
|
||||
onToggle: (on: boolean) => void
|
||||
onVia: (v: string) => void
|
||||
onFallback: (on: boolean) => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
// Never render the token/URL in clear — show a masked descriptor only.
|
||||
const detail = useMemo(() => {
|
||||
if (alert.Type === 'telegram') {
|
||||
return { text: `chat ${alert.ChatID || '—'}`, masked: !!alert.Token }
|
||||
}
|
||||
const { host, masked } = maskUrl(alert.URL ?? '')
|
||||
return { text: host, masked: masked || !!alert.URL }
|
||||
}, [alert.Type, alert.ChatID, alert.Token, alert.URL])
|
||||
|
||||
const events = asArray(alert.Events)
|
||||
const canon = useMemo(() => canonDetour(alert.Via, catalog), [alert.Via, catalog])
|
||||
const route = useMemo(() => describeDetour(canon, catalog, valid), [canon, catalog, valid])
|
||||
const routed = canon !== 'direct'
|
||||
const fallback = alert.Fallback ?? false
|
||||
|
||||
return (
|
||||
<li className="dns-row">
|
||||
<Toggle
|
||||
pressed={alert.Enabled}
|
||||
onChange={onToggle}
|
||||
label={`${alert.Enabled ? 'Disable' : 'Enable'} alert ${alert.Name}`}
|
||||
disabled={busy}
|
||||
/>
|
||||
<div className="dns-row-main">
|
||||
<div className="dns-row-l1">
|
||||
<span className="dns-row-name">{alert.Name}</span>
|
||||
<span className="dns-badge">{alert.Type}</span>
|
||||
{events.map((e) => (
|
||||
<span key={e} className="dns-badge dns-badge--accent">
|
||||
{e}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="dns-row-l2 mono">
|
||||
<span className="dns-row-detail">{detail.text}</span>
|
||||
{detail.masked && (
|
||||
<span className="dns-masked" title="Secret is stored but hidden here">
|
||||
secret hidden
|
||||
</span>
|
||||
)}
|
||||
{route.direct ? (
|
||||
<span className="dns-path">direct</span>
|
||||
) : (
|
||||
<span className="dns-path" data-active="on" data-missing={route.missing ? 'y' : undefined}>
|
||||
{route.prefix} <strong className="dns-path-name">{route.name}</strong>
|
||||
{route.missing && <span className="dns-path-flag"> (missing)</span>}
|
||||
{fallback ? ' · +direct fallback' : ' · no fallback'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{routed && !fallback && <p className="dns-alert-note dns-alert-note--row">{VIA_NO_FALLBACK_NOTE}</p>}
|
||||
</div>
|
||||
<div className="dns-alert-ctl">
|
||||
<label className="dns-detour">
|
||||
<span className="dns-detour-label mono">Deliver via</span>
|
||||
<DetourSelect
|
||||
value={canon}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
busy={busy}
|
||||
disabled={false}
|
||||
ariaLabel={`Deliver alert ${alert.Name} via`}
|
||||
onChange={onVia}
|
||||
directLabel="Direct (default)"
|
||||
/>
|
||||
</label>
|
||||
<label className="dns-fallback">
|
||||
<Toggle
|
||||
pressed={fallback}
|
||||
onChange={onFallback}
|
||||
label={`${fallback ? 'Disable' : 'Enable'} direct fallback for ${alert.Name}`}
|
||||
disabled={busy || !routed}
|
||||
/>
|
||||
<span className="dns-fallback-label mono">Fallback to direct</span>
|
||||
</label>
|
||||
</div>
|
||||
<Button
|
||||
className="dns-del"
|
||||
onClick={onDelete}
|
||||
disabled={busy}
|
||||
aria-label={`Delete alert ${alert.Name}`}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- add form --------------------------------------------------------------
|
||||
|
||||
interface AddDraft {
|
||||
@@ -1695,8 +1358,11 @@ function ListRow({
|
||||
categories,
|
||||
response,
|
||||
filterOn,
|
||||
statuses,
|
||||
updating,
|
||||
busy,
|
||||
onToggle,
|
||||
onUpdateNow,
|
||||
onDelete,
|
||||
}: {
|
||||
name: string
|
||||
@@ -1708,8 +1374,14 @@ function ListRow({
|
||||
categories?: string[] | null
|
||||
response?: BlockResponse
|
||||
filterOn: boolean
|
||||
/** What the running engine reports about this list, one record per geo category.
|
||||
* null/[] ⇒ nothing reported: an older daemon, a stopped engine, or a list that
|
||||
* has not been applied yet. The row then says so instead of guessing. */
|
||||
statuses: RulesetStatus[] | null
|
||||
updating: boolean
|
||||
busy: boolean
|
||||
onToggle: (on: boolean) => void
|
||||
onUpdateNow: () => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const detail = useMemo<{ text: string; masked: boolean; title?: string }>(() => {
|
||||
@@ -1733,8 +1405,45 @@ function ListRow({
|
||||
}
|
||||
}, [source, url, path, entries, categories])
|
||||
|
||||
// A list only actually filters when both it and the master switch are on.
|
||||
const active = enabled && filterOn
|
||||
// url and geosite lists are FETCHED by the engine; inline and file ones are read
|
||||
// straight from the config and are loaded the moment they are applied.
|
||||
const remote = source === 'url' || source === 'geosite'
|
||||
const recs = statuses ?? []
|
||||
const hasStatus = recs.length > 0
|
||||
// A geo list with several categories: the OLDEST fetch (so a category that never
|
||||
// arrived is never hidden behind a fresh sibling) and the SUM of the counts.
|
||||
let ruleCount = 0
|
||||
let neverAny = false
|
||||
let oldestIso = ''
|
||||
for (const s of recs) {
|
||||
ruleCount += s.rule_count
|
||||
if (!s.last_updated) neverAny = true
|
||||
else if (!oldestIso || Date.parse(s.last_updated) < Date.parse(oldestIso)) oldestIso = s.last_updated
|
||||
}
|
||||
const interval = everyLabel(recs[0]?.interval_seconds ?? 0)
|
||||
|
||||
/**
|
||||
* Whether this list is BLOCKING ANYTHING, which is a different question from
|
||||
* whether it is switched on — and the one the row used to answer wrongly.
|
||||
*
|
||||
* "filtering" is now only said when the engine reports rules loaded for it. A
|
||||
* remote list that has never been fetched (the daemon raises this as a critical
|
||||
* apply finding) reads "not loaded", and one that fetched an empty list reads
|
||||
* "empty". Nothing reported at all is "load not reported": unknown, not green.
|
||||
*/
|
||||
const state: { text: string; tone: 'on' | 'off' | 'warn' } = !enabled
|
||||
? { text: 'off', tone: 'off' }
|
||||
: !filterOn
|
||||
? { text: 'inactive', tone: 'off' }
|
||||
: !remote
|
||||
? { text: 'filtering', tone: 'on' }
|
||||
: !hasStatus
|
||||
? { text: 'load not reported', tone: 'off' }
|
||||
: neverAny
|
||||
? { text: 'not loaded — nothing blocked', tone: 'warn' }
|
||||
: ruleCount === 0
|
||||
? { text: 'loaded empty — nothing blocked', tone: 'warn' }
|
||||
: { text: 'filtering', tone: 'on' }
|
||||
|
||||
return (
|
||||
<li className="dns-row">
|
||||
@@ -1764,10 +1473,39 @@ function ListRow({
|
||||
token hidden
|
||||
</span>
|
||||
)}
|
||||
<span className="dns-row-state" data-active={active ? 'on' : 'off'}>
|
||||
{active ? 'filtering' : 'inactive'}
|
||||
<span className="dns-row-state" data-active={state.tone}>
|
||||
{state.text}
|
||||
</span>
|
||||
</div>
|
||||
{remote && (
|
||||
<div className="dns-row-sync">
|
||||
<span className="dns-sync-fresh" data-never={hasStatus && neverAny ? 'y' : undefined}>
|
||||
{hasStatus ? relFetch(oldestIso) : 'status pending'}
|
||||
</span>
|
||||
{interval && <span className="dns-sync-every">{interval}</span>}
|
||||
{ruleCount > 0 && (
|
||||
<span className="dns-sync-rules">
|
||||
{ruleCount.toLocaleString('en-US')} rule{ruleCount === 1 ? '' : 's'}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="dns-sync-update"
|
||||
onClick={onUpdateNow}
|
||||
disabled={busy || updating}
|
||||
aria-label={`Update ${name} now`}
|
||||
>
|
||||
{updating ? (
|
||||
<>
|
||||
<span className="dns-sync-spin" aria-hidden="true" />
|
||||
<span>Updating…</span>
|
||||
</>
|
||||
) : (
|
||||
'Update now'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
className="dns-del"
|
||||
|
||||
+13
-51
@@ -138,57 +138,9 @@
|
||||
|
||||
/* inline rename: a quiet pencil affordance beside the name, and the mono input
|
||||
it swaps to — in the same sink/groove tone as the domain editors. */
|
||||
.dev-rename {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
background: none;
|
||||
color: var(--faint);
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, background 0.15s, border-color 0.15s;
|
||||
}
|
||||
.dev-rename:hover:not(:disabled) {
|
||||
color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||
}
|
||||
.dev-rename:focus-visible {
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.dev-rename:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.dev-name-input {
|
||||
min-width: 0;
|
||||
max-width: 24ch;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 6px;
|
||||
background: var(--sink);
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
box-shadow: 0 1px 2px var(--shadow) inset;
|
||||
}
|
||||
.dev-name-input:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.dev-name-input:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
/* The pencil button and the name input now live in App.css as .inline-rename /
|
||||
.inline-rename-input — Nodes grew the same affordance and the two pages must
|
||||
not drift. */
|
||||
.dev-id-l2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -200,6 +152,16 @@
|
||||
.dev-ip {
|
||||
color: var(--dim);
|
||||
}
|
||||
/* secondary addresses of a merged (multi-IP) device — quiet chips beside the primary */
|
||||
.dev-ip-extra {
|
||||
padding: 1px 6px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 5px;
|
||||
background: color-mix(in srgb, var(--sink) 60%, transparent);
|
||||
color: var(--faint);
|
||||
font-size: 10.5px;
|
||||
cursor: help;
|
||||
}
|
||||
.dev-mac {
|
||||
color: var(--faint);
|
||||
cursor: help;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import './Devices.css'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button, Led, Module, Toggle } from '../components'
|
||||
import { Button, Led, Module, Toggle, useConfirm } from '../components'
|
||||
import type { LedVariant } from '../components'
|
||||
import { apply as apiApply, getConfig, getDevices, putConfig, ApiError } from '../api'
|
||||
import type { Device, DiscoveredDevice, Model } from '../api'
|
||||
@@ -61,7 +61,8 @@ const STATE_LED: Record<string, LedVariant> = {
|
||||
/** A discovered client merged with its config policy (if any). */
|
||||
interface DeviceRow {
|
||||
key: string
|
||||
ip: string
|
||||
ip: string // primary address (most recent lease)
|
||||
ips: string[] // every known address, primary first; [] only for a config-only row without IP
|
||||
mac: string
|
||||
hostname: string
|
||||
state: string // online | idle | offline
|
||||
@@ -80,6 +81,7 @@ function networkLabel(row: DeviceRow): string {
|
||||
// ---- page ------------------------------------------------------------------
|
||||
|
||||
export default function Devices() {
|
||||
const confirm = useConfirm()
|
||||
const [config, setConfig] = useState<Model | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
|
||||
@@ -186,6 +188,7 @@ export default function Devices() {
|
||||
out.push({
|
||||
key: d.mac || d.ip || d.hostname,
|
||||
ip: d.ip,
|
||||
ips: d.ips?.length ? d.ips : d.ip ? [d.ip] : [],
|
||||
mac: d.mac,
|
||||
hostname: d.hostname,
|
||||
state: d.state || (d.online ? 'online' : 'offline'),
|
||||
@@ -202,6 +205,7 @@ export default function Devices() {
|
||||
out.push({
|
||||
key: d.MAC || d.IP || d.Name,
|
||||
ip: d.IP ?? '',
|
||||
ips: d.IP ? [d.IP] : [],
|
||||
mac: d.MAC ?? '',
|
||||
hostname: d.Name,
|
||||
state: 'offline',
|
||||
@@ -248,17 +252,22 @@ export default function Devices() {
|
||||
const nameOf = (row: DeviceRow) => row.cfg?.Name || row.hostname || row.ip || 'device'
|
||||
|
||||
const removeControl = useCallback(
|
||||
(row: DeviceRow) => {
|
||||
async (row: DeviceRow) => {
|
||||
if (!config) return
|
||||
const devs = asArray(config.Devices)
|
||||
const idx = matchDevice(devs, row.mac, row.ip)
|
||||
if (idx < 0) return
|
||||
const nm = devs[idx].Name || nameOf(row)
|
||||
if (!window.confirm(`Stop managing “${nm}”? Its per-device rules are removed; it falls back to network defaults.`))
|
||||
return
|
||||
const ok = await confirm({
|
||||
label: 'Stop managing device',
|
||||
title: `Stop managing “${nm}”?`,
|
||||
body: 'Its per-device rules are removed; it falls back to network defaults.',
|
||||
confirmLabel: 'Stop managing',
|
||||
})
|
||||
if (!ok) return
|
||||
void save({ ...config, Devices: devs.filter((_, i) => i !== idx) }, `Removed control for ${nm}`)
|
||||
},
|
||||
[config, save],
|
||||
[config, save, confirm],
|
||||
)
|
||||
|
||||
const loading = config === null && loadError === null && devices === null && devError === null
|
||||
@@ -468,7 +477,7 @@ function DeviceCard({
|
||||
{renaming ? (
|
||||
<input
|
||||
ref={nameInput}
|
||||
className="dev-name-input mono"
|
||||
className="inline-rename-input mono"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
@@ -494,7 +503,7 @@ function DeviceCard({
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="dev-rename"
|
||||
className="inline-rename"
|
||||
onClick={beginRename}
|
||||
disabled={busy}
|
||||
aria-label={`Rename ${name}`}
|
||||
@@ -515,6 +524,11 @@ function DeviceCard({
|
||||
</div>
|
||||
<div className="dev-id-l2 mono">
|
||||
<span className="dev-ip">{row.ip || '—'}</span>
|
||||
{row.ips.slice(1).map((ip) => (
|
||||
<span key={ip} className="dev-ip-extra" title="Additional address of this device">
|
||||
{ip}
|
||||
</span>
|
||||
))}
|
||||
<span className="dev-mac" title="Hardware (MAC) address">
|
||||
{row.mac || 'no mac'}
|
||||
</span>
|
||||
|
||||
@@ -797,23 +797,6 @@
|
||||
.ins-conn--dns {
|
||||
grid-template-columns: 62px minmax(60px, 116px) 12px minmax(0, 1fr) minmax(72px, 160px) auto;
|
||||
}
|
||||
/* router-originated lookups (urltest probes / sub fetches): a dimmed pill so they
|
||||
* read distinctly from a real LAN client's IP/hostname. */
|
||||
.ins-conn-dev--router {
|
||||
justify-self: start;
|
||||
max-width: 100%;
|
||||
padding: 1px 8px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--faint);
|
||||
background: color-mix(in srgb, var(--raised) 70%, transparent);
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ins-conn--dns .tag {
|
||||
justify-self: end;
|
||||
}
|
||||
|
||||
@@ -177,26 +177,19 @@ function ConnRow({ c, fresh }: { c: ConnLogEntry; fresh: boolean }) {
|
||||
* (block/proxy/pass). Mirrors ConnRow's `device → dest` reading (same `.ins-conn`
|
||||
* chrome + accent arrow) so the DNS log and the Connections log read identically:
|
||||
* the "who asked" is the LAN device, the resolver that answered is the trailing
|
||||
* secondary column. Router-originated lookups (urltest probes / sub fetches) carry
|
||||
* the literal device `router` and render as a dimmed chip so they're distinct from
|
||||
* real LAN clients; an empty device (older data) falls back to a dash.
|
||||
* secondary column. The backend drops the router's own resolutions (urltest probes /
|
||||
* sub fetches) at ingestion, so every row here is a real client; an empty device
|
||||
* (older data) falls back to a dash.
|
||||
*/
|
||||
function DnsRow({ r, fresh }: { r: QueryLogEntry; fresh: boolean }) {
|
||||
const tag = actionTag(r.action)
|
||||
const dev = r.device.trim()
|
||||
const isRouter = dev.toLowerCase() === 'router'
|
||||
return (
|
||||
<li className={fresh ? 'ins-conn ins-conn--dns new' : 'ins-conn ins-conn--dns'}>
|
||||
<span className="ins-conn-t mono">{fmtClock(r.unix)}</span>
|
||||
{isRouter ? (
|
||||
<span className="ins-conn-dev ins-conn-dev--router" title="router-originated lookup">
|
||||
router
|
||||
</span>
|
||||
) : (
|
||||
<span className="ins-conn-dev mono" title={dev || 'source device unknown'}>
|
||||
{dev || '—'}
|
||||
</span>
|
||||
)}
|
||||
<span className="ins-conn-dev mono" title={dev || 'source device unknown'}>
|
||||
{dev || '—'}
|
||||
</span>
|
||||
<span className="ins-conn-arrow" aria-hidden="true">
|
||||
→
|
||||
</span>
|
||||
@@ -1236,7 +1229,7 @@ export default function Insights() {
|
||||
{/* 8 · DNS log — the live DNS DECISIONS (time · device → domain · resolver ·
|
||||
block/proxy/pass). Same shell/scroll/actions as Connections above, and
|
||||
now the same device → target reading: the "who asked" is the LAN client
|
||||
(or `router` for the appliance's own lookups), the resolver trails. */}
|
||||
(router-originated lookups are dropped at ingestion), the resolver trails. */}
|
||||
<Section
|
||||
title="DNS log · decisions"
|
||||
led={dns.err ? 'crit' : dns.rows.length ? 'on' : 'off'}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import './Networks.css'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button, Led, Select, Toggle } from '../components'
|
||||
import { Button, Led, Select, Toggle, useConfirm } from '../components'
|
||||
import { apply as apiApply, getConfig, putConfig, ApiError } from '../api'
|
||||
import type { Inbound, Interface, Model, Status } from '../api'
|
||||
import { isLanNetwork, isWanNetwork, useInterfaces } from '../srcOptions'
|
||||
@@ -85,6 +85,19 @@ const DEFAULT_TPROXY_PORT = 12345
|
||||
* Collapsing those into one switch would make "I want ping to work" silently mean
|
||||
* "I permit a parallel VPN bypass", so the middle option exists to remove that
|
||||
* false choice — and the labels push anyone who wants diagnostics to `icmp`.
|
||||
*
|
||||
* WHY THIS COPY WAS REWRITTEN. `block` used to say "Nothing leaves except through
|
||||
* the tunnel", and it was not true. The daemon let untunnelable traffic out toward
|
||||
* every destination the ROUTING RULES send direct, on the argument that such a host
|
||||
* already has your address from ordinary TCP. Under the commonest setup here —
|
||||
* "tunnel what's blocked, send the rest direct" — the routing default IS direct, so
|
||||
* that covered everything: `block` behaved exactly like `direct`, including ESP/GRE,
|
||||
* i.e. the parallel-VPN case the middle rung exists to exclude. The daemon now drops
|
||||
* unconditionally under `block`, and this copy states the price instead of hiding it
|
||||
* (the owner's call: this router does not do ping and does not do IPTV).
|
||||
*
|
||||
* `icmp` still carries that destination-dependence for its NON-ping half, so its
|
||||
* cost line says so rather than claiming "nothing else gets out".
|
||||
*/
|
||||
type Untunnelable = 'block' | 'icmp' | 'direct'
|
||||
|
||||
@@ -98,7 +111,10 @@ function normUntunnelable(raw: string | undefined): Untunnelable {
|
||||
|
||||
const UNTUNNELABLE_OPTIONS: ReadonlyArray<{ value: string; label: string }> = [
|
||||
{ value: 'block', label: 'Block everything — most private' },
|
||||
{ value: 'icmp', label: 'Allow ping only — for diagnostics' },
|
||||
// Not "Allow ping only": the rung also lets the other untunnelable protocols
|
||||
// out toward directly-routed addresses, and the cost line below says so. A
|
||||
// label that promised "only" would be contradicted two lines under itself.
|
||||
{ value: 'icmp', label: 'Allow ping — for diagnostics' },
|
||||
{ value: 'direct', label: 'Allow everything — most compatible' },
|
||||
]
|
||||
|
||||
@@ -110,13 +126,18 @@ interface PolicyCopy {
|
||||
|
||||
const UNTUNNELABLE_COPY: Record<Untunnelable, PolicyCopy> = {
|
||||
block: {
|
||||
works: 'Nothing leaves except through the tunnel.',
|
||||
cost: 'Ping and traceroute won’t work from your devices, and neither will multicast IPTV or connecting to a VPN from a device on your network.',
|
||||
// Scoped to "this traffic" on purpose. The old line — "Nothing leaves except
|
||||
// through the tunnel" — was doubly loose: it was false (see the note above),
|
||||
// and even read charitably it collides with directly-routed TCP, which does
|
||||
// leave outside the tunnel by design.
|
||||
works:
|
||||
'None of this traffic leaves the router — it’s dropped, whatever your routing rules say. It’s the only setting whose promise doesn’t depend on how the rules are written.',
|
||||
cost: 'Ping and traceroute stop working from your devices. So do IPsec and PPTP VPN connections made from a device on your network, multicast IPTV, and SCTP. VPNs that run over UDP — WireGuard, OpenVPN-UDP, and IPsec through NAT (IKEv2/NAT-T) — are unaffected: they go through the tunnel like everything else.',
|
||||
tone: 'good',
|
||||
},
|
||||
icmp: {
|
||||
works: 'Ping and traceroute work, so you can check whether something is reachable.',
|
||||
cost: 'Whatever you ping sees your real IP address instead of the tunnel’s. Only for hosts you deliberately ping, and nothing else gets out — IPTV and VPN connections stay blocked.',
|
||||
works: 'Ping and traceroute work everywhere, so you can check whether something is reachable.',
|
||||
cost: 'Whatever you ping sees your real IP address instead of the tunnel’s. IPsec, PPTP and IPTV also get out — but only toward addresses your routing rules already send direct, so a VPN app on a device can still open its own connection beside this one if its server is one of those.',
|
||||
tone: 'warn',
|
||||
},
|
||||
direct: {
|
||||
@@ -242,6 +263,7 @@ function computeWarnings(inbounds: Inbound[], ifaces: Interface[]): Warning[] {
|
||||
// ---- page ------------------------------------------------------------------
|
||||
|
||||
export default function Networks({ status }: { status?: Status | null }) {
|
||||
const confirm = useConfirm()
|
||||
const [config, setConfig] = useState<Model | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
const ifaces = useInterfaces()
|
||||
@@ -392,23 +414,21 @@ export default function Networks({ status }: { status?: Status | null }) {
|
||||
)
|
||||
|
||||
const removeInbound = useCallback(
|
||||
(idx: number) => {
|
||||
async (idx: number) => {
|
||||
if (!config) return
|
||||
const target = inbounds[idx]
|
||||
if (
|
||||
!window.confirm(
|
||||
`Delete inbound “${target.Name}”?${
|
||||
intercepts(target)
|
||||
? ` ${target.Network || 'Its network'} stops going through the tunnel.`
|
||||
: ''
|
||||
}`,
|
||||
)
|
||||
)
|
||||
return
|
||||
const ok = await confirm({
|
||||
label: 'Delete inbound',
|
||||
title: `Delete inbound “${target.Name}”?`,
|
||||
body: intercepts(target)
|
||||
? `${target.Network || 'Its network'} stops going through the tunnel.`
|
||||
: undefined,
|
||||
})
|
||||
if (!ok) return
|
||||
const next = inbounds.filter((_, i) => i !== idx)
|
||||
void save({ ...config, Inbounds: next }, `Deleted ${target.Name}`)
|
||||
},
|
||||
[config, inbounds, save],
|
||||
[config, inbounds, save, confirm],
|
||||
)
|
||||
|
||||
return (
|
||||
@@ -552,7 +572,7 @@ export default function Networks({ status }: { status?: Status | null }) {
|
||||
|
||||
{untunnelable === 'block' && (
|
||||
<p className="nw-sec-note nw-policy-hint">
|
||||
If you just want to check whether a site is reachable, choose <strong>Allow ping only</strong>{' '}
|
||||
If you just want to check whether a site is reachable, choose <strong>Allow ping</strong>{' '}
|
||||
rather than allowing everything — it’s the narrower of the two.
|
||||
</p>
|
||||
)}
|
||||
|
||||
+124
-44
@@ -196,6 +196,52 @@
|
||||
border-color: color-mix(in srgb, var(--amber) 55%, var(--groove));
|
||||
color: var(--amber);
|
||||
}
|
||||
/* "not built" — the saved switch says on and the engine has no such outbound. */
|
||||
.badge--crit {
|
||||
border-color: color-mix(in srgb, var(--crit) 55%, var(--groove));
|
||||
color: var(--crit);
|
||||
}
|
||||
|
||||
/* ---- last-apply findings, attached to the row they are about ----
|
||||
Sits under the row's own two lines, inside the row plate, so a node the
|
||||
generator threw away cannot read as an ordinary enabled node. Severity carries
|
||||
the colour; the accent stays reserved for controls. */
|
||||
.row-findings {
|
||||
margin: 6px 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
.row-finding {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 7px 9px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 40%, var(--groove));
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--sink) 35%, transparent);
|
||||
}
|
||||
.row-finding--critical {
|
||||
border-color: color-mix(in srgb, var(--crit) 45%, var(--groove));
|
||||
}
|
||||
.row-finding-msg {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--ink);
|
||||
max-width: 82ch;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
/* Findings that belong to no single row (see Nodes.tsx globalFindings). */
|
||||
.node-findings {
|
||||
margin-bottom: calc(var(--u, 8px) * 2);
|
||||
}
|
||||
.node-findings .row-findings {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
/* masked-credential marker */
|
||||
.masked {
|
||||
@@ -389,55 +435,29 @@ select.fp-input {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* protocol checkboxes */
|
||||
.opt-checks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 16px;
|
||||
}
|
||||
.opt-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--dim);
|
||||
cursor: pointer;
|
||||
}
|
||||
.opt-check input {
|
||||
accent-color: var(--accent);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* chip list */
|
||||
.chip-field {
|
||||
/* extra-headers key/value rows */
|
||||
.hdr-field {
|
||||
gap: 8px;
|
||||
}
|
||||
.chip-row {
|
||||
.hdr-rows {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
.hdr-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(9rem, 1fr) 2fr auto;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 4px 3px 9px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--raised) 70%, transparent);
|
||||
}
|
||||
.chip-text {
|
||||
font-size: 11px;
|
||||
color: var(--ink);
|
||||
max-width: 32ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
.hdr-key {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.chip-x {
|
||||
.hdr-x {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -453,18 +473,14 @@ select.fp-input {
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
}
|
||||
.chip-x:hover:not(:disabled) {
|
||||
.hdr-x:hover:not(:disabled) {
|
||||
color: var(--crit);
|
||||
background: color-mix(in srgb, var(--crit) 14%, transparent);
|
||||
}
|
||||
.chip-x:disabled {
|
||||
.hdr-x:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.chip-add {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* editor footer */
|
||||
.opt-actions {
|
||||
@@ -671,6 +687,20 @@ select.fp-input {
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* A collapsed bucket has to carry its own bad news: a 300-node subscription is
|
||||
closed by default, and the per-row findings inside it are otherwise unreachable
|
||||
without knowing to look. */
|
||||
.group-flagged {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: var(--amber);
|
||||
}
|
||||
.group-rows {
|
||||
margin-top: 8px;
|
||||
}
|
||||
@@ -757,3 +787,53 @@ select.fp-input {
|
||||
width: 9rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- inline node rename ----
|
||||
The pencil / input pair itself is shared (.inline-rename[-input] in App.css);
|
||||
only the row-local sizing and the refusal message live here. A node name is
|
||||
longer than a device name (it carries a protocol and a host), so the field is
|
||||
given more room than the shared 24ch default. */
|
||||
.node-name-input {
|
||||
max-width: 32ch;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
/* Why a rename was refused, pinned under the row it was typed in. Semantic crit:
|
||||
the name did not change, and that must not be mistaken for a saved edit. */
|
||||
.row-err {
|
||||
margin: 2px 0 0;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.45;
|
||||
color: var(--crit);
|
||||
max-width: 68ch;
|
||||
}
|
||||
/* Stated once per subscription bucket: the same rule the locked control in every
|
||||
row carries, so the absent rename is explained before it is looked for. */
|
||||
.group-note {
|
||||
margin: 0;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--groove);
|
||||
border-top: 0;
|
||||
background: color-mix(in srgb, var(--sink) 25%, transparent);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.5;
|
||||
color: var(--faint);
|
||||
}
|
||||
/* The optional name sits beside the link input on a wide row and drops onto its
|
||||
own line when the row can no longer hold both. */
|
||||
.add-name {
|
||||
flex: 0 1 22ch;
|
||||
min-width: 12ch;
|
||||
}
|
||||
.add-row--conf .add-name {
|
||||
flex: none;
|
||||
align-self: stretch;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.add-row {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.add-name {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
}
|
||||
|
||||
+771
-235
File diff suppressed because it is too large
Load Diff
+177
-156
@@ -1,21 +1,21 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Button, Led, Module, QueryLog, SegMeter } from '../components'
|
||||
import type { LedVariant, QueryEntry, QueryTag } from '../components'
|
||||
import { fmtClock, fmtDateTime, fmtDuration } from '../format'
|
||||
import { Button, Led, Module } from '../components'
|
||||
import type { LedVariant } from '../components'
|
||||
import { fmtDateTime, fmtDuration } from '../format'
|
||||
import {
|
||||
apply as apiApply,
|
||||
confirm as apiConfirm,
|
||||
rollback as apiRollback,
|
||||
getConfig,
|
||||
getRulesReachability,
|
||||
getStats,
|
||||
getStatsLog,
|
||||
ApiError,
|
||||
} from '../api'
|
||||
import type { Model, Stats, Status, StatusWarning } from '../api'
|
||||
import { confirmTimeout } from '../pendingConfirm'
|
||||
import { navigate } from '../router'
|
||||
import type { Route } from '../router'
|
||||
import { attentionFindings } from '../findings'
|
||||
import { protectionState } from '../planeState'
|
||||
import { attentionFindings, truncationNote } from '../findings'
|
||||
import { engineReadout, killSwitchReadout, protectionState } from '../planeState'
|
||||
|
||||
// null-safe length for a Go slice that may arrive as null.
|
||||
const len = (a: unknown[] | null | undefined): number => (a ? a.length : 0)
|
||||
@@ -28,13 +28,8 @@ function short(hash: string): string {
|
||||
return h.length > 12 ? h.slice(0, 12) : h
|
||||
}
|
||||
|
||||
function actionTag(action?: string): QueryTag {
|
||||
if (action === 'block') return 'block'
|
||||
if (action === 'proxy') return 'proxy'
|
||||
return 'pass'
|
||||
}
|
||||
|
||||
type ControlKind = 'apply' | 'confirm' | 'rollback'
|
||||
// Confirm is no longer one of them — see the note beside the controls row.
|
||||
type ControlKind = 'apply' | 'rollback'
|
||||
|
||||
/**
|
||||
* Live service uptime in seconds, ticking between status polls.
|
||||
@@ -49,17 +44,32 @@ type ControlKind = 'apply' | 'confirm' | 'rollback'
|
||||
* Returns null when the daemon doesn't report uptime (older builds) — the caller
|
||||
* then renders nothing rather than inventing a number.
|
||||
*/
|
||||
function useUptime(status: Status | null): number | null {
|
||||
function useUptime(status: Status | null): { seconds: number; startedUnix: number } | null {
|
||||
const base = useRef<{ uptime: number; at: number } | null>(null)
|
||||
// The instant the daemon came up, ON THE BROWSER'S CLOCK.
|
||||
//
|
||||
// `status.started_unix` is the router's own clock, and the router has no RTC —
|
||||
// it runs on UTC with no tzdata. Rendering it through the browser's timezone
|
||||
// printed a start time three hours in the FUTURE for a Moscow operator, beside
|
||||
// an uptime of "2 h 41 min". Deriving it instead as now-minus-uptime is a
|
||||
// difference of two client timestamps, so it is skew-proof and can never land
|
||||
// ahead of the clock in the header.
|
||||
const started = useRef<number | null>(null)
|
||||
const [, forceTick] = useState(0)
|
||||
|
||||
const reported = status?.uptime_seconds
|
||||
useEffect(() => {
|
||||
if (typeof reported !== 'number' || !Number.isFinite(reported)) {
|
||||
base.current = null
|
||||
started.current = null
|
||||
return
|
||||
}
|
||||
base.current = { uptime: reported, at: Date.now() }
|
||||
const now = Date.now()
|
||||
base.current = { uptime: reported, at: now }
|
||||
// Re-baselining every poll would jitter the displayed second back and forth;
|
||||
// only move it when the estimate has genuinely drifted (a daemon restart).
|
||||
const est = Math.round(now / 1000 - reported)
|
||||
if (started.current === null || Math.abs(started.current - est) > 5) started.current = est
|
||||
forceTick((n) => n + 1)
|
||||
}, [reported])
|
||||
|
||||
@@ -71,8 +81,11 @@ function useUptime(status: Status | null): number | null {
|
||||
return () => window.clearInterval(id)
|
||||
}, [])
|
||||
|
||||
if (!base.current) return null
|
||||
return base.current.uptime + Math.max(0, (Date.now() - base.current.at) / 1000)
|
||||
if (!base.current || started.current === null) return null
|
||||
return {
|
||||
seconds: base.current.uptime + Math.max(0, (Date.now() - base.current.at) / 1000),
|
||||
startedUnix: started.current,
|
||||
}
|
||||
}
|
||||
|
||||
export function Overview({
|
||||
@@ -100,50 +113,42 @@ export function Overview({
|
||||
void loadConfig()
|
||||
}, [loadConfig])
|
||||
|
||||
// ---- live query log + filter stats: poll both, degrade to honest empty states ----
|
||||
const [entries, setEntries] = useState<QueryEntry[]>([])
|
||||
// ---- how many rules are actually IN FORCE ----------------------------------
|
||||
//
|
||||
// `Rule.Enabled` from /api/config is the DESIRED state; the active WAN profile
|
||||
// overrides it in either direction, and the daemon reports the result as
|
||||
// `effective_enabled`. Counting the saved switches told a router running one
|
||||
// chain that it had "2 / 2" — the Routing page had already been fixed to read
|
||||
// the verdicts, and the home page kept summing the config beside it.
|
||||
//
|
||||
// null ⇒ no verdicts (older daemon, engine stopped, endpoint unreachable). The
|
||||
// module then says so rather than passing the saved count off as the live one.
|
||||
const [inForce, setInForce] = useState<number | null>(null)
|
||||
const loadReach = useCallback(async () => {
|
||||
try {
|
||||
const { rules } = await getRulesReachability()
|
||||
setInForce(rules.filter((r) => r.effective_enabled).length)
|
||||
} catch {
|
||||
setInForce(null)
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
void loadReach()
|
||||
}, [loadReach])
|
||||
|
||||
// ---- live filter stats: poll the aggregate snapshot, degrade to honest empty states ----
|
||||
const [stats, setStats] = useState<Stats | null>(null)
|
||||
const [statsOk, setStatsOk] = useState(true)
|
||||
// `loggingOff` is read back out of the snapshot each tick so the poll can stop
|
||||
// asking for a log the daemon isn't keeping. A ref (not state) keeps the effect
|
||||
// stable — it must not re-subscribe every time the snapshot lands.
|
||||
const loggingOffRef = useRef(false)
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
const tick = async () => {
|
||||
// Nothing to poll for while the tab is in the background.
|
||||
if (document.hidden) return
|
||||
try {
|
||||
// Logging off ⇒ the log endpoint has nothing to give; skip it and keep
|
||||
// polling the snapshot alone so the page notices it being switched back on.
|
||||
const [log, s] = await Promise.all([
|
||||
loggingOffRef.current ? Promise.resolve([]) : getStatsLog(50),
|
||||
getStats(),
|
||||
])
|
||||
const s = await getStats()
|
||||
if (!alive) return
|
||||
loggingOffRef.current = s.backend === 'off'
|
||||
setStatsOk(true)
|
||||
setStats(s)
|
||||
const rows = Array.isArray(log) ? log : []
|
||||
setEntries(
|
||||
rows.slice(0, 10).map((r) => ({
|
||||
// The resolution unix-time + domain is a stable identity for the row,
|
||||
// so React only replays the slide-in for genuinely new queries.
|
||||
id: `${r.unix}-${r.domain}-${r.qtype}`,
|
||||
// Format from unix in the browser's local timezone (shared helper) so
|
||||
// this log matches the Insights logs — not the server's UTC `time`.
|
||||
time: fmtClock(r.unix) || (r.time ?? ''),
|
||||
domain: r.domain,
|
||||
// The REAL query source, same as the Insights DNS log: the LAN
|
||||
// client's hostname/IP, or 'router' for the appliance's own lookups.
|
||||
// (The resolver lives in the Insights log's own column.) '' only on
|
||||
// rows persisted before device attribution existed.
|
||||
device: r.device || '—',
|
||||
tag: actionTag(r.action),
|
||||
})),
|
||||
)
|
||||
} catch {
|
||||
if (alive) setStatsOk(false)
|
||||
// Transient — the interval retries, and the modules keep their last reading.
|
||||
}
|
||||
}
|
||||
void tick()
|
||||
@@ -159,7 +164,7 @@ export function Overview({
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ---- apply / confirm / rollback ----
|
||||
// ---- apply / rollback ----
|
||||
const [busy, setBusy] = useState<ControlKind | null>(null)
|
||||
const [result, setResult] = useState<{ ok: boolean; msg: string } | null>(null)
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
@@ -177,22 +182,25 @@ export function Overview({
|
||||
setBusy(kind)
|
||||
setResult(null)
|
||||
try {
|
||||
const fn = kind === 'apply' ? apiApply : kind === 'confirm' ? apiConfirm : apiRollback
|
||||
const r = await fn()
|
||||
const r = kind === 'apply' ? await apiApply() : await apiRollback()
|
||||
if (r.error) {
|
||||
setResult({ ok: false, msg: r.error })
|
||||
flash(`${kind} failed`)
|
||||
} else {
|
||||
// An apply that changed something armed an auto-rollback, and saying
|
||||
// "data plane reconciled" while a timer runs is how someone walks away
|
||||
// from a config that then reverts. Name the window when there is one.
|
||||
const window = confirmTimeout()
|
||||
const msg =
|
||||
kind === 'apply'
|
||||
? r.changed
|
||||
? 'Applied — data plane reconciled'
|
||||
? window > 0
|
||||
? `Applied — keep this config within ${window}s or it rolls back`
|
||||
: 'Applied — data plane reconciled'
|
||||
: 'Applied — already up to date'
|
||||
: kind === 'confirm'
|
||||
? 'Confirmed — auto-rollback cancelled'
|
||||
: 'Rolled back to last-good config'
|
||||
: 'Rolled back to last-good config'
|
||||
setResult({ ok: true, msg })
|
||||
flash(kind === 'apply' ? 'Applied' : kind === 'confirm' ? 'Confirmed' : 'Rolled back')
|
||||
flash(kind === 'apply' ? 'Applied' : 'Rolled back')
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'request failed'
|
||||
@@ -201,16 +209,20 @@ export function Overview({
|
||||
} finally {
|
||||
setBusy(null)
|
||||
onStatusChange()
|
||||
if (kind !== 'confirm') void loadConfig()
|
||||
void loadConfig()
|
||||
// An apply or a rollback is exactly what changes which rules are in force.
|
||||
void loadReach()
|
||||
}
|
||||
},
|
||||
[flash, loadConfig, onStatusChange],
|
||||
[flash, loadConfig, loadReach, onStatusChange],
|
||||
)
|
||||
|
||||
// ---- service uptime (PROCESS uptime, not "time since the last apply") ----
|
||||
const uptime = useUptime(status)
|
||||
const uptimeText = uptime === null ? '' : fmtDuration(uptime)
|
||||
const startedAt = status?.started_unix ? fmtDateTime(status.started_unix) : ''
|
||||
const uptimeText = uptime === null ? '' : fmtDuration(uptime.seconds)
|
||||
// On YOUR clock, derived from the uptime — never `status.started_unix`, which is
|
||||
// the router's clock and has no timezone to convert from. See useUptime.
|
||||
const startedAt = uptime === null ? '' : fmtDateTime(uptime.startedUnix)
|
||||
|
||||
// ---- derived display state ----
|
||||
const g = config?.Globals
|
||||
@@ -289,24 +301,27 @@ export function Overview({
|
||||
? `${worstGroup.group} — no answer`
|
||||
: `${worstGroup.group} — ${worstGroup.dead} down`
|
||||
|
||||
const engineVariant: LedVariant = !status
|
||||
? 'off'
|
||||
: status.running && status.active
|
||||
? 'on'
|
||||
: status.running
|
||||
? 'amber'
|
||||
: 'crit'
|
||||
// One reading for the engine, and it is able to say "stopped": `status.running`
|
||||
// was a constant `true` on the daemon, so this LED could never go crit and the
|
||||
// Engine module was green through a process that had failed to start. See
|
||||
// planeState.engineState.
|
||||
const engine = engineReadout(status)
|
||||
const engineVariant: LedVariant = engine.variant
|
||||
|
||||
const protection = protectionState(status)
|
||||
// Configured fail-closed AND actually enforcing it. `none` means nothing is
|
||||
// installed, so the setting is inert no matter what it says.
|
||||
const killInEffect = killArmed && status?.plane !== 'none'
|
||||
// Configured fail-closed, actually enforcing it, or not known — three answers,
|
||||
// and the third is not folded into the first. See planeState.killSwitchReadout.
|
||||
const kill = killSwitchReadout(status, g?.KillSwitch)
|
||||
|
||||
// Findings that need attention. `info` notes are statements about the config,
|
||||
// not problems, so they live beside the setting they describe (see findings.ts)
|
||||
// — keeping this list to things someone could actually act on.
|
||||
const warnings = attentionFindings(status?.warnings)
|
||||
const criticalCount = warnings.filter((w) => w.severity === 'critical').length
|
||||
// The daemon caps the published list at 50 and says so in an `info` note — the
|
||||
// one channel this page filters away. Carried separately so the list can admit
|
||||
// it is not the whole list. See findings.ts truncationNote.
|
||||
const truncated = truncationNote(status?.warnings)
|
||||
|
||||
return (
|
||||
<section className="page" aria-label="Overview">
|
||||
@@ -329,7 +344,7 @@ export function Overview({
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Findings warnings={warnings} criticalCount={criticalCount} />
|
||||
<Findings warnings={warnings} criticalCount={criticalCount} truncated={truncated} />
|
||||
|
||||
<div className="grid">
|
||||
{/* Groups, not nodes: a group is where a dial path is defined, so it is the
|
||||
@@ -372,14 +387,31 @@ export function Overview({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* "N / M in force", the same reading the Routing page shows — never the
|
||||
count of saved switches. The lamp follows the same rule: a table of
|
||||
rules none of which are in force routes exactly nothing, and it used
|
||||
to sit under a green light saying "0 / 7". */}
|
||||
<Module
|
||||
name="Routing"
|
||||
value={String(enabledCount(config?.Rules))}
|
||||
unit={`/ ${len(config?.Rules)} rules`}
|
||||
led={{ variant: len(config?.Rules) ? 'on' : 'amber' }}
|
||||
value={inForce === null ? String(enabledCount(config?.Rules)) : String(inForce)}
|
||||
unit={
|
||||
inForce === null
|
||||
? `/ ${len(config?.Rules)} rules saved`
|
||||
: `/ ${len(config?.Rules)} in force`
|
||||
}
|
||||
led={{
|
||||
variant:
|
||||
len(config?.Rules) === 0
|
||||
? 'amber'
|
||||
: inForce === null
|
||||
? 'off'
|
||||
: inForce === 0
|
||||
? 'amber'
|
||||
: 'on',
|
||||
}}
|
||||
rows={[
|
||||
{ k: 'egresses', v: String(len(config?.Egresses)) },
|
||||
{ k: 'default', v: defaultTarget(config), hot: true },
|
||||
{ k: 'default', v: defaultTarget(status, config), hot: true },
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -419,17 +451,17 @@ export function Overview({
|
||||
/>
|
||||
|
||||
{/* A kill-switch set to fail-closed is only ARMED if something is actually
|
||||
installed to enforce it. With no plane it is configured but inert, and
|
||||
saying "ARMED" there would be a false reassurance next to a readout
|
||||
that says nothing is protected. */}
|
||||
installed to enforce it, and "we haven't been told" is neither. With no
|
||||
plane it is configured but inert; with no reading the lamp stays unlit
|
||||
rather than joining the healthy branch by default. */}
|
||||
<Module
|
||||
name="Kill-switch"
|
||||
value={killInEffect ? 'ARMED' : killArmed ? 'NOT IN EFFECT' : 'OPEN'}
|
||||
led={{ variant: killInEffect ? 'on' : killArmed ? 'crit' : 'amber' }}
|
||||
value={kill.value}
|
||||
led={{ variant: kill.variant }}
|
||||
rows={[
|
||||
{ k: 'setting', v: killArmed ? 'fail-closed' : 'fail-open', hot: !killArmed },
|
||||
...(killArmed && !killInEffect
|
||||
? [{ k: 'blocking now', v: 'no — nothing installed', hot: true }]
|
||||
...(kill.blockingNow
|
||||
? [{ k: 'blocking now', v: kill.blockingNow, hot: kill.hot }]
|
||||
: [{ k: 'ipv6', v: g?.IPv6 ? 'covered' : 'off' }]),
|
||||
{ k: 'confirm', v: g?.ConfirmTimeout ? `${g.ConfirmTimeout}s window` : 'no auto-rollback' },
|
||||
]}
|
||||
@@ -452,6 +484,7 @@ export function Overview({
|
||||
unit={status?.version?.includes('-') ? '· ' + status.version.split('-').slice(1).join('-') : ''}
|
||||
led={{ variant: engineVariant }}
|
||||
rows={[
|
||||
{ k: 'process', v: engine.word, hot: engineVariant === 'crit' },
|
||||
{ k: 'config hash', v: <span className="mono">{short(status?.hash ?? '')}</span> },
|
||||
// Uptime of the daemon PROCESS. "started" is the moment it came up,
|
||||
// by the router's clock — not the moment a config was applied.
|
||||
@@ -463,73 +496,20 @@ export function Overview({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="log-wrap">
|
||||
{hasStats && (
|
||||
<div className="filter-readout">
|
||||
<SegMeter label="Filtered" value={blockedPct} max={100} unit="%" />
|
||||
{topBlocked.length > 0 ? (
|
||||
<ul className="topblocked" aria-label="Top blocked domains">
|
||||
{topBlocked.map((d) => (
|
||||
<li key={d.domain}>
|
||||
<span className="tb-dom">{d.domain}</span>
|
||||
<span className="tb-n">{d.blocked}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="qempty" style={{ margin: 0 }}>
|
||||
{blocked > 0 ? 'blocked queries logged' : 'nothing blocked yet'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<QueryLog
|
||||
title="Query log"
|
||||
led={!statsOk ? 'crit' : loggingOff ? 'off' : entries.length > 0 ? 'on' : 'amber'}
|
||||
hint={
|
||||
!statsOk
|
||||
? 'stats unavailable'
|
||||
: loggingOff
|
||||
? 'logging off'
|
||||
: hasStats
|
||||
? `${queries} queries · ${blocked} blocked`
|
||||
: // Aggregates can reset on a daemon restart while the persistent
|
||||
// log still streams rows — don't claim "waiting" when the log is
|
||||
// clearly live; only show it when there's genuinely nothing.
|
||||
entries.length > 0
|
||||
? 'recent queries'
|
||||
: 'waiting for engine stats'
|
||||
}
|
||||
entries={entries}
|
||||
/>
|
||||
{entries.length === 0 && (
|
||||
<p className="qempty">
|
||||
{!statsOk ? (
|
||||
'Stats endpoint unreachable — retrying every few seconds.'
|
||||
) : loggingOff ? (
|
||||
<>
|
||||
Logging is off — no DNS, connection, or per-device history is recorded.{' '}
|
||||
<a className="linkish" href="#/settings">
|
||||
Turn it on in Settings → Logging backend
|
||||
</a>
|
||||
.
|
||||
</>
|
||||
) : (
|
||||
'No query data yet — the live stream lights up once the engine resolves DNS (needs an active subscriber + traffic).'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Apply / Confirm / Rollback — active voice, honest results. */}
|
||||
<div className="controls" role="group" aria-label="Config actions">
|
||||
<div className="controls-btns">
|
||||
<Button variant="primary" onClick={() => void run('apply')} disabled={busy !== null}>
|
||||
{busy === 'apply' ? 'Applying…' : 'Apply config'}
|
||||
</Button>
|
||||
<Button onClick={() => void run('confirm')} disabled={busy !== null}>
|
||||
{busy === 'confirm' ? 'Confirming…' : 'Confirm'}
|
||||
</Button>
|
||||
{/* A "Confirm" button used to sit here permanently, and pressing it
|
||||
always printed "Confirmed — auto-rollback cancelled": `apply.Confirm()`
|
||||
returns nil whether or not a window was ever armed, so the message was
|
||||
a success report for an event that usually had not happened.
|
||||
Keeping a config is now offered only while a window is actually open,
|
||||
and that is announced by the app-wide band directly above this page —
|
||||
which is where the button lives, beside the countdown it belongs to,
|
||||
rather than duplicated here. */}
|
||||
{canRollback && (
|
||||
<Button onClick={() => void run('rollback')} disabled={busy !== null}>
|
||||
{busy === 'rollback' ? 'Rolling back…' : 'Rollback'}
|
||||
@@ -560,11 +540,23 @@ const SECTION_ROUTE: Record<string, Route> = {
|
||||
rule: 'routing',
|
||||
ruleset: 'routing',
|
||||
blocklist: 'dns',
|
||||
allowlist: 'dns',
|
||||
resolver: 'dns',
|
||||
dns_rule: 'dns',
|
||||
device: 'devices',
|
||||
chain: 'targets',
|
||||
group: 'targets',
|
||||
// A node the generator dropped (unparseable share link, duplicate WireGuard
|
||||
// key, name colliding with a reserved tag) is reported under `node` — and had
|
||||
// nowhere to jump to, so the one page that could show it a green toggle was
|
||||
// also the one page the finding could not reach.
|
||||
node: 'nodes',
|
||||
subscription: 'nodes',
|
||||
egress: 'targets',
|
||||
inbound: 'networks',
|
||||
interface: 'networks',
|
||||
profile: 'profiles',
|
||||
alert: 'settings',
|
||||
// The standing note about non-TCP/UDP traffic — its control lives on Networks.
|
||||
untunnelable: 'networks',
|
||||
}
|
||||
@@ -582,11 +574,14 @@ const SECTION_ROUTE: Record<string, Route> = {
|
||||
function Findings({
|
||||
warnings,
|
||||
criticalCount,
|
||||
truncated,
|
||||
}: {
|
||||
warnings: StatusWarning[]
|
||||
criticalCount: number
|
||||
/** The daemon's "N further suppressed" note, when the list was capped. */
|
||||
truncated: StatusWarning | null
|
||||
}) {
|
||||
if (warnings.length === 0) return null
|
||||
if (warnings.length === 0 && !truncated) return null
|
||||
|
||||
const rank = { critical: 0, warning: 1, info: 2 } as const
|
||||
const sorted = [...warnings].sort((a, b) => rank[a.severity] - rank[b.severity])
|
||||
@@ -596,6 +591,10 @@ function Findings({
|
||||
<header className="findings-hd">
|
||||
<h2 className="findings-title">Last apply</h2>
|
||||
<span className="findings-count mono">
|
||||
{/* "at least" whenever the list was capped: the counts below it are a
|
||||
floor, not a total, and the cap drops the least severe FIRST — so
|
||||
on a config with fifty criticals the thing it drops is a critical. */}
|
||||
{truncated ? 'at least ' : ''}
|
||||
{criticalCount > 0
|
||||
? `${criticalCount} critical · ${warnings.length} total`
|
||||
: `${warnings.length} note${warnings.length === 1 ? '' : 's'}`}
|
||||
@@ -634,6 +633,20 @@ function Findings({
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
{/* The list saying it is not the whole list. Last, because it is about
|
||||
everything above it — and never filtered out with the other `info`
|
||||
notes, which is where it used to disappear. */}
|
||||
{truncated && (
|
||||
<li className="finding finding--truncated">
|
||||
<Led variant="amber" />
|
||||
<div className="finding-copy">
|
||||
<span className="finding-where mono">list truncated</span>
|
||||
<span className="finding-msg">
|
||||
Some findings are missing from this list. {truncated.message}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
@@ -659,12 +672,20 @@ const NAV_LABEL: Record<Route, string> = {
|
||||
// for the apply/rollback flow, where the individual flags are the actual
|
||||
// subject of the page.)
|
||||
|
||||
function defaultTarget(config: Model | null): string {
|
||||
const rules = config?.Rules ?? []
|
||||
if (rules.length === 0) return '—'
|
||||
// The highest Order enabled rule is the effective catch-all.
|
||||
const enabled = rules.filter((r) => r.Enabled)
|
||||
if (enabled.length === 0) return 'none'
|
||||
const last = enabled.reduce((a, b) => (b.Order >= a.Order ? b : a))
|
||||
return last.Target || last.Egress || last.Name
|
||||
/** Where everything not matched by a rule goes — the engine's route `final`.
|
||||
*
|
||||
* Taken from the daemon (status.traffic.default), which reads it off the config
|
||||
* it is running. The guess this replaced was "the highest-Order enabled rule",
|
||||
* and that is not what the default is: a rule only becomes the default by having
|
||||
* NO conditions at all, whatever its Order (model.IsCatchAll), so a specific
|
||||
* high-Order rule was routinely printed here as the router's default. It also
|
||||
* described the config on disk rather than the one running, and could not see a
|
||||
* target that failed to resolve and fell back.
|
||||
*
|
||||
* Falls back to the rule count only when the daemon has not reported — never to
|
||||
* a guess about where traffic goes. */
|
||||
function defaultTarget(status: Status | null, config: Model | null): string {
|
||||
const d = status?.traffic?.default
|
||||
if (d) return d
|
||||
return len(config?.Rules) === 0 ? '—' : 'not reported'
|
||||
}
|
||||
|
||||
@@ -142,9 +142,6 @@
|
||||
width: 7rem;
|
||||
flex: none;
|
||||
}
|
||||
.pf-field--time {
|
||||
width: auto;
|
||||
}
|
||||
.pf-flabel {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
@@ -315,9 +312,6 @@
|
||||
color: var(--faint);
|
||||
font-style: italic;
|
||||
}
|
||||
.pf-chip--target {
|
||||
border-color: color-mix(in srgb, var(--accent) 30%, var(--groove));
|
||||
}
|
||||
.pf-chip--on {
|
||||
border-color: color-mix(in srgb, var(--led-on) 45%, var(--groove));
|
||||
color: var(--led-on);
|
||||
@@ -432,9 +426,6 @@
|
||||
.pf-erow-ctl {
|
||||
min-width: 0;
|
||||
}
|
||||
/* (The .pf-erow--muted dimming that used to sit here is gone with its reason:
|
||||
the watcher DOES evaluate an iface-driven profile's schedule now, so the
|
||||
schedule fields are never inert.) */
|
||||
.pf-ehint {
|
||||
margin: 6px 0 0;
|
||||
font-family: var(--font-sans);
|
||||
@@ -477,63 +468,6 @@
|
||||
outline-offset: 1px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.pf-chipinput-in {
|
||||
flex: 1 1 8rem;
|
||||
border: 0;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
padding: 3px 4px;
|
||||
}
|
||||
.pf-chipinput-in:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
.pf-chipinput:focus-within {
|
||||
border-color: var(--accent);
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* ---- schedule ---- */
|
||||
.pf-days {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.pf-day {
|
||||
padding: 6px 9px;
|
||||
border: 1px solid var(--groove);
|
||||
border-radius: 6px;
|
||||
background: var(--sink);
|
||||
color: var(--dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.02em;
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, border-color 0.15s, background 0.15s;
|
||||
}
|
||||
.pf-day:hover:not(:disabled) {
|
||||
color: var(--ink);
|
||||
}
|
||||
.pf-day.on {
|
||||
color: var(--accent);
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--groove));
|
||||
background: color-mix(in srgb, var(--accent) 12%, transparent);
|
||||
}
|
||||
.pf-day:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.pf-day:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: default;
|
||||
}
|
||||
.pf-times {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* ---- rule on/off matrix ---- */
|
||||
.pf-rules {
|
||||
@@ -594,56 +528,6 @@
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ---- preset packs ---- */
|
||||
.pf-pack-desc {
|
||||
margin: 6px 0 0;
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--dim);
|
||||
max-width: 60ch;
|
||||
}
|
||||
.pf-pack-target {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 6px;
|
||||
}
|
||||
.pf-adv {
|
||||
border-top: 1px solid var(--groove);
|
||||
}
|
||||
.pf-adv-summary {
|
||||
padding: 9px 14px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 10.5px;
|
||||
letter-spacing: var(--track-label, 0.16em);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
.pf-adv-summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
.pf-adv-summary::before {
|
||||
content: '▸ ';
|
||||
color: var(--faint);
|
||||
}
|
||||
.pf-adv[open] .pf-adv-summary::before {
|
||||
content: '▾ ';
|
||||
}
|
||||
.pf-adv-summary:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.pf-adv-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 0 14px 14px;
|
||||
}
|
||||
|
||||
/* ---- empty + skeleton ---- */
|
||||
.pf-empty {
|
||||
margin-top: calc(var(--u, 8px) * 2);
|
||||
@@ -706,10 +590,6 @@
|
||||
grid-column: 1 / -1;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.pf-pack-target {
|
||||
grid-column: 1 / -1;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@@ -717,7 +597,6 @@
|
||||
animation: none;
|
||||
}
|
||||
.pf-input,
|
||||
.pf-day,
|
||||
.pf-edit,
|
||||
.pf-del {
|
||||
transition: none;
|
||||
|
||||
+111
-539
@@ -1,19 +1,16 @@
|
||||
import './Profiles.css'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button, Led, Toggle } from '../components'
|
||||
import { apply as apiApply, getConfig, putConfig, ApiError } from '../api'
|
||||
import type { Model, Preset, Profile } from '../api'
|
||||
import { Button, Led, Toggle, useConfirm } from '../components'
|
||||
import { apply as apiApply, getConfig, getInterfaces, putConfig, ApiError } from '../api'
|
||||
import type { Interface, Model, Profile } from '../api'
|
||||
|
||||
// The Profiles page is a thin editor over the desired-state Model — the same
|
||||
// save→apply split as Settings / DNS / Routing. Every edit rewrites a slice in
|
||||
// place, PUTs the whole Model (save), marks the config dirty, and only Apply
|
||||
// pushes it onto the live data plane. Two sections:
|
||||
//
|
||||
// 1. PROFILES — named WAN-mode / failover overrides that activate by
|
||||
// condition (uplink iface, schedule). Manual override lives in
|
||||
// Globals.ActiveProfile ("" = auto, evaluated on the router).
|
||||
// 2. PRESET PACKS — three built-in curated rule bundles (block-ads / ru-bypass
|
||||
// / private). Toggling one upserts the matching entry in Model.Presets.
|
||||
// pushes it onto the live data plane. One section: PROFILES — named WAN-mode /
|
||||
// failover overrides that activate when the router's default-route uplink
|
||||
// matches. Manual override lives in Globals.ActiveProfile ("" = auto,
|
||||
// evaluated on the router).
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
@@ -27,59 +24,7 @@ const asArray = <T,>(a: T[] | null | undefined): T[] => (a ? a : [])
|
||||
const ruleSummary = (names: string[], max = 2): string =>
|
||||
names.length <= max ? names.join(', ') : `${names.slice(0, max).join(', ')} +${names.length - max} more`
|
||||
|
||||
// Weekday tokens as stored on the model (mon..sun), in display order.
|
||||
const DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const
|
||||
const cap = (s: string): string => (s ? s[0].toUpperCase() + s.slice(1) : s)
|
||||
|
||||
// ---- schedule timezone anchoring --------------------------------------------
|
||||
// The router carries no IANA tzdata, so the daemon cannot resolve a timezone
|
||||
// NAME — it evaluates schedule windows at a fixed UTC offset (minutes east,
|
||||
// model SchedUTCOffset). The panel's job is to capture the editing browser's
|
||||
// offset alongside every schedule edit, so "22:00" means 22:00 on the clock of
|
||||
// whoever wrote it. Known limitation (stated in the hint): a fixed offset does
|
||||
// not follow DST until the schedule is re-saved.
|
||||
|
||||
/** The browser's current UTC offset in minutes EAST (Moscow ⇒ 180). */
|
||||
const browserUTCOffsetMin = (): number => -new Date().getTimezoneOffset()
|
||||
|
||||
/** "UTC+03:00" / "UTC−05:00" for a minutes-east offset. */
|
||||
const utcOffsetLabel = (min: number): string => {
|
||||
const sign = min < 0 ? '−' : '+'
|
||||
const a = Math.abs(min)
|
||||
const hh = String(Math.floor(a / 60)).padStart(2, '0')
|
||||
const mm = String(a % 60).padStart(2, '0')
|
||||
return `UTC${sign}${hh}:${mm}`
|
||||
}
|
||||
|
||||
/** IANA-style name of the browser zone ("Europe/Moscow"), best-effort. */
|
||||
const browserTZName = (): string => {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'local time'
|
||||
} catch {
|
||||
return 'local time'
|
||||
}
|
||||
}
|
||||
|
||||
// The three built-in packs. Fixed set — the operator toggles them, never adds or
|
||||
// removes. Name is the on-disk `config preset` name the engine expands.
|
||||
const PACKS: ReadonlyArray<{ name: string; title: string; desc: string }> = [
|
||||
{ name: 'block-ads', title: 'Block ads', desc: 'Blocks known ad & tracker domains.' },
|
||||
{ name: 'ru-bypass', title: 'Russia bypass', desc: 'Routes Russian services direct (no proxy).' },
|
||||
{ name: 'private', title: 'Private ranges', desc: 'Keeps LAN / private ranges off the proxy.' },
|
||||
]
|
||||
|
||||
// ---- target picker ---------------------------------------------------------
|
||||
// A routing target in the model's canonical form: `direct` | `block` |
|
||||
// `group:<n>` | `chain:<n>` | `node:<n>` | `egress:<n>`. Built entirely from the
|
||||
// live Model, exactly like the Routing / DNS pickers.
|
||||
|
||||
interface TargetCatalog {
|
||||
groups: string[]
|
||||
chains: string[]
|
||||
nodes: string[]
|
||||
egresses: { name: string; type: string }[]
|
||||
}
|
||||
|
||||
// Pull Name strings out of a model slice (Rules / Resolvers) for the pickers.
|
||||
type Named = { Name?: unknown }
|
||||
function namesOf(v: unknown): string[] {
|
||||
if (!Array.isArray(v)) return []
|
||||
@@ -88,19 +33,10 @@ function namesOf(v: unknown): string[] {
|
||||
.filter((n): n is string => typeof n === 'string' && n.length > 0)
|
||||
}
|
||||
|
||||
/** Every valid canonical target value for a catalog (excludes the empty option). */
|
||||
function targetValues(cat: TargetCatalog): Set<string> {
|
||||
const s = new Set<string>(['direct', 'block'])
|
||||
for (const g of cat.groups) s.add(`group:${g}`)
|
||||
for (const c of cat.chains) s.add(`chain:${c}`)
|
||||
for (const n of cat.nodes) s.add(`node:${n}`)
|
||||
for (const e of cat.egresses) s.add(`egress:${e.name}`)
|
||||
return s
|
||||
}
|
||||
|
||||
// ---- page ------------------------------------------------------------------
|
||||
|
||||
export default function Profiles() {
|
||||
const confirm = useConfirm()
|
||||
const [config, setConfig] = useState<Model | null>(null)
|
||||
const [loadError, setLoadError] = useState<string | null>(null)
|
||||
|
||||
@@ -117,6 +53,24 @@ export default function Profiles() {
|
||||
void loadConfig()
|
||||
}, [loadConfig])
|
||||
|
||||
// The router's UCI interfaces feed the uplink-condition picker. Best-effort:
|
||||
// if the list can't be fetched the editor keeps existing chips removable and
|
||||
// simply offers nothing to add (same degradation as the Targets egress picker).
|
||||
const [interfaces, setInterfaces] = useState<Interface[]>([])
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
getInterfaces()
|
||||
.then((ifs) => {
|
||||
if (alive) setInterfaces(ifs)
|
||||
})
|
||||
.catch(() => {
|
||||
/* leave empty → chips stay removable, nothing to add */
|
||||
})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
// ---- toast + persistent apply banner (mirrors DNS / Settings) -------------
|
||||
const [toast, setToast] = useState<string | null>(null)
|
||||
const toastTimer = useRef<number | undefined>(undefined)
|
||||
@@ -174,22 +128,9 @@ export default function Profiles() {
|
||||
// ---- derived slices -------------------------------------------------------
|
||||
const globals = config?.Globals
|
||||
const profiles = useMemo<Profile[]>(() => asArray(config?.Profiles), [config])
|
||||
const presets = useMemo<Preset[]>(() => asArray(config?.Presets), [config])
|
||||
const ruleNames = useMemo(() => namesOf(config?.Rules), [config])
|
||||
const egresses = useMemo(() => asArray(config?.Egresses), [config])
|
||||
const resolverNames = useMemo(() => namesOf(config?.Resolvers), [config])
|
||||
|
||||
const catalog = useMemo<TargetCatalog>(
|
||||
() => ({
|
||||
groups: namesOf(config?.Groups),
|
||||
chains: namesOf(config?.['Chains']),
|
||||
nodes: namesOf(config?.Nodes),
|
||||
egresses: egresses.map((e) => ({ name: e.Name, type: e.Type })),
|
||||
}),
|
||||
[config, egresses],
|
||||
)
|
||||
const targetValid = useMemo(() => targetValues(catalog), [catalog])
|
||||
|
||||
const profileNames = useMemo(() => new Set(profiles.map((p) => p.Name)), [profiles])
|
||||
const active = globals?.ActiveProfile ?? ''
|
||||
const busy = saving || applying
|
||||
@@ -226,7 +167,6 @@ export default function Profiles() {
|
||||
Enabled: true,
|
||||
Priority: priority,
|
||||
MatchIface: [],
|
||||
SchedDays: [],
|
||||
EnableRules: [],
|
||||
DisableRules: [],
|
||||
}
|
||||
@@ -253,9 +193,14 @@ export default function Profiles() {
|
||||
)
|
||||
|
||||
const deleteProfile = useCallback(
|
||||
(name: string) => {
|
||||
async (name: string) => {
|
||||
if (!config) return
|
||||
if (!window.confirm(`Delete profile “${name}”? Its overrides stop applying.`)) return
|
||||
const ok = await confirm({
|
||||
label: 'Delete profile',
|
||||
title: `Delete profile “${name}”?`,
|
||||
body: 'Its overrides stop applying.',
|
||||
})
|
||||
if (!ok) return
|
||||
const next = profiles.filter((p) => p.Name !== name)
|
||||
const g =
|
||||
config.Globals.ActiveProfile === name
|
||||
@@ -263,20 +208,7 @@ export default function Profiles() {
|
||||
: config.Globals
|
||||
void save({ ...config, Profiles: next, Globals: g }, `Deleted ${name}`)
|
||||
},
|
||||
[config, profiles, save],
|
||||
)
|
||||
|
||||
// ---- preset-pack upsert ---------------------------------------------------
|
||||
const setPreset = useCallback(
|
||||
(name: string, patch: Partial<Preset>, msg: string) => {
|
||||
if (!config) return
|
||||
const exists = presets.some((p) => p.Name === name)
|
||||
const next = exists
|
||||
? presets.map((p) => (p.Name === name ? { ...p, ...patch } : p))
|
||||
: [...presets, { Name: name, Enabled: false, ...patch }]
|
||||
void save({ ...config, Presets: next }, msg)
|
||||
},
|
||||
[config, presets, save],
|
||||
[config, profiles, save, confirm],
|
||||
)
|
||||
|
||||
// ---- expansion (only one profile editor open at a time) -------------------
|
||||
@@ -319,7 +251,7 @@ export default function Profiles() {
|
||||
const loading = config === null && loadError === null
|
||||
|
||||
return (
|
||||
<section className="page pf-page" aria-label="Profiles and preset packs">
|
||||
<section className="page pf-page" aria-label="Profiles">
|
||||
{loadError && (
|
||||
<p className="page-error" role="alert">
|
||||
Couldn’t read config — {loadError}.{' '}
|
||||
@@ -351,7 +283,7 @@ export default function Profiles() {
|
||||
onChange={setActive}
|
||||
/>
|
||||
|
||||
{/* ---- 1. PROFILES ---- */}
|
||||
{/* ---- PROFILES ---- */}
|
||||
<div className="pf-section" aria-label="Profiles">
|
||||
<header className="pf-sec-hd">
|
||||
<h2 className="pf-sec-title">Profiles</h2>
|
||||
@@ -360,9 +292,9 @@ export default function Profiles() {
|
||||
</span>
|
||||
</header>
|
||||
<p className="pf-sec-note">
|
||||
A profile is a named override that switches on by condition — which uplink is carrying the
|
||||
router, or a time window. When active it can flip rules on or off and change the default
|
||||
route. Higher priority wins; a manual override above beats every condition.
|
||||
A profile is a named override that switches on by condition — which uplink is carrying
|
||||
the router. When active it can flip rules on or off. Higher priority wins; a manual
|
||||
override above beats every condition.
|
||||
</p>
|
||||
|
||||
<AddProfileForm busy={busy} disabled={!config} taken={profileNames} onAdd={addProfile} />
|
||||
@@ -376,7 +308,7 @@ export default function Profiles() {
|
||||
<div className="pf-empty">
|
||||
<span className="pf-empty-title mono">No profiles</span>
|
||||
<p className="pf-empty-body">
|
||||
No profiles — add one to auto-switch routing by uplink or schedule.
|
||||
No profiles — add one to auto-switch routing by the active uplink.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -391,10 +323,8 @@ export default function Profiles() {
|
||||
onOpen={() => setOpenName(openName === p.Name ? null : p.Name)}
|
||||
busy={busy}
|
||||
ruleNames={ruleNames}
|
||||
egresses={egresses}
|
||||
interfaces={interfaces}
|
||||
resolverNames={resolverNames}
|
||||
catalog={catalog}
|
||||
valid={targetValid}
|
||||
taken={profileNames}
|
||||
onPatch={(patch, msg) => patchProfile(p.Name, patch, msg)}
|
||||
onRename={(nn) => onRename(p.Name, nn)}
|
||||
@@ -405,38 +335,6 @@ export default function Profiles() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ---- 2. PRESET PACKS ---- */}
|
||||
<div className="pf-section" aria-label="Preset packs">
|
||||
<header className="pf-sec-hd">
|
||||
<h2 className="pf-sec-title">Preset packs</h2>
|
||||
<span className="pf-sec-count mono">
|
||||
{presets.filter((p) => p.Enabled).length} / {PACKS.length} on
|
||||
</span>
|
||||
</header>
|
||||
<p className="pf-sec-note">
|
||||
Curated rule bundles, built in. Turn one on to add its rules to the router; set a target to
|
||||
override where its traffic goes.
|
||||
</p>
|
||||
|
||||
<ul className="pf-rows">
|
||||
{PACKS.map((pack) => {
|
||||
const entry = presets.find((p) => p.Name === pack.name)
|
||||
return (
|
||||
<PackRow
|
||||
key={pack.name}
|
||||
pack={pack}
|
||||
preset={entry}
|
||||
busy={busy}
|
||||
disabled={!config}
|
||||
catalog={catalog}
|
||||
valid={targetValid}
|
||||
onSet={(patch, msg) => setPreset(pack.name, patch, msg)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{toast && (
|
||||
<div className="toast" role="status">
|
||||
{toast}
|
||||
@@ -660,10 +558,8 @@ function ProfileRow({
|
||||
onOpen,
|
||||
busy,
|
||||
ruleNames,
|
||||
egresses,
|
||||
interfaces,
|
||||
resolverNames,
|
||||
catalog,
|
||||
valid,
|
||||
taken,
|
||||
onPatch,
|
||||
onRename,
|
||||
@@ -676,10 +572,8 @@ function ProfileRow({
|
||||
onOpen: () => void
|
||||
busy: boolean
|
||||
ruleNames: string[]
|
||||
egresses: { Name: string }[]
|
||||
interfaces: Interface[]
|
||||
resolverNames: string[]
|
||||
catalog: TargetCatalog
|
||||
valid: Set<string>
|
||||
taken: Set<string>
|
||||
onPatch: (patch: Partial<Profile>, msg: string) => void
|
||||
onRename: (newName: string) => void
|
||||
@@ -688,8 +582,6 @@ function ProfileRow({
|
||||
const iface = asArray(profile.MatchIface)
|
||||
const enableRules = asArray(profile.EnableRules)
|
||||
const disableRules = asArray(profile.DisableRules)
|
||||
const days = asArray(profile.SchedDays)
|
||||
const hasSchedule = days.length > 0 || !!profile.SchedStart || !!profile.SchedEnd
|
||||
|
||||
return (
|
||||
<li className={profile.Enabled ? 'pf-row' : 'pf-row off'}>
|
||||
@@ -721,42 +613,16 @@ function ProfileRow({
|
||||
)}
|
||||
</div>
|
||||
<div className="pf-row-l2">
|
||||
{!hasSchedule && iface.length === 0 ? (
|
||||
{iface.length === 0 ? (
|
||||
<span className="pf-chip pf-chip--muted">always — no condition set</span>
|
||||
) : (
|
||||
<>
|
||||
{iface.length > 0 && (
|
||||
<span className="pf-chip">
|
||||
<b>iface</b>
|
||||
<span className="mono">{iface.join(', ')}</span>
|
||||
</span>
|
||||
)}
|
||||
{hasSchedule && (
|
||||
<span className="pf-chip">
|
||||
<b>time</b>
|
||||
<span className="mono">
|
||||
{days.length ? days.map(cap).join(',') + ' ' : ''}
|
||||
{(profile.SchedStart || '00:00') + '–' + (profile.SchedEnd || '24:00')}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{(enableRules.length > 0 ||
|
||||
disableRules.length > 0 ||
|
||||
!!profile.DefaultTarget ||
|
||||
!!profile.DefaultEgress) && <span className="pf-chip-sep" aria-hidden="true">→</span>}
|
||||
{profile.DefaultTarget && (
|
||||
<span className="pf-chip pf-chip--target">
|
||||
<b>route</b>
|
||||
<span className="mono">{profile.DefaultTarget}</span>
|
||||
<span className="pf-chip">
|
||||
<b>iface</b>
|
||||
<span className="mono">{iface.join(', ')}</span>
|
||||
</span>
|
||||
)}
|
||||
{profile.DefaultEgress && (
|
||||
<span className="pf-chip pf-chip--target">
|
||||
<b>egress</b>
|
||||
<span className="mono">{profile.DefaultEgress}</span>
|
||||
</span>
|
||||
{(enableRules.length > 0 || disableRules.length > 0) && (
|
||||
<span className="pf-chip-sep" aria-hidden="true">→</span>
|
||||
)}
|
||||
{enableRules.length > 0 && (
|
||||
<span
|
||||
@@ -803,10 +669,8 @@ function ProfileRow({
|
||||
profile={profile}
|
||||
busy={busy}
|
||||
ruleNames={ruleNames}
|
||||
egresses={egresses}
|
||||
interfaces={interfaces}
|
||||
resolverNames={resolverNames}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
taken={taken}
|
||||
onPatch={onPatch}
|
||||
onRename={onRename}
|
||||
@@ -822,10 +686,8 @@ function ProfileEditor({
|
||||
profile,
|
||||
busy,
|
||||
ruleNames,
|
||||
egresses,
|
||||
interfaces,
|
||||
resolverNames,
|
||||
catalog,
|
||||
valid,
|
||||
taken,
|
||||
onPatch,
|
||||
onRename,
|
||||
@@ -833,10 +695,8 @@ function ProfileEditor({
|
||||
profile: Profile
|
||||
busy: boolean
|
||||
ruleNames: string[]
|
||||
egresses: { Name: string }[]
|
||||
interfaces: Interface[]
|
||||
resolverNames: string[]
|
||||
catalog: TargetCatalog
|
||||
valid: Set<string>
|
||||
taken: Set<string>
|
||||
onPatch: (patch: Partial<Profile>, msg: string) => void
|
||||
onRename: (newName: string) => void
|
||||
@@ -844,7 +704,6 @@ function ProfileEditor({
|
||||
const iface = asArray(profile.MatchIface)
|
||||
const enableRules = asArray(profile.EnableRules)
|
||||
const disableRules = asArray(profile.DisableRules)
|
||||
const days = asArray(profile.SchedDays)
|
||||
|
||||
// Name is the only field that can't be a bare instant-save (needs a uniqueness
|
||||
// guard + it moves the ActiveProfile pointer), so it commits on blur/Enter.
|
||||
@@ -862,18 +721,6 @@ function ProfileEditor({
|
||||
const removeIface = (dev: string) =>
|
||||
onPatch({ MatchIface: iface.filter((x) => x !== dev) }, `iface − ${dev}`)
|
||||
|
||||
// Every schedule edit re-anchors the window to the editing browser's UTC
|
||||
// offset — the daemon has no tzdata, so the offset IS the timezone (see the
|
||||
// schedule helpers at the top of the file).
|
||||
const patchSched = (patch: Partial<Profile>, msg: string) =>
|
||||
onPatch({ ...patch, SchedUTCOffset: browserUTCOffsetMin() }, msg)
|
||||
|
||||
const toggleDay = (d: string) =>
|
||||
patchSched(
|
||||
{ SchedDays: days.includes(d) ? days.filter((x) => x !== d) : [...days, d] },
|
||||
'Schedule updated',
|
||||
)
|
||||
|
||||
// A rule sits in at most one override list. Checking it in one clears the other.
|
||||
const toggleRule = (rule: string, list: 'enable' | 'disable') => {
|
||||
if (list === 'enable') {
|
||||
@@ -917,15 +764,14 @@ function ProfileEditor({
|
||||
|
||||
{/* -- conditions -- */}
|
||||
<fieldset className="pf-eblock">
|
||||
<legend className="pf-elegend">Conditions — all must hold</legend>
|
||||
<legend className="pf-elegend">Condition</legend>
|
||||
|
||||
<div className="pf-erow">
|
||||
<span className="pf-elabel">Uplink interface</span>
|
||||
<div className="pf-erow-ctl">
|
||||
<ChipInput
|
||||
<IfaceChips
|
||||
chips={iface}
|
||||
placeholder="wwan0, usb0…"
|
||||
ariaLabel="Uplink interface names"
|
||||
interfaces={interfaces}
|
||||
busy={busy}
|
||||
onAdd={addIface}
|
||||
onRemove={removeIface}
|
||||
@@ -934,131 +780,17 @@ function ProfileEditor({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* A "Probe" condition (URL + activate-when-up/down) used to sit here. It
|
||||
never probed anything, and it did worse than nothing: a profile that
|
||||
carried one was treated as having a condition that could never hold, so
|
||||
filling this in SWITCHED OFF an otherwise working profile. Both fields
|
||||
are gone from the daemon; the conditions that remain are the two below,
|
||||
which are read for real. */}
|
||||
|
||||
<div className="pf-erow">
|
||||
<span className="pf-elabel">Schedule</span>
|
||||
<div className="pf-erow-ctl">
|
||||
{iface.length > 0 && (
|
||||
<p className="pf-ehint">
|
||||
Applies together with the uplink match: the profile is active only while the uplink
|
||||
matches AND the window is open (the watcher re-checks both every ~25 s).
|
||||
</p>
|
||||
)}
|
||||
<div className="pf-days" role="group" aria-label="Active days (none = every day)">
|
||||
{DAYS.map((d) => {
|
||||
const on = days.includes(d)
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={d}
|
||||
className={on ? 'pf-day on' : 'pf-day'}
|
||||
aria-pressed={on}
|
||||
onClick={() => toggleDay(d)}
|
||||
disabled={busy}
|
||||
>
|
||||
{cap(d)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="pf-times">
|
||||
<label className="pf-field pf-field--time">
|
||||
<span className="pf-flabel">From</span>
|
||||
<input
|
||||
className="pf-input mono"
|
||||
type="time"
|
||||
value={profile.SchedStart ?? ''}
|
||||
onChange={(e) => patchSched({ SchedStart: e.target.value }, 'Schedule updated')}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
<label className="pf-field pf-field--time">
|
||||
<span className="pf-flabel">To</span>
|
||||
<input
|
||||
className="pf-input mono"
|
||||
type="time"
|
||||
value={profile.SchedEnd ?? ''}
|
||||
onChange={(e) => patchSched({ SchedEnd: e.target.value }, 'Schedule updated')}
|
||||
disabled={busy}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="pf-ehint">
|
||||
No days = every day · empty times = all day · times are in your browser's timezone (
|
||||
{browserTZName()}, {utcOffsetLabel(browserUTCOffsetMin())}) — the offset is saved with the
|
||||
schedule; DST shifts apply after a re-save.
|
||||
</p>
|
||||
{(profile.SchedUTCOffset ?? 0) !== browserUTCOffsetMin() &&
|
||||
((profile.SchedStart ?? '') !== '' ||
|
||||
(profile.SchedEnd ?? '') !== '' ||
|
||||
days.length > 0) && (
|
||||
<p className="pf-ehint">
|
||||
This schedule was saved at {utcOffsetLabel(profile.SchedUTCOffset ?? 0)} — the times
|
||||
above are on that clock. Editing any schedule field re-anchors it to your timezone.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* A "Probe" condition (URL + activate-when-up/down) used to sit here, and
|
||||
a schedule window below it. The probe never probed anything and treated
|
||||
a profile carrying one as unsatisfiable — filling it in SWITCHED OFF an
|
||||
otherwise working profile; the schedule editor left with the feature.
|
||||
The uplink match above is the one condition left, read for real. */}
|
||||
</fieldset>
|
||||
|
||||
{/* -- overrides -- */}
|
||||
<fieldset className="pf-eblock">
|
||||
<legend className="pf-elegend">Overrides while active</legend>
|
||||
|
||||
<div className="pf-erow">
|
||||
<span className="pf-elabel">Default route</span>
|
||||
<div className="pf-erow-ctl">
|
||||
<TargetSelect
|
||||
value={profile.DefaultTarget ?? ''}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
includeNoOverride
|
||||
noOverrideLabel="No override — keep default"
|
||||
busy={busy}
|
||||
ariaLabel="Default route target"
|
||||
onChange={(v) =>
|
||||
onPatch({ DefaultTarget: v }, v ? `Default route → ${v}` : 'Default route override cleared')
|
||||
}
|
||||
/>
|
||||
<p className="pf-ehint">Where unmatched traffic goes while this profile is active.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pf-erow">
|
||||
<span className="pf-elabel">Default egress</span>
|
||||
<div className="pf-erow-ctl">
|
||||
<select
|
||||
className="pf-select"
|
||||
value={profile.DefaultEgress ?? ''}
|
||||
onChange={(e) =>
|
||||
onPatch(
|
||||
{ DefaultEgress: e.target.value },
|
||||
e.target.value ? `Egress → ${e.target.value}` : 'Egress override cleared',
|
||||
)
|
||||
}
|
||||
disabled={busy}
|
||||
aria-label="Default egress"
|
||||
>
|
||||
<option value="">No override</option>
|
||||
{egresses.map((eg) => (
|
||||
<option key={eg.Name} value={eg.Name}>
|
||||
{eg.Name}
|
||||
</option>
|
||||
))}
|
||||
{profile.DefaultEgress && !egresses.some((eg) => eg.Name === profile.DefaultEgress) && (
|
||||
<option value={profile.DefaultEgress}>{profile.DefaultEgress} (missing)</option>
|
||||
)}
|
||||
</select>
|
||||
<p className="pf-ehint">Pins the outbound interface / egress for this profile.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pf-erow">
|
||||
<span className="pf-elabel">Endpoint resolver</span>
|
||||
<div className="pf-erow-ctl">
|
||||
@@ -1141,172 +873,8 @@ function ProfileEditor({
|
||||
)
|
||||
}
|
||||
|
||||
// ---- a preset pack row -----------------------------------------------------
|
||||
|
||||
function PackRow({
|
||||
pack,
|
||||
preset,
|
||||
busy,
|
||||
disabled,
|
||||
catalog,
|
||||
valid,
|
||||
onSet,
|
||||
}: {
|
||||
pack: { name: string; title: string; desc: string }
|
||||
preset: Preset | undefined
|
||||
busy: boolean
|
||||
disabled: boolean
|
||||
catalog: TargetCatalog
|
||||
valid: Set<string>
|
||||
onSet: (patch: Partial<Preset>, msg: string) => void
|
||||
}) {
|
||||
const enabled = preset?.Enabled ?? false
|
||||
const target = preset?.Target ?? ''
|
||||
const [advOpen, setAdvOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<li className={enabled ? 'pf-row pf-pack' : 'pf-row pf-pack off'}>
|
||||
<div className="pf-row-head">
|
||||
<Toggle
|
||||
pressed={enabled}
|
||||
onChange={(on) => onSet({ Enabled: on }, `${pack.name} ${on ? 'enabled' : 'disabled'}`)}
|
||||
label={`${enabled ? 'Disable' : 'Enable'} ${pack.title}`}
|
||||
disabled={busy || disabled}
|
||||
/>
|
||||
<div className="pf-row-main">
|
||||
<div className="pf-row-l1">
|
||||
<span className="pf-row-name">{pack.title}</span>
|
||||
<span className="pf-badge mono">{pack.name}</span>
|
||||
</div>
|
||||
<p className="pf-pack-desc">{pack.desc}</p>
|
||||
</div>
|
||||
<label className="pf-pack-target">
|
||||
<span className="pf-active-ctl-label mono">Target</span>
|
||||
<TargetSelect
|
||||
value={target}
|
||||
catalog={catalog}
|
||||
valid={valid}
|
||||
includeNoOverride
|
||||
noOverrideLabel="Pack default"
|
||||
busy={busy}
|
||||
disabled={disabled}
|
||||
ariaLabel={`${pack.title} target`}
|
||||
onChange={(v) => onSet({ Target: v }, v ? `${pack.name} → ${v}` : `${pack.name} → pack default`)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<details
|
||||
className="pf-adv"
|
||||
open={advOpen}
|
||||
onToggle={(e) => setAdvOpen((e.target as HTMLDetailsElement).open)}
|
||||
>
|
||||
<summary className="pf-adv-summary">Advanced</summary>
|
||||
<div className="pf-adv-body">
|
||||
<label className="pf-field pf-field--num">
|
||||
<span className="pf-flabel">Order</span>
|
||||
<BlurField
|
||||
value={preset?.Order != null ? String(preset.Order) : ''}
|
||||
onCommit={(v) => {
|
||||
const s = v.trim()
|
||||
if (s === '') {
|
||||
onSet({ Order: undefined }, `${pack.name} order cleared`)
|
||||
} else if (/^\d+$/.test(s)) {
|
||||
onSet({ Order: Number(s) }, `${pack.name} order → ${s}`)
|
||||
}
|
||||
}}
|
||||
placeholder="auto"
|
||||
ariaLabel={`${pack.title} order`}
|
||||
busy={busy}
|
||||
width="6rem"
|
||||
inputMode="numeric"
|
||||
/>
|
||||
</label>
|
||||
<p className="pf-ehint">Lower runs first among packs. Leave blank for the built-in order.</p>
|
||||
</div>
|
||||
</details>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
// ---- shared controls -------------------------------------------------------
|
||||
|
||||
/** Canonical target picker (direct/block + groups/chains/nodes/egresses). */
|
||||
function TargetSelect({
|
||||
value,
|
||||
catalog,
|
||||
valid,
|
||||
includeNoOverride,
|
||||
noOverrideLabel,
|
||||
busy,
|
||||
disabled,
|
||||
ariaLabel,
|
||||
onChange,
|
||||
}: {
|
||||
value: string
|
||||
catalog: TargetCatalog
|
||||
valid: Set<string>
|
||||
includeNoOverride?: boolean
|
||||
noOverrideLabel?: string
|
||||
busy: boolean
|
||||
disabled?: boolean
|
||||
ariaLabel: string
|
||||
onChange: (v: string) => void
|
||||
}) {
|
||||
const missing = value !== '' && !valid.has(value)
|
||||
return (
|
||||
<select
|
||||
className="pf-select"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
disabled={busy || disabled}
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
{includeNoOverride && <option value="">{noOverrideLabel ?? 'No override'}</option>}
|
||||
<option value="direct">Direct (no proxy)</option>
|
||||
<option value="block">Block</option>
|
||||
{catalog.groups.length > 0 && (
|
||||
<optgroup label="Groups">
|
||||
{catalog.groups.map((g) => (
|
||||
<option key={g} value={`group:${g}`}>
|
||||
Group {g} (balancer)
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.chains.length > 0 && (
|
||||
<optgroup label="Chains">
|
||||
{catalog.chains.map((c) => (
|
||||
<option key={c} value={`chain:${c}`}>
|
||||
Chain {c}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.nodes.length > 0 && (
|
||||
<optgroup label="Nodes">
|
||||
{catalog.nodes.map((n) => (
|
||||
<option key={n} value={`node:${n}`}>
|
||||
Node {n}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{catalog.egresses.length > 0 && (
|
||||
<optgroup label="Interfaces / egresses">
|
||||
{catalog.egresses.map((e) => (
|
||||
<option key={e.name} value={`egress:${e.name}`}>
|
||||
Interface/egress {e.name}
|
||||
{e.type ? ` (${e.type})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
)}
|
||||
{missing && <option value={value}>{value} (missing)</option>}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
/** A text input that keeps a local draft and commits on blur / Enter, reverts on Escape. */
|
||||
function BlurField({
|
||||
value,
|
||||
@@ -1361,65 +929,69 @@ function BlurField({
|
||||
)
|
||||
}
|
||||
|
||||
/** A chips editor: type + Enter to add, ✕ to remove. */
|
||||
function ChipInput({
|
||||
/** Uplink-iface chips + a dropdown of the router's UCI interfaces to add from.
|
||||
* A stored iface missing from the live list still renders as a chip (marked
|
||||
* stale) so it stays removable; with no interfaces fetched there is simply
|
||||
* nothing to add. */
|
||||
function IfaceChips({
|
||||
chips,
|
||||
placeholder,
|
||||
ariaLabel,
|
||||
interfaces,
|
||||
busy,
|
||||
onAdd,
|
||||
onRemove,
|
||||
}: {
|
||||
chips: string[]
|
||||
placeholder?: string
|
||||
ariaLabel: string
|
||||
interfaces: Interface[]
|
||||
busy: boolean
|
||||
onAdd: (v: string) => void
|
||||
onRemove: (v: string) => void
|
||||
}) {
|
||||
const [draft, setDraft] = useState('')
|
||||
|
||||
const commit = () => {
|
||||
const v = draft.trim()
|
||||
if (!v) return
|
||||
onAdd(v)
|
||||
setDraft('')
|
||||
}
|
||||
|
||||
const known = new Set(interfaces.map((i) => i.name))
|
||||
const available = interfaces.filter((i) => !chips.includes(i.name))
|
||||
return (
|
||||
<div className="pf-chipinput">
|
||||
{chips.map((c) => (
|
||||
<span key={c} className="pf-chip pf-chip--edit">
|
||||
<span className="mono">{c}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="pf-chip-x"
|
||||
aria-label={`Remove ${c}`}
|
||||
onClick={() => onRemove(c)}
|
||||
disabled={busy}
|
||||
{chips.map((c) => {
|
||||
const stale = interfaces.length > 0 && !known.has(c)
|
||||
return (
|
||||
<span
|
||||
key={c}
|
||||
className="pf-chip pf-chip--edit"
|
||||
title={stale ? 'Not among the router’s interfaces' : undefined}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
<input
|
||||
className="pf-input pf-chipinput-in mono"
|
||||
type="text"
|
||||
value={draft}
|
||||
placeholder={placeholder}
|
||||
aria-label={ariaLabel}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
disabled={busy}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault()
|
||||
commit()
|
||||
}
|
||||
}}
|
||||
onBlur={commit}
|
||||
/>
|
||||
<span className="mono">
|
||||
{c}
|
||||
{stale ? ' (stale)' : ''}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="pf-chip-x"
|
||||
aria-label={`Remove ${c}`}
|
||||
onClick={() => onRemove(c)}
|
||||
disabled={busy}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
{available.length > 0 && (
|
||||
<select
|
||||
className="pf-select"
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
if (e.target.value) onAdd(e.target.value)
|
||||
}}
|
||||
disabled={busy}
|
||||
aria-label="Add uplink interface"
|
||||
>
|
||||
<option value="">Add interface…</option>
|
||||
{available.map((i) => (
|
||||
<option key={i.name} value={i.name}>
|
||||
{i.name} ({i.device || '?'}){i.up ? '' : ' — down'}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+123
-6
@@ -58,6 +58,45 @@
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* ---- active-profile banner ----
|
||||
*
|
||||
* Deliberately NOT the accent plate the save→apply bar wears above. Orange is
|
||||
* "there is something for you to do" on this faceplate, and an active WAN profile
|
||||
* is a standing condition, not a pending action. A quiet plate with an amber tag
|
||||
* reads as "note the state" — and it is the SAME amber the overridden rows below
|
||||
* carry, so the banner and its rows are visibly one story rather than two
|
||||
* unrelated oddities. */
|
||||
.rt-prof-banner {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
margin: 0 0 calc(var(--u, 8px) * 2.5);
|
||||
padding: 10px 14px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 35%, var(--groove));
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--amber) 7%, transparent);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: var(--dim);
|
||||
}
|
||||
.rt-prof-banner strong {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
.rt-prof-tag {
|
||||
flex: none;
|
||||
margin-top: 1px;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 55%, var(--groove));
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--amber) 12%, transparent);
|
||||
font-size: 9px;
|
||||
letter-spacing: var(--track-label);
|
||||
text-transform: uppercase;
|
||||
color: var(--amber);
|
||||
}
|
||||
|
||||
/* ---- empty state ---- */
|
||||
.rt-empty {
|
||||
padding: calc(var(--u, 8px) * 4) 0 calc(var(--u, 8px) * 3);
|
||||
@@ -252,6 +291,88 @@
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
/* ---- a rule that can never fire (superseded by a later condition-less rule) ----
|
||||
*
|
||||
* Warn semantics only: --amber, never --accent. Orange is the ACTIVE state on this
|
||||
* faceplate, and a rule the router ignores is the opposite of active — painting it
|
||||
* orange is what made two `default` rows look equally live. It is a dashed amber
|
||||
* frame, an amber order chip, and a dimmed target, so the row reads as "wired but
|
||||
* not connected" without shouting: nothing is broken, one setting is just inert. */
|
||||
.rt-rule.dead {
|
||||
border-style: dashed;
|
||||
border-color: color-mix(in srgb, var(--amber) 55%, var(--groove));
|
||||
background: var(--panel);
|
||||
box-shadow: none;
|
||||
}
|
||||
.rt-ord.dead {
|
||||
color: var(--amber);
|
||||
border-color: color-mix(in srgb, var(--amber) 45%, var(--groove));
|
||||
}
|
||||
.rt-badge.dead {
|
||||
padding: 1px 7px;
|
||||
border: 1px solid color-mix(in srgb, var(--amber) 55%, var(--groove));
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--amber) 12%, transparent);
|
||||
color: var(--amber);
|
||||
}
|
||||
.rt-dead-note {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.45;
|
||||
color: var(--dim);
|
||||
}
|
||||
/* The target is still what the operator asked for, so it stays readable — just
|
||||
* quiet, because the router is not using it. */
|
||||
.rt-rule.dead .rt-target {
|
||||
border-style: dashed;
|
||||
opacity: 0.62;
|
||||
}
|
||||
|
||||
/* ---- a rule the active WAN profile overrides ----
|
||||
*
|
||||
* The row itself needs no new paint: an overridden-off rule already wears `.off`
|
||||
* (it is off, whatever its switch says) and an overridden-on rule wears nothing
|
||||
* (it is on). What was missing was never colour — it was the sentence naming who
|
||||
* decided. So this is the per-row twin of the banner and borrows .rt-dead-note's
|
||||
* type wholesale: same voice, same size, one <p> margin to reset. */
|
||||
/* The same pill as .rt-badge.dead, so the two override states read as one pair,
|
||||
* but in accent — a rule the profile forces ON is active, and active is orange on
|
||||
* this faceplate. The pill is also what keeps it from running into the plain
|
||||
* "default route · final" badge beside it, where "final on · by profile" read as
|
||||
* one phrase. */
|
||||
.rt-badge.prof-on {
|
||||
padding: 1px 7px;
|
||||
border: 1px solid var(--accent-soft);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--accent) 10%, transparent);
|
||||
}
|
||||
|
||||
.rt-prof-note {
|
||||
margin: 0;
|
||||
}
|
||||
.rt-prof-note strong {
|
||||
color: var(--ink);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Switch + its legend. The caption shows ONLY while a profile overrides the rule,
|
||||
* and it is what keeps the control honest: the plate says what the router is
|
||||
* doing, this says the switch is about the saved setting. A legend under the
|
||||
* control it names is the faceplate's own idiom. */
|
||||
.rt-switch {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
}
|
||||
.rt-switch-note {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 8.5px;
|
||||
letter-spacing: var(--track-label);
|
||||
text-transform: uppercase;
|
||||
color: var(--faint);
|
||||
}
|
||||
|
||||
/* ---- target chip (styled like the artifact's group:auto mono chips) ---- */
|
||||
.rt-target {
|
||||
display: inline-flex;
|
||||
@@ -359,9 +480,6 @@
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
}
|
||||
.rt-field-wide {
|
||||
grid-column: span 2;
|
||||
}
|
||||
.rt-flabel {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 9px;
|
||||
@@ -478,6 +596,8 @@ select.rt-input {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 1px 0 var(--edge) inset, 0 0 0 1px var(--accent-soft);
|
||||
}
|
||||
/* "no matchers" flag in the plate foot — shared by BOTH rule forms (add and
|
||||
* edit), so the same non-blocking warning reads identically in either. */
|
||||
.rt-edit-warn {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
@@ -800,9 +920,6 @@ select.rt-input {
|
||||
justify-content: flex-start;
|
||||
align-self: start;
|
||||
}
|
||||
.rt-field-wide {
|
||||
grid-column: auto;
|
||||
}
|
||||
.rt-rs-row {
|
||||
grid-template-columns: 1fr;
|
||||
row-gap: 10px;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user