Merge main into the IPv6 certificate branch

install.sh conflicted where the branch made a failed config_after_install
abort the installer. Resolved to main's flow: the installer carries on and
sets up fail2ban, as it did before this branch.
This commit is contained in:
Sanaei
2026-11-29 17:29:15 +03:30
656 changed files with 58136 additions and 7088 deletions
+6
View File
@@ -0,0 +1,6 @@
# actionlint v1.7.12 bundles claude-code-action metadata older than v1.0.288,
# which added allow_fork_prs; drop this entry once actionlint knows the input.
paths:
.github/workflows/claude-pr-review.yml:
ignore:
- 'input "allow_fork_prs" is not defined in action "anthropics/claude-code-action@v1"'
+4 -2
View File
@@ -148,6 +148,7 @@ It is paths-filtered, so a docs-only or workflow-only change produces no run.
| `go-test` | `go test -shuffle=on -count=1` over every package except `frontend/node_modules` |
| `race` | the same set under `-race -shuffle=on` |
| `postgres-durable-first` | live PostgreSQL 16: the `PostgresCommitFailure` tests plus `TestHostAutoMigrateCreatesColumns_Postgres` and `TestMigrate_Postgres`. Both steps COUNT passes rather than assert on SKIP, so a renamed or deleted test fails the job |
| `xray-e2e` | `make xray-e2e`: the `XRAY_E2E_BINARY` tests in `internal/xray/`, `internal/web/service/` and `internal/amneziawgnet/` against the core pinned in `go.mod`, run as a real child process. A skip naming the binary fails the job |
| `govulncheck` | known vulnerabilities |
| `golangci` | `golangci-lint` |
| `fuzz-smoke` | 30s each on `FuzzParseLink` and `FuzzDecodeCertPin` |
@@ -155,13 +156,14 @@ It is paths-filtered, so a docs-only or workflow-only change produces no run.
| `frontend` | lint, format:check, typecheck, `npm test` (Vitest + headless-Chromium Storybook), build, build-storybook, `npm audit` |
**What CI does NOT prove.** These test families `t.Skip` unless an environment
variable is set, and CI sets only the PostgreSQL ones above:
variable is set. CI sets the PostgreSQL ones in `postgres-durable-first` and
`XRAY_E2E_BINARY` in `xray-e2e` only, so every other job still skips them:
| gate | covers |
| --- | --- |
| `XUI_TEST_PG_DSN` | PostgreSQL-specific paths |
| `XUI_DB_TYPE` + `XUI_DB_DSN` | dialect-dependent behaviour |
| `XRAY_E2E_BINARY` | the Xray gRPC end-to-end tests in `internal/xray/` |
| `XRAY_E2E_BINARY` | the real-core tests: Xray gRPC API, hot apply, balancer overrides, the AmneziaWG relay |
| `XUI_SCALE_TEST` | scale tests in `internal/sub/`, `internal/web/job/`, `internal/web/service/` |
Mutation testing (`mutation.yml`) runs nightly and never on a pull request, so a
+92 -8
View File
@@ -92,6 +92,25 @@ jobs:
exit 1
fi
- name: PostgreSQL inbound add orphan cleanup
run: |
set -o pipefail
go test ./internal/web/service -run '^TestAddInboundClient(BoundedOrphanCleanup|OrphanProbePreservesConcurrentRecreation)Postgres$' -count=1 -v | tee /tmp/postgres-add-orphans.log
passed=$(grep -c -- '^--- PASS: TestAddInboundClient' /tmp/postgres-add-orphans.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected both PostgreSQL inbound add orphan cleanup tests to pass, got $passed" >&2
exit 1
fi
- name: PostgreSQL client traffic lifecycle edits
run: |
set -o pipefail
go test ./internal/web/service -run '^TestClientTrafficLifecyclePostgres$' -count=1 -v | tee /tmp/postgres-client-traffic-lifecycle.log
if ! grep -q -- '^--- PASS: TestClientTrafficLifecyclePostgres ' /tmp/postgres-client-traffic-lifecycle.log; then
echo "expected the PostgreSQL client traffic lifecycle suite to pass" >&2
exit 1
fi
- name: PostgreSQL batched stats identities
run: |
set -o pipefail
@@ -112,6 +131,16 @@ jobs:
exit 1
fi
- name: PostgreSQL Xray traffic retry
run: |
set -o pipefail
go test -p=1 ./internal/web/job ./internal/web/service -run '^TestXrayTraffic(PollRetriesRolledBackSample|BatchSurvivesFullQueueAndWriterRestart|BatchRetriesDeferredCommitFailure)Postgres$' -count=1 -v | tee /tmp/postgres-xray-traffic-retry.log
passed=$(grep -c -- '^--- PASS: TestXrayTraffic' /tmp/postgres-xray-traffic-retry.log || true)
if [ "$passed" -ne 3 ]; then
echo "expected 3 passing PostgreSQL Xray traffic retry tests, got $passed" >&2
exit 1
fi
- name: PostgreSQL global-traffic heartbeat regressions
run: |
set -o pipefail
@@ -122,25 +151,55 @@ jobs:
exit 1
fi
- name: PostgreSQL deferred-commit test
- name: PostgreSQL node client reconciliation rollback
run: |
set -o pipefail
go test ./internal/web/service/outbound -run '^TestAddTrafficReturnsDeferredCommitFailure$' -count=1 -v | tee /tmp/postgres-outbound.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-outbound.log || true)
if [ "$passed" -lt 1 ]; then
echo "expected at least 1 passing deferred-commit test, got $passed" >&2
go test ./internal/web/service -run '^TestNode(ClientReconcileRollback|RefusedFirstAdoptionKeepsNodeSettings)Postgres$' -count=1 -v | tee /tmp/postgres-node-client-rollback.log
passed=$(grep -c -- '^--- PASS: TestNode' /tmp/postgres-node-client-rollback.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected both PostgreSQL node client reconciliation rollback tests to pass, got $passed" >&2
exit 1
fi
- name: PostgreSQL client usage history
run: |
set -o pipefail
go test ./internal/web/service -run '^TestClientUsageHistoryPostgres$' -count=1 -v | tee /tmp/postgres-usage-history.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-usage-history.log || true)
if [ "$passed" -ne 1 ]; then
echo "expected 1 passing PostgreSQL client usage history test, got $passed" >&2
exit 1
fi
- name: PostgreSQL attach candidate selection
run: |
set -o pipefail
go test ./internal/web/service -run '^Test(AttachCandidatesSelection|FrozenAttachSelectionFollowsFilter)Postgres$' -count=1 -v | tee /tmp/postgres-attach-selection.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-attach-selection.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected 2 passing PostgreSQL attach selection tests, got $passed" >&2
exit 1
fi
- name: PostgreSQL depletion query regressions
run: |
set -o pipefail
go test ./internal/web/service -run '^TestDepletionQuery(Semantics|FreshnessAndReset|ConcurrentCommit|Renewals)$' -count=1 -v | tee /tmp/postgres-depletion-query.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-depletion-query.log || true)
if [ "$passed" -ne 4 ]; then
echo "expected 4 passing PostgreSQL depletion tests, got $passed" >&2
exit 1
fi
- name: PostgreSQL schema and migration tests
run: |
set -o pipefail
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence)$' -count=1 -v | tee /tmp/postgres-schema.log
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence|TestEnsureClientGroupRows_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log
# All must pass. Counting, not SKIP-matching: renaming a test would
# otherwise leave this step green while testing nothing.
passed=$(grep -c -- '^--- PASS' /tmp/postgres-schema.log || true)
if [ "$passed" -lt 6 ]; then
echo "expected at least 6 passing PostgreSQL schema tests, got $passed" >&2
if [ "$passed" -lt 7 ]; then
echo "expected at least 7 passing PostgreSQL schema tests, got $passed" >&2
exit 1
fi
@@ -280,6 +339,22 @@ jobs:
make node-e2e 2>&1 | tee /tmp/node-e2e.log
if grep -q -- '--- SKIP' /tmp/node-e2e.log; then echo "node-e2e skipped"; exit 1; fi
# The core pinned in go.mod as a real child process, driven over its gRPC API.
# A skip naming the binary means it was never handed over, so it fails the job.
xray-e2e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: Real core end to end
run: |
set -o pipefail
make xray-e2e 2>&1 | tee /tmp/xray-e2e.log
if grep -q -- '_test.go:[0-9]*: .*XRAY_E2E_BINARY' /tmp/xray-e2e.log; then echo "a real-core test skipped"; exit 1; fi
# Brief native-fuzz smoke on the security-/parser-critical decoders. Each runs the
# generated corpus plus 30s of exploration; a crash here is a real input-handling bug.
fuzz-smoke:
@@ -383,6 +458,15 @@ jobs:
- name: Build Storybook
run: npm run build-storybook
working-directory: frontend
- name: Inbound keyboard and accessibility tree
working-directory: frontend
run: |
set -euo pipefail
./node_modules/.bin/vite preview --outDir storybook-static --host 127.0.0.1 --port 6006 > /tmp/inbound-preview.log 2>&1 &
preview_pid=$!
trap 'kill "$preview_pid" 2>/dev/null || true' EXIT
curl --retry 30 --retry-connrefused --retry-delay 1 --retry-max-time 45 -fsS http://127.0.0.1:6006/iframe.html > /dev/null
node tools/check-inbound-keyboard.mjs http://127.0.0.1:6006
- name: Audit
run: npm run audit
working-directory: frontend
+3
View File
@@ -143,6 +143,9 @@ jobs:
# Only a fork author lacks write access; an `@claude review` requester passes
# the action's own check, so the bypass stays off for it.
allowed_non_write_users: ${{ github.event_name == 'pull_request_target' && '*' || '' }}
# Since v1.0.288 the action skips fork pull requests unless told otherwise; the
# head is only ever read from pr-head/ at the pinned SHA, with a read-only token.
allow_fork_prs: "true"
# Claude Code loads a CLAUDE.md or .claude/rules/ file the moment a file
# beside it is read, so a fork's copy under pr-head/ would brief its own review.
settings: '{"claudeMdExcludes": ["**/pr-head/**"]}'
+2
View File
@@ -7,12 +7,14 @@ on:
- 'docs/**'
- 'frontend/public/openapi.json'
- 'frontend/src/pages/api-docs/endpoints.ts'
- 'internal/sub/default.json'
- '.github/workflows/docs-ci.yml'
pull_request:
paths:
- 'docs/**'
- 'frontend/public/openapi.json'
- 'frontend/src/pages/api-docs/endpoints.ts'
- 'internal/sub/default.json'
- '.github/workflows/docs-ci.yml'
permissions:
+2 -2
View File
@@ -115,7 +115,7 @@ jobs:
cd x-ui/bin
# Download dependencies
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.10.31/"
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.11.9/"
if [ "${{ matrix.platform }}" == "amd64" ]; then
fetch ${Xray_URL}Xray-linux-64.zip
unzip Xray-linux-64.zip
@@ -283,7 +283,7 @@ jobs:
cd x-ui\bin
# Download Xray for Windows
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.10.31/"
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.11.9/"
Invoke-WebRequest @retry -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip"
Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath .
Remove-Item "Xray-windows-64.zip"
+1 -1
View File
@@ -20,7 +20,7 @@ bin/
x-ui/
dist/
release/
node_modules/
node_modules
# Ignore compiled binaries
main
+1 -1
View File
@@ -4,7 +4,7 @@
FROM node:26-trixie-slim AS node
FROM golang:1.27.3-trixie
FROM golang:1.27.4-trixie
ENV DEBIAN_FRONTEND=noninteractive \
CGO_ENABLED=1 \
+11 -3
View File
@@ -63,6 +63,12 @@ file locations when it can answer in one hop.
CPU/memory watchdogs, …); full table in `docs/architecture.md` §5.4.
- `middleware/`, `entity/`, `global/`, `session/` (CSRF), `network/`,
`runtime/` (master/sub-node over mTLS), `websocket/`.
- `mcp/` — MCP server at `POST /panel/api/mcp` (official go-sdk, stateless).
Tools never call services: each re-enters the router via `dispatcher.call`
with the caller's credentials, so auth, scopes and `runtime.Runtime` apply.
One file per toolset (`tools_<set>.go`, `?toolsets=` filter); every tool
needs a `toolCase`, or `TestToolsHitDocumentedRoutes` fails. Niche routes
stay reachable through `call_api` instead of getting their own tool.
- `locale/` + `translation/` — i18n, 14 embedded locale JSON files.
- `frontend/` — React + TS source (see `frontend/CLAUDE.md`).
- `tools/openapigen/` — Go generator that emits frontend types + Zod/JSON schemas
@@ -194,9 +200,11 @@ reads as a broken repo, not a missing step. Run `make dist-stub` once; every
That is the *fast* gate, not all of CI. `ci.yml` also runs `make race`,
`make vulncheck`, a live-Postgres job (where a SKIP counts as a failure),
`make node-e2e` (a real master and node panel, `internal/nodee2e/`) and a
30s fuzz smoke on `FuzzParseLink`/`FuzzDecodeCertPin` — run those locally when
you touch DB/dialect, node sync or parser code. Node sync has two layers: every
`make node-e2e` (a real master and node panel, `internal/nodee2e/`),
`make xray-e2e` (the `XRAY_E2E_BINARY` tests against the core pinned in `go.mod`,
run as a real child process) and a 30s fuzz smoke on
`FuzzParseLink`/`FuzzDecodeCertPin` — run those locally when you touch
DB/dialect, node sync, the Xray gRPC API or hot apply, or parser code. Node sync has two layers: every
`runtime.Remote` call gets a cell in `internal/web/node_contract_test.go` (fast,
in `make test-go`; a method without one fails it), and a multi-tick flow (cron,
adopt, node down) gets one in `internal/nodee2e/node_sync_test.go`.
+1 -1
View File
@@ -52,7 +52,7 @@ if [ -z "$MTG_MULTI_VER" ]; then
fi
mkdir -p build/bin
cd build/bin
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.10.31/Xray-linux-${XRAY_ZIP}.zip"
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.11.9/Xray-linux-${XRAY_ZIP}.zip"
unzip "Xray-linux-${XRAY_ZIP}.zip"
rm -f "Xray-linux-${XRAY_ZIP}.zip" geoip.dat geosite.dat
mv xray "${XRAY_BIN}"
+8
View File
@@ -65,6 +65,14 @@ node-e2e: dist-stub ## Master+node sync end to end with two real panel processes
go build -o $(NODE_E2E_BIN) .
XUI_NODE_E2E_BINARY=$(NODE_E2E_BIN) go test -count=1 -timeout 20m -v ./internal/nodee2e/
.PHONY: xray-e2e
# The core pinned in go.mod as a real child process; test-go only runs these as skips.
XRAY_E2E_BIN = $(CURDIR)/.cache/xray-e2e/xray$(shell go env GOEXE)
XRAY_E2E_PKGS = $(shell grep -rl --include='*_test.go' 'Getenv("XRAY_E2E_BINARY")' internal | xargs -n1 dirname | sort -u | sed 's|^|./|')
xray-e2e: dist-stub ## Real-core tests against the xray-core pinned in go.mod
go build -o $(XRAY_E2E_BIN) github.com/xtls/xray-core/main
XRAY_E2E_BINARY=$(XRAY_E2E_BIN) go test -count=1 -timeout 20m -v $(XRAY_E2E_PKGS)
.PHONY: test-fe
test-fe: ## Frontend tests (vitest)
cd $(FRONTEND) && npm test
+1
View File
@@ -200,6 +200,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (الترخيص: **MIT**): _إدارة الاتصالات الواردة والعملاء وإعدادات اللوحة وتكوين Xray كرمز باستخدام Terraform / OpenTofu._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (الترخيص: **MIT**): _عميل أندرويد أصلي لـ 3x-ui — لوحة التحكم، الاتصالات الواردة، العملاء مع مشاركة رمز QR، العقد وإدارة عدة لوحات. متاح على F-Droid._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (الترخيص: **MIT**): _مُصدِّر Prometheus خفيف ولوحة Grafana لـ 3x-ui و Xray Core — معدل نقل البيانات في الوقت الفعلي، العملاء النشطون، المقابس المفتوحة، الموازِنات وحالة زمن الاستجابة._
## دعم المشروع
+1
View File
@@ -200,6 +200,7 @@ Herramientas e integraciones construidas por la comunidad alrededor de 3x-ui.
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (Licencia: **MIT**): _Gestiona inbounds, clientes, configuración del panel y configuración de Xray como código con Terraform / OpenTofu._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (Licencia: **MIT**): _Cliente nativo de Android para 3x-ui — panel de control, inbounds, clientes con compartición por QR, nodos y gestión de múltiples paneles. Disponible en F-Droid._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (Licencia: **MIT**): _Exportador ligero de Prometheus y panel de Grafana para 3x-ui y Xray Core — tráfico en tiempo real, clientes activos, sockets abiertos, balanceadores y estado de latencia._
## Apoyar el Proyecto
+1
View File
@@ -200,6 +200,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (مجوز: **MIT**): _مدیریت اینباندها، کلاینت‌ها، تنظیمات پنل و پیکربندی Xray به‌صورت کد با Terraform / OpenTofu._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (مجوز: **MIT**): _کلاینت بومی اندروید برای 3x-ui — داشبورد، اینباندها، کلاینت‌ها با اشتراک‌گذاری QR، نودها و مدیریت چند پنل. در F-Droid در دسترس است._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (مجوز: **MIT**): _اکسپورتر سبک Prometheus و داشبورد Grafana برای 3x-ui و Xray Core — نرخ ترافیک لحظه‌ای، کلاینت‌های فعال، سوکت‌های باز، بالانسرها و وضعیت تأخیر._
## پشتیبانی از پروژه
+1
View File
@@ -200,6 +200,7 @@ Tools and integrations built by the community around 3x-ui.
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (License: **MIT**): _Manage inbounds, clients, panel settings, and Xray configuration as code with Terraform / OpenTofu._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (License: **MIT**): _Native Android client for 3x-ui — dashboard, inbounds, clients with QR sharing, nodes and multi-panel management. Available on F-Droid._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (License: **MIT**): _Lightweight Prometheus exporter and Grafana dashboard for 3x-ui and Xray Core — real-time traffic throughput, active clients, open sockets, balancers, and latency health._
## Support project
+1
View File
@@ -200,6 +200,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (Лицензия: **MIT**): _Управление входящими, клиентами, настройками панели и конфигурацией Xray через код с помощью Terraform / OpenTofu._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (Лицензия: **MIT**): _Нативный Android-клиент для 3x-ui — дашборд, входящие, клиенты с QR, узлы и управление несколькими панелями. Доступен в F-Droid._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (Лицензия: **MIT**): _Лёгкий экспортер Prometheus и дашборд Grafana для 3x-ui и Xray Core — трафик в реальном времени, активные клиенты, открытые сокеты, балансировщики и состояние задержек._
## Поддержка проекта
+1
View File
@@ -200,6 +200,7 @@ Katkılarınızı her zaman bekliyoruz. Bir sorun (issue) açmadan veya pull req
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (Lisans: **MIT**): _Gelen bağlantılarnı, kullanıcıları, panel ayarlarını ve Xray yapılandırmasını Terraform / OpenTofu ile kod olarak (as code) yönetin._
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (Lisans: **MIT**): _3x-ui için yerel Android istemcisi — kontrol paneli, gelen bağlantılar, QR ile paylaşımlı kullanıcılar, düğümler ve çoklu panel yönetimi. F-Droid'de mevcut._
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (Lisans: **MIT**): _3x-ui ve Xray Core için hafif Prometheus dışa aktarıcısı ve Grafana panosu — gerçek zamanlı trafik hızı, aktif kullanıcılar, açık soketler, dengeleyiciler ve gecikme durumu._
## Projeyi Destekleyin
+1
View File
@@ -200,6 +200,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
- [terraform-provider-3x-ui](https://github.com/batonogov/terraform-provider-threexui) (许可证: **MIT**): _使用 Terraform / OpenTofu 通过代码管理入站、客户端、面板设置和 Xray 配置。_
- [3X-UI Manager](https://github.com/yukh975/3X-UI-Manager) (许可证: **MIT**): _3x-ui 的原生 Android 客户端 — 仪表板、入站、带二维码分享的客户端、节点以及多面板管理。可在 F-Droid 获取。_
- [3x-ui-exporter](https://github.com/nike38rus/3x-ui-exporter) (许可证: **MIT**): _适用于 3x-ui 和 Xray Core 的轻量级 Prometheus 导出器和 Grafana 仪表板 — 实时流量吞吐、活跃客户端、打开的套接字、负载均衡器和延迟健康状况。_
## 支持项目
+2 -1
View File
@@ -178,7 +178,8 @@ near-certain about and that actually breaks something:
- "CI passed" is a claim too, and needs the same evidence: say it only of a
run you actually read. A green one proves less here than it looks — only
`postgres-durable-first` runs against PostgreSQL, `go-test` and `race` are
SQLite, and `XRAY_E2E_BINARY` and `XUI_SCALE_TEST` are set by no job, so
SQLite, only `xray-e2e` starts the real core (the gRPC API and hot-apply
tests skip in every other job), and `XUI_SCALE_TEST` is set by no job, so
those tests have never run in CI at all. Where a change touches dialect,
migration or Xray gRPC code that no job exercised, say it is unverified
rather than repeating a green tick as proof.
+1
View File
@@ -418,6 +418,7 @@ All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` me
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
| `@every 10s` | `amneziawg_job` | Reconcile embedded AmneziaWG interfaces against enabled local inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@every 5m` | `reap_sync_orphans_job` | Delete sync-orphaned clients, then the history of emails no client holds |
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets |
+27
View File
@@ -164,6 +164,33 @@ after it is not charged. Interfaces and configs the panel cannot prove are its
own — a same-named link with a different key, or an unmarked, non-regular or
symlinked config file — are never changed or removed.
### Reboots and kernel module updates
The installer registers amneziawg in `/etc/modules-load.d/amneziawg.conf` so the
host loads it during boot. If you installed it with an older panel build and
kernel mode stops working after reboot, rerun the `install-awg-kernel` command
above using a build that includes boot registration.
Run these checks on the host to identify the installed and loaded module.
```sh
modinfo amneziawg
lsmod | grep '^amneziawg '
awg --version
```
`modinfo` looks up the module built for the running kernel. `lsmod` lists the
module only after the kernel has loaded it. The panel's systemd service cannot
load kernel modules itself, so kernel mode requires the host to load amneziawg
before the panel starts.
Use the same `install-awg-kernel` command to update the module and tools to the
versions pinned by your panel build. The installer prints the source tags.
`modinfo` reports the version declared by the compiled module, which can differ
from its source tag. An in-use module stays loaded during the install. Schedule
a maintenance reboot to load the updated module and allow for tunnel
interruption.
## Keepalive ranges
AmneziaWG clients accept `keepAlive` as a number or an ordered range from 0 to 65535, such as `15-25`. Omitted values keep the existing setting; explicit `0` disables keepalive. Native `.conf` files preserve ranges, while Clash/Mihomo scalar-only output uses the lower bound (`0-25` therefore disables keepalive). Plain WireGuard clients support only a scalar value. Upgrade sub-nodes before sending them range values because older nodes parse keepalive as an integer.
+26
View File
@@ -32,6 +32,32 @@ inbounds** at once, with per-client traffic accounting.
(`restartXrayOnClientDisable`, on by default).
</Callout>
## Block a subscription device
Open a client's **HWID Devices** list from the edit form or info card and select
**Block** beside the device. **Unblock** restores its access. Bans apply to that
subscription ID, including any clients sharing it, even when **HWID Limit** is
`0` (unlimited). They do not affect the same device on a different subscription.
![HWID device blocking](/images/hwid-device-blocking.png)
Example device list with one allowed device and one blocked device. The screenshot uses synthetic Storybook data.
Blocked devices are marked in red and do not consume device slots. Clearing
the list or reducing the device limit preserves bans. To remove a blocked
entry, unblock it first. Existing devices remain unblocked after upgrading.
A matching `X-HWID` receives HTTP `404` with `X-Hwid-Blocked: true` from the
Raw/Base64, JSON, Clash/Mihomo and legacy Clash subscription-body routes. Bans
depend on the HWID supplied by the app: a changed or omitted HWID cannot identify
the banned device. Previously downloaded configurations and copied credentials
are not revoked; apps can retain them after a failed subscription refresh.
The authenticated panel API uses
`POST /panel/api/clients/hwids/:email/:id/block` with JSON `{"blocked": true}`
to block, or `{"blocked": false}` to unblock. The device list includes a
`blocked` boolean for each entry. Missing or non-boolean values are rejected.
## Limits and IP control
- **Traffic / expiry** caps disable the client when hit; a **Reset** period
+6
View File
@@ -43,6 +43,12 @@ periodic **traffic reset** schedule: `never` (default), `hourly`, `daily`,
For `monthly` resets, select a day from 1 to 31. If the selected day does not
exist in a shorter month, the reset runs on that month's last day.
Enable **Keep client usage** to reset only the inbound's counters on its schedule.
Clients keep their accumulated usage until their own reset. With the switch off,
the schedule also resets the attached clients' usage, including their usage on
other inbounds. Upgrade the master and the nodes hosting the inbound before
enabling this option on a managed inbound.
</Step>
</Steps>
+1
View File
@@ -12,6 +12,7 @@
"transports",
"clients",
"subscription",
"routing-profiles",
"share-links"
]
}
+81
View File
@@ -49,6 +49,87 @@ can obtain a Let's Encrypt certificate for you — or terminate TLS at a
| `timeLocation` | `Local` | Time zone for stats and expiry. |
| `datepicker` | `gregorian` | Calendar for date inputs (Gregorian or Jalali/Persian). |
## Network traffic interface
In **Settings → General → Panel settings**, use **Network Traffic Interface**
to select the source of system traffic totals and throughput. It does not change
Xray client quotas, client billing counters, or inbound traffic accounting.
| Setting | Default | Meaning |
| --- | --- | --- |
| `networkTrafficMode` | `legacy` | `legacy`, `auto`, or `manual`. |
| `networkTrafficInterface` | _(empty)_ | Exact interface name used in manual mode, such as `eth0`, `ens3`, or `enP6129s1`. |
- **All interfaces (Legacy)** remains the default on new installations and upgrades.
It sums the same interfaces as before, excluding the existing loopback and virtual
interface prefixes. Stacked interfaces, such as Azure's synthetic interface and
its SR-IOV function, can represent the same traffic and be counted twice.
- **Automatic** reads Linux's main routing table through netlink without executing
shell commands or sending network probes. Among usable default routes, IPv4 is
preferred to IPv6. The lowest route metric wins within that family; equal metrics
use the interface name as a deterministic tie-breaker. IPv6-only systems use their
IPv6 default route. ECMP also selects a single usable next hop.
Only the selected interface is counted, including virtual
interfaces when the default route uses one. Policy-routing tables and
destination-specific route selection are outside this primary-route heuristic.
- **Manual** lists interfaces dynamically and counts only the exact selected name.
Explicit selections bypass the legacy virtual-interface exclusions. The backend
validates that a newly selected interface exists when settings are saved.
An unchanged saved selection may remain unavailable, so unrelated settings can
still be edited while the interface is absent.
![Manual network traffic interface selection](/images/network-traffic-interface.png)
![Automatic default-route interface resolution](/images/network-traffic-automatic.png)
These screenshots render the settings component locally with example interface names.
Automatic detection runs on each status collection, normally every two seconds,
so route changes take effect on the next sample. If detection fails, a selected
interface disappears, or counters cannot be read, the network metrics are marked
unavailable. The dashboard and bot reports show this state, and histories omit
unavailable samples. No other interface or aggregation mode is substituted.
When the interface returns, normal collection resumes automatically.
Speed and packet-rate calculations start from a new baseline after a mode change,
interface change, detected device recreation, counter decrease/reset, or a failed
sample. The first comparable sample resumes normal rates. Totals remain the
selected kernel counters, rather than monthly billing totals; existing history
can contain samples collected under previous interface selections.
Each panel, including a sub-node, selects interfaces in its own network namespace.
In a Docker bridge network these are container interfaces, not host-wide traffic.
Host interfaces are visible only when the deployment shares the host network
namespace. Reading interfaces, routes, and counters requires no `CAP_NET_ADMIN`,
firewall rules, nftables setup, Python process, or additional daemon. The existing
Docker capabilities needed by other features are unrelated to this setting.
Legacy and manual modes remain available on supported non-Linux platforms.
Automatic mode currently requires Linux; other platforms show an explicit
detection error and should use manual or legacy mode.
Settings persist in the existing key/value settings table; no schema migration is
needed. Database backups retain the selection. **Keep this machine's settings** on
import preserves the destination panel's selection, including a missing setting
that uses the legacy default. An imported manual interface that does not exist
is reported as unavailable rather than replaced.
Older settings API clients that omit the new fields preserve the current selection.
Send an explicit `networkTrafficMode: "legacy"` to restore legacy aggregation.
Authenticated administrators can list interfaces with
`GET /panel/api/server/networkInterfaces`. It uses the existing response envelope
and returns interface names/up state plus the automatic choice or detection error.
Status responses retain `netTraffic` and `netIO` and add `networkInterface`
(`mode`, `name`, `available`, `error`), together with the existing
`unavailableMetrics` list when collection fails. Older status responses without
this metadata remain compatible.
The default-route selection approach was inspired by
[IPv6Monitor](https://github.com/HamedSanaei/ipv6monitor). Its Python daemon,
database, and nftables accounting are not used. Separate IPv4/IPv6 traffic counters
are outside this feature's scope: the selected interface's counters include both.
## Security & authentication
Credentials, two-factor auth, the brute-force limiter, sessions, and LDAP are
@@ -0,0 +1,408 @@
---
title: Routing for Happ, Clash/Mihomo and Incy
description: How to write the JSON and YAML routing profiles served in subscriptions — the Happ format, Clash/Mihomo rules and the Incy profile — and how the panel accepts and validates them.
icon: GitBranch
---
The panel can hand clients a ready routing profile: which sites and IPs go
direct, which go through the proxy and which are blocked. The profile format
depends on the app:
| App | Profile format | Where to set it in the panel |
| ------------------ | ----------------------------------- | ------------------------------------------- |
| **Happ** | JSON (as a `happ://` link) | Subscription settings → **Happ** tab |
| **Clash / Mihomo** | YAML (rules, groups, providers) | **Clash / Mihomo** tab |
| **Incy** | JSON (as an `incy://` link) | **Incy** tab → **Routing** |
Each of the three fields accepts **either the profile itself** (inline) **or
one permanent HTTPS URL** to a file, for example a raw gist. A URL lets you
change the rules without opening the panel.
## How the panel handles a remote URL
In the Happ and Clash / Mihomo fields, a value that is a single `https://...`
line is treated as a remote source that the panel fetches itself:
- the panel downloads it **in the background** and caches it for 10 minutes; a
subscription request never waits for the source;
- the file is validated; if it is invalid the panel **keeps serving the last
working value** and logs a warning;
- only `https://` is allowed, with no credentials in the URL, and the host must
be public (local and internal addresses are blocked);
- redirects are followed (up to 5) but must stay on `https://`;
- limits: Clash 2 MiB; Happ 16 KiB for the download and 8 KiB for the value
after Base64 encoding, which is about 6 KiB of JSON; 6 second request timeout.
The Incy field is different: the panel never downloads an Incy URL. It only
checks that the URL is `https://` without credentials and hands it to the app,
which fetches and refreshes the profile itself (see the Incy section below).
Use the **raw** link (`gist.githubusercontent.com/.../raw/...`), not the gist
page.
---
## Happ
### Where to enter it
**Settings → Subscription → Happ → Routing & rules**:
1. turn on **Enable routing** (sends `Routing-Enable: true`);
2. put one of these in **Routing rules**:
- a ready `happ://routing/onadd/<base64>` link;
- a permanent HTTPS URL to **JSON** or to a file containing a `happ://` link;
- `happ://routing/off` to turn routing off on the client.
The panel sends the value to the client in the `Routing` header. If the HTTPS
file contains plain JSON, the panel converts it to
`happ://routing/onadd/<base64>` itself. The source may also answer with a
redirect to `happ://...`, which is accepted too (this is how services such as
routing.help publish a profile).
If the field is empty but the **JSON subscription routing profile**
(`subJsonRoutingRules`) is set, that profile is sent as the `Routing` header
automatically.
The fastest start is the **routing presets** (Iran Bypass, China Direct,
Global, LAN bypass, optionally with ad blocking) or the **visual rule
builder**, which loads the current profile and lets you edit the lists or the
full JSON.
### JSON format
A profile is one JSON object. Happ writes flag values as strings (`"true"`,
`"false"`) and lists as arrays of strings.
```json
{
"Name": "My Routing",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"RemoteDNSType": "DoH",
"RemoteDNSDomain": "https://cloudflare-dns.com/dns-query",
"RemoteDNSIP": "1.1.1.1",
"DomesticDNSType": "DoH",
"DomesticDNSDomain": "https://dns.alidns.com/dns-query",
"DomesticDNSIP": "223.5.5.5",
"DnsHosts": {
"cloudflare-dns.com": "1.1.1.1",
"dns.alidns.com": "223.5.5.5"
},
"DirectSites": ["geosite:private", "geosite:cn", "domain:example.cn"],
"DirectIp": ["geoip:cn", "geoip:private", "192.168.0.0/16"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch",
"FakeDNS": "false",
"UseChunkFiles": "true"
}
```
| Field | Type | Meaning |
| ----- | ---- | ------- |
| `Name` | string | Profile name shown in the app. |
| `GlobalProxy` | `"true"`/`"false"` | Global mode: anything not matched by a rule goes through the proxy. |
| `RouteOrder` | string | Group check order joined by dashes: `block-proxy-direct`, `block-direct-proxy`, … The **first** matching group wins. Allowed words: `block`, `proxy`, `direct`; repeats are ignored. |
| `DirectSites` / `ProxySites` / `BlockSites` | array of strings | Domains: direct / via proxy / blocked. |
| `DirectIp` / `ProxyIp` / `BlockIp` | array of strings | IPs and subnets, same three groups. |
| `RemoteDNSDomain`, `RemoteDNSIP`, `RemoteDNSType` | string | DNS for proxied traffic (`DoH` and an `https://.../dns-query` address). |
| `DomesticDNSDomain`, `DomesticDNSIP`, `DomesticDNSType` | string | DNS for the "direct" domains. |
| `DnsHosts` | object name → IP | Static records, so DoH hosts do not need DNS to resolve themselves. |
| `DomainStrategy` | string | Xray strategy: `AsIs`, `IPIfNonMatch`, `IPOnDemand`. |
| `FakeDNS`, `UseChunkFiles` | `"true"`/`"false"` | Happ extensions; the panel passes them to the client unchanged. |
Unknown fields are **not lost**: the panel and the editor keep them and pass
them to Happ.
### List entry syntax
Entries use Xray routing syntax:
| Entry | Matches |
| ----- | ------- |
| `geosite:category-ads-all` | A category from `geosite.dat`. |
| `geosite:private`, `geoip:private` | Local/private addresses. |
| `geoip:ir`, `geoip:cn` | A country from `geoip.dat`. |
| `domain:example.com` | The domain and all its subdomains. |
| `full:www.example.com` | Exactly this domain. |
| `keyword:ads` | Any domain containing the substring. |
| `regexp:\\.ru$` | A regular expression. |
| `10.0.0.0/8`, `1.2.3.4` | A CIDR subnet or a single IP. |
An entry without a prefix is a domain substring; write `domain:` for precision.
`geosite:`/`geoip:` categories must exist in the client's `.dat` files; the
panel sends them in the `Routing` header so Happ fetches the right geo files.
### Building a `happ://` link by hand
A link is the prefix plus the JSON in Base64 (UTF-8):
```text
happ://routing/onadd/<base64 of the JSON>
```
`onadd` adds the profile and activates it; `add` only adds it. The panel
accepts standard and URL-safe Base64, with or without `=`. From PowerShell:
```powershell
$json = Get-Content .\routing.json -Raw -Encoding UTF8
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
"happ://routing/onadd/$b64"
```
The final value must stay under 8 KiB and be a single line.
### What the panel does with this JSON in JSON subscriptions
For clients that read the config from the body of a JSON subscription, the
profile is **baked into** the `dns` and `routing` sections:
- group order comes from `RouteOrder`, default `block`, `direct`, `proxy`;
- empty lists are skipped and a final "everything else → `proxy`" rule is
always appended;
- `DomainStrategy` defaults to `IPIfNonMatch`;
- DNS: a domestic server (`DomesticDNS*`, default `https://77.88.8.8/dns-query`)
is added for `DirectSites`, everything else uses `RemoteDNS*` (default
`https://8.8.8.8/dns-query`); `DnsHosts` is copied to `dns.hosts`.
Types must be exact: string is a string, a list is an array of strings,
`DnsHosts` is a string → string object. Otherwise the profile is dropped, the
subscription is served with default routing and a warning is logged.
---
## Clash / Mihomo
### Where to enter it
**Settings → Subscription → Clash / Mihomo**:
1. turn on **Enable routing**;
2. fill in **Global routing rules**, either inline or with one HTTPS URL to YAML.
The rules apply to profiles at `subClashPath` and `/mihomo/<sub-id>`. The
`/clash-legacy/` endpoint (Clash for Windows) always serves a minimal profile
and **ignores** these settings.
### What the profile already contains
The panel builds the base itself:
```yaml
proxies: # all your nodes, named by their remarks
- { name: "node-1", type: vless, ... }
proxy-groups:
- name: PROXY # select: all nodes + DIRECT
type: select
proxies: [node-1, DIRECT]
rules:
- MATCH,PROXY
```
Point your rules at the **`PROXY`** group, at `DIRECT`, at `REJECT`, or at any
group you declare yourself.
### Option 1: inline value
Three accepted forms.
**A) Plain rule lines** (`#` comments allowed):
```text
# block ads
GEOSITE,category-ads-all,REJECT
DOMAIN-SUFFIX,example.com,DIRECT
GEOIP,RU,DIRECT,no-resolve
```
**B) A YAML list:**
```yaml
- GEOSITE,category-ads-all,REJECT
- DOMAIN-SUFFIX,example.com,DIRECT
- GEOIP,RU,DIRECT,no-resolve
```
**C) A YAML map.** The `rules` key is merged with the base rules; any other key
(`proxy-groups`, `rule-providers`, `dns`, `sniffer`, …) **replaces** the
profile's key of the same name entirely:
```yaml
proxy-groups:
- name: PROXY
type: select
proxies: [DIRECT] # careful: replaces the whole PROXY group
rule-providers:
ads:
type: http
behavior: domain
format: yaml
url: https://example.com/ads.yaml
path: ./ruleset/ads.yaml
interval: 86400
rules:
- RULE-SET,ads,REJECT
- GEOIP,RU,DIRECT
```
How rules are combined:
- if your rules contain **no** `MATCH`, they are placed **before** the base
`MATCH,PROXY`, so everything else goes through the proxy;
- if a `MATCH` is present, your list **completely replaces** the base rules.
Inline validation is light: the map contents are copied as-is, so a mistake in
a group name only shows up in the client.
### Option 2: HTTPS URL to YAML
Here the panel is stricter: it **validates** the file before using it. Only
three keys are taken from the document:
| Key | Effect |
| --- | ------ |
| `rules` | Rules, merged by the same logic as above. |
| `proxy-groups` | Groups: ones with the same name replace the base ones, other base groups are kept. |
| `rule-providers` | Rule providers. |
`dns` and `sniffer` are taken **only if** the **DNS from remote rules**
(`subClashRemoteDNS`) switch is on. Enable it only for a template you trust,
since it changes the client's DNS. All other keys (`proxies`, `proxy-providers`,
`port`, …) are ignored; the nodes always stay yours.
A working example file:
```yaml
proxy-groups:
- name: Streaming
type: select
proxies: [PROXY, DIRECT]
- name: Auto
type: url-test
url: https://www.gstatic.com/generate_204
interval: 300
proxies: [PROXY]
rule-providers:
ru-direct:
type: http
behavior: domain
format: yaml
url: https://example.com/ru-direct.yaml
path: ./ruleset/ru-direct.yaml
interval: 86400
rules:
- RULE-SET,ru-direct,DIRECT
- DOMAIN-SUFFIX,netflix.com,Streaming
- GEOIP,PRIVATE,DIRECT,no-resolve
- MATCH,PROXY
```
What is checked (a failing file is rejected and the previous working version
stays):
- the document is a YAML map with at least one of `rules`, `proxy-groups`,
`rule-providers`;
- every group is a map with non-empty `name` and `type`, and names are **unique**;
- groups **cannot** use `use:` (proxy providers are not supported);
- every entry in a group's `proxies:`, every rule target and a provider's
`proxy:` must point to a group declared in the same file, to `PROXY`, or to
the built-ins `DIRECT`, `REJECT`, `REJECT-DROP`, `REJECT-TINYGIF`, `PASS`,
`GLOBAL`. A remote file is checked on its own, so the name of one of your
nodes fails the check;
- `RULE-SET,<name>,<target>` needs a provider with that name in `rule-providers`;
- each rule is a non-empty string `TYPE,value,target`; the flags `no-resolve`
and `src` may follow the target;
- size limits: 2 MiB response, plus a bound on nesting and on the size after
YAML aliases are expanded.
Node names depend on client remarks, so the most reliable target is the
**`PROXY`** group, which contains all nodes.
---
## Incy
### Where to enter it
**Settings → Subscription → Incy → Routing**:
1. turn on **Enable routing**;
2. fill in **Routing rules**:
- a ready `incy://routing/onadd/<base64>` link, the same JSON as Happ's,
Base64-encoded;
- **or one HTTPS URL** to a JSON file. The panel turns it into
`incy://autorouting/onadd/<url>` and the app **refreshes the profile
itself**.
The Incy profile goes as a line in the **body** of the subscription (only when
the User-Agent is INCY). In that case the panel does not send the `Routing`
header to Incy, so it cannot override the profile from the body.
### JSON format
The Incy profile format matches Happ's — use the same fields (`Name`,
`RouteOrder`, `DirectSites`, `DirectIp`, `ProxySites`, `BlockSites`,
`DomainStrategy`, …, see the table above):
```json
{
"Name": "RU bypass",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"DirectSites": ["geosite:private", "domain:ru", "geosite:category-ru"],
"DirectIp": ["geoip:ru", "geoip:private"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch"
}
```
Encoded form: `incy://routing/onadd/<base64 of the JSON>` (encode as in the Happ
example).
> If the Incy field is empty, Incy receives the shared **JSON subscription**
> profile (`subJsonRoutingRules`). Incy does not read the Happ field.
### The other Incy tabs
The **App**, **Banners**, **Privacy** and **Network** tabs are not routing: they
set app-management headers (profile description, banner, hidden URL,
fragmentation, …) and are sent only when **Incy header auto-detection** is on.
---
## Which format to use
| You need | Do this |
| -------- | ------- |
| One rule set for Happ and Incy | One JSON: paste as `happ://...` in Happ and `incy://...` in Incy, or give both the same HTTPS URL to the JSON. |
| Rules for Clash/Mihomo | A separate YAML; JSON and YAML are not converted into each other. |
| Change rules without touching the panel | A permanent raw URL (gist, repository) in the relevant field. |
| Check the result | Request the subscription with a client User-Agent (`curl -A "Happ/1.0"`, `-A "INCY/1.0"`, `-A "clash.meta"`) and inspect the `Routing` header / response body. |
## Common problems
- **Rules not applied, log says "Remote happ routing refresh from … failed"**
(or `clash`; for the JSON-subscription profile it says "remote source
unavailable"). The URL has not
been fetched yet (the first fetch runs in the background; refresh the
subscription in a minute) or the source returned an invalid file.
- **File rejected for size.** Happ allows 8 KiB after Base64 encoding, about
6 KiB of JSON; move long lists into
`geosite`/`geoip` categories or, for Clash, into `rule-providers`.
- **`references unknown proxy or group` error.** A rule or group points to a
name that is not in the profile. Use `PROXY`, `DIRECT`, `REJECT`, or declare
the group in the same file.
- **A gist page URL does not work.** Use the `raw` URL.
- **Clash for Windows ignores the rules.** `/clash-legacy/` does not support
custom routing; use `/mihomo/`.
+20 -2
View File
@@ -23,6 +23,8 @@ panel's subscription settings:
| `subCertFile` / `subKeyFile` | _(none)_ | TLS cert + key — when set, the server serves **HTTPS**. |
| `subEncrypt` | `true` | Base64-encode the raw subscription body. |
| `subUpdates` | `12` | Suggested refresh interval (hours) sent to clients. |
| `subRateLimitEnable` | `false` | Limit how often one client address may fetch subscription URLs; over the limit the server answers `429` with `Retry-After`. |
| `subRateLimit` | `60` | Fetches allowed per client address and minute (1–1000) while the limit is on. Behind a reverse proxy, `trustedProxyCIDRs` decides which address counts as the client. |
A subscription URL looks like:
@@ -38,6 +40,22 @@ URLs and preview both bodies here:
<SubscriptionBuilder />
## Replacing nodes after an HWID rejection
In **Panel settings → Subscription**, enable **Replace configs when HWID is
rejected** (`subHwidRejectWithConfig`, off by default). When HWID is missing or
the device limit is reached, the server returns HTTP 200 with a non-working
node instead of 404. This supports raw/base64 links, Xray JSON, Clash/Mihomo,
legacy Clash, and automatic format detection. Compatible apps can accept the
update and replace previously downloaded nodes. With this option off, the
existing 404 response and HWID error headers are preserved.
Replacement requires the app to refresh and accept the subscription. It does
not revoke copied credentials or immediately terminate existing connections.
Deleting a device only frees its slot: it can register again if a slot is
available. To reject it after deletion, the remaining devices must fill the
configured limit.
## Output formats
The **format is chosen by path**, each with its own enable toggle:
@@ -69,8 +87,8 @@ If an administrator has already assigned `/mihomo/` or `/clash-legacy/` to a
different configurable subscription path, that existing path is preserved and
the conflicting alias is skipped with a warning at startup.
Automatic Clash format detection keeps the existing `(?i)(clash|mihomo)`
default matcher so existing subscription URLs continue returning YAML.
Automatic Clash format detection defaults to the `(?i)(clash|mihomo|rabbit-hole)`
matcher, so existing subscription URLs continue returning YAML.
It does not distinguish legacy clients from Mihomo-based clients; Clash for
Windows users must use `/clash-legacy/<sub-id>` for a compatible profile.
+7 -1
View File
@@ -107,6 +107,12 @@ Session-ID fields (`sessionIDPlacement`, `sessionIDKey`, `sessionIDTable`,
`sessionIDLength`) and the `scMin/MaxEachPostBytes` knobs are advanced; leave them
empty unless you're matching a specific upstream.
Enable **Use separate download** to send the client's download requests to a
second endpoint. Enter its address and port, then set the HTTP host, path, and
security settings to match that endpoint. Both routes must reach the same XHTTP
listener. On an inbound, the panel includes these settings in client subscriptions.
The switch is available in `auto`, `packet-up`, and `stream-up` modes.
### Hysteria — `hysteriaSettings`
Only valid when the protocol is **Hysteria2**.
@@ -137,7 +143,7 @@ enabled. The panel offers XDRIVE only for VLESS, refuses to save an inbound with
| `secrets` | — | Google Drive: ClientID, ClientSecret, RefreshToken — exactly three, in that order. Template: values read as `{secret0}`, `{secret1}`, …. S3: AccessKeyID, SecretAccessKey and an optional SessionToken. |
| `template` | — | Template service only: the storage API's `auth`, `put`, `get`, `list` and `delete` operations. |
| `s3` | — | S3 service only: `endpoint` (an http(s) URL), `region`, `bucket` and `pathStyle` (default `true`; `false` puts the bucket in the host name). `remoteFolder` is the object prefix. |
| tuning | core defaults | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). |
| tuning | core defaults | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). Google Drive defaults to `flushIntervalMs` 10, `maxPollIntervalMs` 200 and `concurrency` 64 (xray-core 26.11.9). |
The optional **Front address/port** (the stream-level `address`/`port`) is a domain
front the storage API is dialed through; TLS still names the API host. XDRIVE has
@@ -3,11 +3,13 @@
"icon": "ServerCog",
"pages": [
"reverse-proxy",
"system-monitoring",
"multi-node",
"outbounds-routing",
"backup-restore",
"telegram-bot",
"discord-bot",
"wechat-notifications",
"security"
]
}
+27 -1
View File
@@ -23,7 +23,7 @@ Provide the node's connection details:
| **Scheme** | `https` (default) or `http`. |
| **Address / Port**| The node panel's host and port. |
| **Base path** | The node's web base path. |
| **API token** | A Bearer token created on the node (not needed in mTLS mode). |
| **API token** | A Bearer token created on the node. Optional in mTLS mode, except for **Update panel** (needs `node-admin`). |
| **TLS verify** | `verify` (default), `skip`, `pin` (pin a cert SHA-256), or `mtls`. |
| **Inbound sync** | `all` inbounds, or `selected` by tag. |
| **Outbound tag** | Optionally reach the node **through** a named outbound (egress bridge).|
@@ -39,6 +39,24 @@ and emitting `node.up` / `node.down` events (see the
those as read-only **transitive** sub-nodes (Node 1 → Node 2 → Node 3).
</Callout>
### Restart a node
Open a directly configured node's action menu and choose **Restart Xray** or
**Restart Panel**, then confirm the node name. Restart Xray interrupts that
node's active Xray connections. Restart Panel restarts its panel and subscription
services after a three-second delay; the success message acknowledges the request,
and the node may be temporarily unavailable.
Restart actions are disabled for disabled nodes and read-only transitive nodes.
An enabled node can be contacted even when its last heartbeat says offline.
Connection and permission failures are reported without automatically retrying.
Xray restart supports the node's existing `node-sync`, `node-admin`, and `admin`
API tokens. Panel restart requires `node-admin` or `admin`; mTLS connections must
also present an explicit `node-admin` bearer token. Update older nodes before
using `node-admin` for panel restart. The master-side node actions retain the
normal Nodes API permissions.
### Mutual TLS (mTLS) between master and node
For the strongest trust, use `tlsVerifyMode = mtls` (requires `https`):
@@ -64,6 +82,14 @@ next restart.
Set the node's TLS verify mode to `mtls`. The master now presents a client
certificate instead of an API token.
<Callout type="warn">
A node reached over mTLS without a token only has the `node-sync` scope, which
cannot run **Update panel** (the node answers HTTP 403, "this API token is not
permitted to access this endpoint"). To update such a node from the master,
create an API token with the `node-admin` scope on the node and paste it into
the master's **API token** field for that node. Keep TLS verify on `mtls`.
</Callout>
</Step>
</Steps>
@@ -128,7 +128,8 @@ Imported outbounds get **stable tags**: the same server keeps the same tag acros
refreshes, so exact-tag routing/balancer selectors stay pinned — while
prefix/wildcard selectors (e.g. `hk-*`) automatically pick up new servers as the
pool changes. Supported link schemes: `vmess`, `vless`, `trojan`, `ss`,
`hysteria2` (`hy2`), and `wireguard` (`wg`). The panel refreshes enabled
`hysteria2` (`hy2`), `wireguard` (`wg`), and `vpn` (AmneziaWG, from a 3x-ui
panel or an AmneziaVPN app key). The panel refreshes enabled
subscriptions on a timer and reloads Xray when something changes.
## Routing rules
+4 -2
View File
@@ -21,8 +21,10 @@ See [First login](/docs/guide/first-login) for the full checklist.
Set an **IP limit** per client (see [Clients](/docs/config/clients)) to cap the
number of simultaneous source IPs. Enforcement is handled by **Fail2ban**, which
3x-ui installs and configures for you (enabled by default on script installs, and
on Docker via `XUI_ENABLE_FAIL2BAN=true`).
3x-ui installs and configures when you opt in. On a fresh native install,
answer **Yes** to enable enforcement, or set `XUI_ENABLE_FAIL2BAN=true` for
unattended and Docker installs. The native installer remembers your choice across
updates and reinstalls. Source IP tracking continues independently of enforcement.
Manage it from the `x-ui` menu (**22 — IP Limit Management**): install/configure,
change the ban duration (default **30 minutes**), ban/unban an IP, view ban logs,
@@ -0,0 +1,47 @@
---
title: System monitoring
description: Read the overview charts, choose a time window, and understand how 3x-ui stores system history.
icon: ChartNoAxesCombined
---
The overview page combines a current server snapshot with short time-series charts. It shows CPU, memory, swap, storage, network throughput, and open TCP/UDP connections. Open **System history** for additional metrics such as packets, disk I/O, load averages, and Xray online clients.
## Choose a chart window
Each overview chart has the same time-range selector in its upper-right corner. The default is **2m**. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. Changing any selector changes the window on every overview chart.
The number of chart points stays capped at 60. Short windows use finer samples; longer windows use averages. At **2m** the charts are live: every status poll, once every 2 seconds, adds a point. A longer window is read from the server's stored history and refreshed once per point, at most once a minute.
The **System history** dialog has per-metric tabs and longer windows: **2m**, **1h**, **3h**, **6h**, **12h**, **24h**, **2d**, and **7d**. It refreshes only the active metric, and slows its polling as the selected window grows.
## Metrics and scope
The overview charts show:
- CPU use, memory use, swap use, and disk use as percentages.
- Network upload and download throughput in bytes per second.
- Current TCP and UDP connection counts.
System history adds packet rates, disk read/write rates, Xray online clients, and the 1, 5, and 15 minute load averages. CPU and swap follow the panel's resource scope when it runs inside a container; unavailable scoped metrics are left empty instead of being filled with host values.
Chart summaries show the average and peak inside the selected window. For Persian labels, the text and numeric value are isolated separately so right-to-left text direction does not reorder the number or percent sign.
## Collection and retention
The panel samples server status every **2 seconds**. Each metric is written into three fixed-size rollup tiers:
| Resolution | Retained window | Use |
| --- | --- | --- |
| 2 seconds | 1 hour | Recent charts |
| 1 minute | 48 hours | Medium windows |
| 10 minutes | 7 days | Long history |
Samples are averaged as they move through each tier. A series retains about 5,700 points (roughly 90 KiB before serialization), regardless of uptime. The overview endpoint returns up to 60 points per metric in one response, avoiding a request for each individual chart.
System history is saved to `system_metrics.gob` in the panel's database directory once a minute and again during shutdown. It is restored at startup. A new installation begins collecting history when the panel starts; it cannot reconstruct metrics from before collection was enabled.
## API
For a window longer than **2m** the overview requests `GET /panel/api/server/overviewHistory/{bucket}`. `bucket` is the number of seconds one point covers: `5`, `30`, `60`, `360` and `720` give the 5 minute through 12 hour windows. The response contains up to 60 `{ "t": unixSeconds, "v": value }` points for each overview metric.
The system history dialog requests `GET /panel/api/server/history/{metric}/{bucket}` for the active metric. It uses the same `{t, v}` point format and supports the longer bucket values documented in the [Server API reference](/docs/reference/api/server).
@@ -6,7 +6,7 @@ icon: Send
3x-ui can drive a Telegram bot for monitoring, alerts, backups, and remote
management. Admins get full control; regular users (linked by Telegram ID) can
check their own usage and links.
check their own usage and fetch their links and setup guides.
<Callout type="info">
Looking for news and community support? Join the official Telegram channel
@@ -80,7 +80,9 @@ clients, "depleting soon", and a full **add-client** wizard. The admin's
**client card** carries the client's subscription link, individual links and QR
code, so a config can be handed to a client who cannot reach Telegram yet.
Regular users get buttons for their own usage, subscription links, individual
links, and QR codes.
links, QR codes, **Get one** (pick one link and get it alone, with its own QR
code), and a per-platform **Setup guide**. Every links page opens with the
config's expiry date and the traffic it has left.
## Reports & alerts
@@ -0,0 +1,62 @@
---
title: WeChat Notifications
description: Receive event alerts and scheduled reports through a WeCom group robot or a compatible WeChat webhook gateway.
icon: MessageCircle
---
WeChat is an independent, optional text-notification channel. It supports event alerts and scheduled status reports, with its own language, event selection, and CPU/memory thresholds. Existing notification channels retain their settings. WeChat notifications are disabled by default.
WeCom mode sends to an enterprise group robot. Personal WeChat requires a separately deployed bridge that implements the custom gateway protocol and has its own working WeChat connection. The panel does not include that bridge or provide a direct personal WeChat bot login.
## Setup
1. Open **Panel Settings → WeChat** and enable notifications.
2. Choose a delivery mode:
- **WeCom group robot**: add a message-push robot to your enterprise WeChat group and paste its HTTPS webhook URL. See the [official configuration guide](https://developer.work.weixin.qq.com/document/path/99110).
- **Custom webhook gateway**: enter your HTTPS receiver URL and, optionally, a Bearer token that the receiver verifies. A compatible gateway delivers messages to personal WeChat. This uses the protocol below; an arbitrary third-party push URL or a WeChat contact name is not a receiver.
3. Select the notification language. It is independent of the Telegram bot language.
4. Under **Notifications**, choose events and thresholds. A metric threshold of `0` disables that metric's alerts.
5. Optionally enable scheduled reports and choose a cron schedule. `@daily` uses the panel scheduler's time zone.
6. **Save**, then click **Send test notification**. The test uses saved settings and is disabled while the channel is off or any settings have unsaved changes.
URLs can contain robot credentials, so both the URL and token are redacted when settings are loaded. Leaving a secret blank retains its saved value; **Clear** followed by **Save** removes it. Disable the channel before clearing a required destination. Saving also updates report schedules and metric sampling without restarting the panel.
![WeChat notification settings with a saved custom gateway and redacted credentials](/images/wechat-settings.png)
## Alerts and reports
Event keys are `login.attempt`, `cpu.high`, `memory.high`, `xray.crash`, `node.down`, `node.up`, `outbound.down`, and `outbound.up`. The initial selection is login attempts and high CPU usage. Login notifications include the attempted username, client IP, outcome, and available failure reason, but not the password.
Repeated alerts for one event and source are limited to one successful send per minute. Failed and successful login outcomes have separate limits. A failed delivery does not consume the successful-send cooldown.
Reports summarize the host, panel and Xray versions, CPU, memory, disk, uptime, and inbound/client counts, including disabled, expired, and depleted entries. Reports also run when Xray is stopped. This channel has no remote commands or file-backup feature, and does not include subscription links or client configuration files in reports.
Traffic totals cover client statistics managed by this panel, deduplicated by client email. Used traffic is upload plus download. Remaining traffic sums each client's non-negative quota balance; when a runtime quota is unset, the client's configured quota is used. If there are no client statistics or any client has no configured quota, the remaining total reads **Quota not configured**. These values do not represent a VPS provider's billing allowance or traffic outside 3x-ui.
## Custom gateway protocol, version 1
The panel sends an HTTPS `POST` with `Content-Type: application/json` and, when configured, `Authorization: Bearer <your-token>`:
```json
{
"version": 1,
"id": "8f793626-a0e0-4a28-bddf-84c077a1bd21",
"type": "event",
"event": "cpu.high",
"hostname": "my-server",
"occurred_at": "2026-11-04T12:00:00Z",
"text": "3x-ui · my-server\nHigh CPU usage: 92.00%; threshold: 80%"
}
```
`type` is `event`, `report`, or `test`. For events, `event` is a selected event key; reports and tests use `report` and `test`. `occurred_at` preserves the event's occurrence time, falling back to send time only when no event time is available. `text` is plain UTF-8 text, at most 20,480 bytes.
The receiver should verify authentication and version, durably enqueue with a uniqueness constraint on `id`, and return `2xx` after accepting responsibility for delivery. This acknowledges the gateway's receipt, not necessarily delivery to the final WeChat user. The receiver handles final delivery and further retries.
Connection failures and `5xx` receive at most one retry with the **same ID and body**. Other rejected responses are not retried. Deduplicate by ID to handle lost acknowledgements. Each request has a 10-second timeout, responses are limited to 4 KiB, and redirects are refused. This contract has no dependency on a particular gateway service.
## WeCom and network requirements
WeCom mode requires the official `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...` endpoint and a successful `errcode: 0` response. Long text is split at UTF-8 boundaries into at most ten messages of 2,048 bytes, spaced at least 3.1 seconds apart. Requests are not automatically retried because the robot API has no ID-based deduplication for this channel.
Both modes use direct outbound HTTPS with certificate verification, independent of the panel outbound proxy. Custom receivers must resolve to public addresses. Private, loopback, link-local, and metadata-service addresses are blocked again at connection time. Provide a public HTTPS receiver when the final WeChat adapter runs on a private network.
+307 -74
View File
@@ -13,6 +13,13 @@ _openapi:
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
url: '#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write'
- depth: 2
title: List up to 100 clients for the inbound attachment picker. Counts
distinguish filtered rows and all eligible clients. A freeze request
returns only the eligible count, maximum ID and a scope token covering
the eligible IDs that match the given search and group for the chosen
source and targets.
url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets'
- depth: 2
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
@@ -28,6 +35,10 @@ _openapi:
title: Fetch one client by email, including the inbound IDs and external config
IDs it is attached to.
url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to'
- depth: 2
title: Fetch one client by email, including the inbound IDs and external config
IDs it is attached to.
url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1'
- depth: 2
title: Fetch clients by subscription ID.
url: '#fetch-clients-by-subscription-id'
@@ -44,14 +55,25 @@ _openapi:
title: Preview client auto-renewal dates without saving or resetting anything.
url: '#preview-client-auto-renewal-dates-without-saving-or-resetting-anything'
- depth: 2
title: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields
you want to keep (the server replaces the row, it does not patch).
url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch'
title: 'Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload: omitted fields keep their
current values, and an explicit zero, empty or null value clears a
field, except as noted below.'
url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below'
- depth: 2
title: 'Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload: omitted fields keep their
current values, and an explicit zero, empty or null value clears a
field, except as noted below.'
url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1'
- depth: 2
title: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed'
- depth: 2
title: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1'
- depth: 2
title: Attach an existing client to one or more additional inbounds. Body is
JSON.
@@ -67,6 +89,21 @@ _openapi:
emitted on future subscription fetches; credentials already imported by
an app remain valid until the external provider revokes them.
url: '#replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions-the-owning-clients-disabled-or-expired-state-also-stops-these-rows-from-being-emitted-on-future-subscription-fetches-credentials-already-imported-by-an-app-remain-valid-until-the-external-provider-revokes-them'
- depth: 2
title: List WireGuard devices and their per-inbound addresses.
url: '#list-wireguard-devices-and-their-per-inbound-addresses'
- depth: 2
title: Create a WireGuard device on every attached WireGuard inbound.
url: '#create-a-wireguard-device-on-every-attached-wireguard-inbound'
- depth: 2
title: Set the maximum number of WireGuard devices.
url: '#set-the-maximum-number-of-wireguard-devices'
- depth: 2
title: Rename or enable a WireGuard device.
url: '#rename-or-enable-a-wireguard-device'
- depth: 2
title: Delete an additional WireGuard device and release its address.
url: '#delete-an-additional-wireguard-device-and-release-its-address'
- depth: 2
title: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
@@ -118,9 +155,19 @@ _openapi:
"xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound
supports it (omit or "" to leave it unchanged). The optional limitHwid
sets maximum registered devices (0 = unlimited). The optional adTag sets
MTProto Telegram sponsor channel ("none" clears). Returns the adjusted
count and per-email skip reasons.'
url: '#shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-returns-the-adjusted-count-and-per-email-skip-reasons'
MTProto Telegram sponsor channel ("none" clears). Alternatively, send
externalLinks to append external share links and http(s) subscriptions
to each selected client in one transaction. This mode cannot be combined
with other adjustments. Existing entries, metadata, and ordering are
preserved. Duplicates match (kind, value) per client, including repeated
input rows; the first entry wins. Missing clients are not written and
appear in skipped. externalLinks.added counts inserted rows,
externalLinks.skipped counts duplicate rows across found clients,
externalLinks.errors counts missing clients, and adjusted counts clients
receiving at least one new row. Validation or database failure aborts
the whole append without writes. Repeating an append is idempotent and
does not restart Xray.'
url: '#shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray'
- depth: 2
title: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
@@ -166,9 +213,21 @@ _openapi:
keeps its identity (email/UUID/password/subId) and a shared traffic row;
all clients are added to a target inbound in a single AddInboundClient
call. Clients already present on a target are reported under skipped.
Returns per-email attached/skipped/errors lists and triggers a single
Xray restart if any target inbound was running.
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
Explicit email requests return per-email lists. Alternatively submit
selection with explicit clientIds or a frozen allMatching scopeToken
plus excludedClientIds and the search and group it was frozen under.
Scoped requests start a background job and return {jobId}. Poll GET
/bulkAttach/:id for counts or a stale-selection error. Newer IDs stay
outside the frozen scope. Changes to the frozen membership are rejected
before applying changes. Triggers a single Xray restart if any target
inbound was running.
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: Poll a scoped attachment job. The result contains counts per target
(attached, skipped, errors); an operation failure sets error instead.
Completed results are retained for up to 15 minutes in the running panel
process.
url: '#poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process'
- depth: 2
title: "Mirror of bulkAttach: detach many existing clients from many inbounds in
one call. For each email, intersects the client's current inbounds with
@@ -188,27 +247,36 @@ _openapi:
clients.
url: '#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients'
- depth: 2
title: List all client groups with their member counts. Merges persisted groups
(rows in client_groups, including empty placeholders) with the distinct
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: '#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
title: List all client groups with their member counts and the host groups bound
to each. Merges persisted groups (rows in client_groups, including empty
placeholders) with the distinct group_name values currently set on
clients. Sorted alphabetically (case-insensitive).
url: '#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
- depth: 2
title: Replace the host groups attached to a client group. Clients in this group
receive the bound host groups instead of the inbound default host pool;
other clients are unaffected. An empty array clears the bindings.
Returns the saved host group IDs.
url: '#replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids'
- depth: 2
title: Return just the email list of clients that currently belong to the given
group. Useful for fanning a single bulk action over an entire group
without round-tripping the full client list.
url: '#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list'
- depth: 2
title: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: '#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists'
title: Create a new group, optionally with host rules bound to it. The group
becomes selectable in client forms and the filter drawer even before any
client is added to it. Host group IDs are validated before the group is
created. Errors if a group with the same name already exists.
url: '#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists'
- depth: 2
title: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: '#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated'
title: Rename a group and optionally replace its host rules in one transaction.
The new name is applied to the client_groups row AND propagated to every
matching client (both clients.group_name and the client entry inside
every owning inbound's settings JSON). Omit hostGroupIds to leave the
bindings unchanged; send an empty array to clear them. Returns the
number of clients whose label was updated.
url: '#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated'
- depth: 2
title: Remove a group. Deletes the client_groups row and clears the group label
from every matching client (both clients.group_name and the inbound
@@ -241,17 +309,26 @@ _openapi:
title: Reset the recorded IP list for a client.
url: '#reset-the-recorded-ip-list-for-a-client'
- depth: 2
title: List registered HWID devices for a client with a short fingerprint. Full
hashes are not exposed.
url: '#list-registered-hwid-devices-for-a-client-with-a-short-fingerprint-full-hashes-are-not-exposed'
title: List registered HWID devices for a client with a short fingerprint and a
blocked flag. Bans are scoped to the subscription ID shared by the
client. Full hashes are not exposed.
url: '#list-registered-hwid-devices-for-a-client-with-a-short-fingerprint-and-a-blocked-flag-bans-are-scoped-to-the-subscription-id-shared-by-the-client-full-hashes-are-not-exposed'
- depth: 2
title: Clear all registered HWID devices for a client so new devices can
register again.
url: '#clear-all-registered-hwid-devices-for-a-client-so-new-devices-can-register-again'
title: Clear unblocked HWID registrations for a client so devices can register
again. Blocked devices and their bans are preserved.
url: '#clear-unblocked-hwid-registrations-for-a-client-so-devices-can-register-again-blocked-devices-and-their-bans-are-preserved'
- depth: 2
title: Remove a single registered HWID device by its id, freeing one slot under
the HWID limit.
url: '#remove-a-single-registered-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit'
title: Remove a single unblocked HWID device by its id, freeing one slot under
the HWID limit. A blocked device must be unblocked before it can be
removed.
url: '#remove-a-single-unblocked-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit-a-blocked-device-must-be-unblocked-before-it-can-be-removed'
- depth: 2
title: Block or unblock one device for the client subscription. Send an explicit
boolean blocked value. A ban denies subscription bodies for that HWID
even with limitHwid=0, does not consume a device slot, and survives
clearing devices or changing the limit. It does not revoke copied
credentials or identify requests with a different or missing HWID.
url: '#block-or-unblock-one-device-for-the-client-subscription-send-an-explicit-boolean-blocked-value-a-ban-denies-subscription-bodies-for-that-hwid-even-with-limithwid0-does-not-consume-a-device-slot-and-survives-clearing-devices-or-changing-the-limit-it-does-not-revoke-copied-credentials-or-identify-requests-with-a-different-or-missing-hwid'
- depth: 2
title: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
@@ -281,6 +358,23 @@ _openapi:
- depth: 2
title: Traffic counters for a client identified by email.
url: '#traffic-counters-for-a-client-identified-by-email'
- depth: 2
title: "Usage and change history for one client, behind the edit modal's history
button. lifetimeUp/lifetimeDown are every archived window plus the
client's live counters; currentUp/currentDown are the still-open window.
windows lists the closed cycles, newest first (reason: reset | renew |
earlier): one is archived whenever a traffic reset or an auto-renewal
zeroes the client's counters, the newest 100 are kept and older ones are
folded into a single earlier row, so the lifetime total does not change.
nodes is the per-node upload/download accumulated since the last reset.
changes is the metadata change log, newest first, capped at the newest
200 rows: one row per changed field (subId, expiry, dataLimit, enable,
limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a
rename; source is panel | tgbot | auto-renew. A renamed client keeps its
history under the new email. The history belongs to the client: once the
client is deleted, its history is removed within five minutes. Requires
an admin token or a panel login session."
url: '#usage-and-change-history-for-one-client-behind-the-edit-modals-history-button-lifetimeuplifetimedown-are-every-archived-window-plus-the-clients-live-counters-currentupcurrentdown-are-the-still-open-window-windows-lists-the-closed-cycles-newest-first-reason-reset--renew--earlier-one-is-archived-whenever-a-traffic-reset-or-an-auto-renewal-zeroes-the-clients-counters-the-newest-100-are-kept-and-older-ones-are-folded-into-a-single-earlier-row-so-the-lifetime-total-does-not-change-nodes-is-the-per-node-uploaddownload-accumulated-since-the-last-reset-changes-is-the-metadata-change-log-newest-first-capped-at-the-newest-200-rows-one-row-per-changed-field-subid-expiry-datalimit-enable-limitip-limithwid-adtag-group-renewalplan-and-a-name-row-for-a-rename-source-is-panel--tgbot--auto-renew-a-renamed-client-keeps-its-history-under-the-new-email-the-history-belongs-to-the-client-once-the-client-is-deleted-its-history-is-removed-within-five-minutes-requires-an-admin-token-or-a-panel-login-session'
- depth: 2
title: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
@@ -311,6 +405,12 @@ _openapi:
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
id: list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: List up to 100 clients for the inbound attachment picker. Counts
distinguish filtered rows and all eligible clients. A freeze request
returns only the eligible count, maximum ID and a scope token covering
the eligible IDs that match the given search and group for the chosen
source and targets.
id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
@@ -324,6 +424,9 @@ _openapi:
- content: Fetch one client by email, including the inbound IDs and external
config IDs it is attached to.
id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: Fetch one client by email, including the inbound IDs and external
config IDs it is attached to.
id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1
- content: Fetch clients by subscription ID.
id: fetch-clients-by-subscription-id
- content: Fetch clients by Telegram user ID. Returns an array since multiple
@@ -335,14 +438,22 @@ _openapi:
id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: Preview client auto-renewal dates without saving or resetting anything.
id: preview-client-auto-renewal-dates-without-saving-or-resetting-anything
- content: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of
fields you want to keep (the server replaces the row, it does not
patch).
id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
- content: 'Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload: omitted fields keep
their current values, and an explicit zero, empty or null value clears
a field, except as noted below.'
id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- content: 'Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload: omitted fields keep
their current values, and an explicit zero, empty or null value clears
a field, except as noted below.'
id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1
- content: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1
- content: Attach an existing client to one or more additional inbounds. Body is
JSON.
id: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
@@ -355,6 +466,16 @@ _openapi:
emitted on future subscription fetches; credentials already imported
by an app remain valid until the external provider revokes them.
id: replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions-the-owning-clients-disabled-or-expired-state-also-stops-these-rows-from-being-emitted-on-future-subscription-fetches-credentials-already-imported-by-an-app-remain-valid-until-the-external-provider-revokes-them
- content: List WireGuard devices and their per-inbound addresses.
id: list-wireguard-devices-and-their-per-inbound-addresses
- content: Create a WireGuard device on every attached WireGuard inbound.
id: create-a-wireguard-device-on-every-attached-wireguard-inbound
- content: Set the maximum number of WireGuard devices.
id: set-the-maximum-number-of-wireguard-devices
- content: Rename or enable a WireGuard device.
id: rename-or-enable-a-wireguard-device
- content: Delete an additional WireGuard device and release its address.
id: delete-an-additional-wireguard-device-and-release-its-address
- content: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
moved.
@@ -402,8 +523,19 @@ _openapi:
the inbound supports it (omit or "" to leave it unchanged). The
optional limitHwid sets maximum registered devices (0 = unlimited).
The optional adTag sets MTProto Telegram sponsor channel ("none"
clears). Returns the adjusted count and per-email skip reasons.'
id: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-returns-the-adjusted-count-and-per-email-skip-reasons
clears). Alternatively, send externalLinks to append external share
links and http(s) subscriptions to each selected client in one
transaction. This mode cannot be combined with other adjustments.
Existing entries, metadata, and ordering are preserved. Duplicates
match (kind, value) per client, including repeated input rows; the
first entry wins. Missing clients are not written and appear in
skipped. externalLinks.added counts inserted rows,
externalLinks.skipped counts duplicate rows across found clients,
externalLinks.errors counts missing clients, and adjusted counts
clients receiving at least one new row. Validation or database failure
aborts the whole append without writes. Repeating an append is
idempotent and does not restart Xray.'
id: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray
- content: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to add each user. Note that enabling
@@ -444,10 +576,20 @@ _openapi:
keeps its identity (email/UUID/password/subId) and a shared traffic
row; all clients are added to a target inbound in a single
AddInboundClient call. Clients already present on a target are
reported under skipped. Returns per-email attached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
reported under skipped. Explicit email requests return per-email
lists. Alternatively submit selection with explicit clientIds or a
frozen allMatching scopeToken plus excludedClientIds and the search
and group it was frozen under. Scoped requests start a background job
and return {jobId}. Poll GET /bulkAttach/:id for counts or a
stale-selection error. Newer IDs stay outside the frozen scope.
Changes to the frozen membership are rejected before applying changes.
Triggers a single Xray restart if any target inbound was running.
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: Poll a scoped attachment job. The result contains counts per target
(attached, skipped, errors); an operation failure sets error instead.
Completed results are retained for up to 15 minutes in the running
panel process.
id: poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process
- content: "Mirror of bulkAttach: detach many existing clients from many inbounds
in one call. For each email, intersects the client's current inbounds
with the requested set and detaches from those only; (email, inbound)
@@ -464,24 +606,32 @@ _openapi:
disabled by hand stays disabled. Returns the count of successfully
reset clients.
id: zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients
- content: List all client groups with their member counts. Merges persisted
groups (rows in client_groups, including empty placeholders) with the
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: List all client groups with their member counts and the host groups
bound to each. Merges persisted groups (rows in client_groups,
including empty placeholders) with the distinct group_name values
currently set on clients. Sorted alphabetically (case-insensitive).
id: list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: Replace the host groups attached to a client group. Clients in this
group receive the bound host groups instead of the inbound default
host pool; other clients are unaffected. An empty array clears the
bindings. Returns the saved host group IDs.
id: replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids
- content: Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
group without round-tripping the full client list.
id: return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
id: create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group. The new name is applied to the client_groups row AND
- content: Create a new group, optionally with host rules bound to it. The group
becomes selectable in client forms and the filter drawer even before
any client is added to it. Host group IDs are validated before the
group is created. Errors if a group with the same name already exists.
id: create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group and optionally replace its host rules in one
transaction. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
client entry inside every owning inbound's settings JSON). Omit
hostGroupIds to leave the bindings unchanged; send an empty array to
clear them. Returns the number of clients whose label was updated.
id: rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
inbound settings JSON). The clients themselves are NOT deleted — use
@@ -508,15 +658,24 @@ _openapi:
id: list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
- content: Reset the recorded IP list for a client.
id: reset-the-recorded-ip-list-for-a-client
- content: List registered HWID devices for a client with a short fingerprint.
Full hashes are not exposed.
id: list-registered-hwid-devices-for-a-client-with-a-short-fingerprint-full-hashes-are-not-exposed
- content: Clear all registered HWID devices for a client so new devices can
register again.
id: clear-all-registered-hwid-devices-for-a-client-so-new-devices-can-register-again
- content: Remove a single registered HWID device by its id, freeing one slot
under the HWID limit.
id: remove-a-single-registered-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit
- content: List registered HWID devices for a client with a short fingerprint and
a blocked flag. Bans are scoped to the subscription ID shared by the
client. Full hashes are not exposed.
id: list-registered-hwid-devices-for-a-client-with-a-short-fingerprint-and-a-blocked-flag-bans-are-scoped-to-the-subscription-id-shared-by-the-client-full-hashes-are-not-exposed
- content: Clear unblocked HWID registrations for a client so devices can register
again. Blocked devices and their bans are preserved.
id: clear-unblocked-hwid-registrations-for-a-client-so-devices-can-register-again-blocked-devices-and-their-bans-are-preserved
- content: Remove a single unblocked HWID device by its id, freeing one slot under
the HWID limit. A blocked device must be unblocked before it can be
removed.
id: remove-a-single-unblocked-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit-a-blocked-device-must-be-unblocked-before-it-can-be-removed
- content: Block or unblock one device for the client subscription. Send an
explicit boolean blocked value. A ban denies subscription bodies for
that HWID even with limitHwid=0, does not consume a device slot, and
survives clearing devices or changing the limit. It does not revoke
copied credentials or identify requests with a different or missing
HWID.
id: block-or-unblock-one-device-for-the-client-subscription-send-an-explicit-boolean-blocked-value-a-ban-denies-subscription-bodies-for-that-hwid-even-with-limithwid0-does-not-consume-a-device-slot-and-survives-clearing-devices-or-changing-the-limit-it-does-not-revoke-copied-credentials-or-identify-requests-with-a-different-or-missing-hwid
- content: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
id: list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
@@ -541,6 +700,23 @@ _openapi:
id: map-of-client-email--last-seen-unix-timestamp
- content: Traffic counters for a client identified by email.
id: traffic-counters-for-a-client-identified-by-email
- content: "Usage and change history for one client, behind the edit modal's
history button. lifetimeUp/lifetimeDown are every archived window plus
the client's live counters; currentUp/currentDown are the still-open
window. windows lists the closed cycles, newest first (reason: reset |
renew | earlier): one is archived whenever a traffic reset or an
auto-renewal zeroes the client's counters, the newest 100 are kept and
older ones are folded into a single earlier row, so the lifetime total
does not change. nodes is the per-node upload/download accumulated
since the last reset. changes is the metadata change log, newest
first, capped at the newest 200 rows: one row per changed field
(subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group,
renewalPlan) and a name row for a rename; source is panel | tgbot |
auto-renew. A renamed client keeps its history under the new email.
The history belongs to the client: once the client is deleted, its
history is removed within five minutes. Requires an admin token or a
panel login session."
id: usage-and-change-history-for-one-client-behind-the-edit-modals-history-button-lifetimeuplifetimedown-are-every-archived-window-plus-the-clients-live-counters-currentupcurrentdown-are-the-still-open-window-windows-lists-the-closed-cycles-newest-first-reason-reset--renew--earlier-one-is-archived-whenever-a-traffic-reset-or-an-auto-renewal-zeroes-the-clients-counters-the-newest-100-are-kept-and-older-ones-are-folded-into-a-single-earlier-row-so-the-lifetime-total-does-not-change-nodes-is-the-per-node-uploaddownload-accumulated-since-the-last-reset-changes-is-the-metadata-change-log-newest-first-capped-at-the-newest-200-rows-one-row-per-changed-field-subid-expiry-datalimit-enable-limitip-limithwid-adtag-group-renewalplan-and-a-name-row-for-a-rename-source-is-panel--tgbot--auto-renew-a-renamed-client-keeps-its-history-under-the-new-email-the-history-belongs-to-the-client-once-the-client-is-deleted-its-history-is-removed-within-five-minutes-requires-an-admin-token-or-a-panel-login-session
- content: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
result set as the configured subPath endpoint, but as a JSON array —
@@ -564,6 +740,9 @@ _openapi:
tunnel) contribute nothing.'
id: return-every-url-for-one-client-across-all-attached-inbounds-one-per-advertised-endpoint-the-managed-hosts-of-the-inbound-else-its-streamsettingsexternalproxy-entries-else-its-own-address-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-mtproto-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents:
- content: Query-parameter alias for the path endpoint. Use email=. or email=.. to
manage legacy reserved names without URL dot-segment normalization.
heading: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to-1
- content: Matches the exact subscription ID and orders results by client ID.
Returns an array of the same payloads as GET /clients/get/:email,
since multiple clients can share a subscription ID. Includes disabled,
@@ -572,11 +751,14 @@ _openapi:
email lookup. Requires an admin token or a panel login session.
heading: fetch-clients-by-subscription-id
- content: >-
Fields the server fills in when they are omitted — a valid value sent
by the caller is never overwritten. Re-adding an email that already
exists, with its stored `subId`, reuses the stored `id`, `password`,
`auth` and `secret` instead of minting new ones, so the identity stays
in sync across its inbounds.
Client email must not be exactly `.` or `..`. Existing reserved-name
clients can be read, renamed to a valid name, or deleted using the
query-parameter /get, /update and /del aliases. Fields the server
fills in when they are omitted — a valid value sent by the caller is
never overwritten. Re-adding an email that already exists, with its
stored `subId`, reuses the stored `id`, `password`, `auth` and
`secret` instead of minting new ones, so the identity stays in sync
across its inbounds.
- **VLESS / VMess** — `id`, a fresh UUID
@@ -641,7 +823,11 @@ _openapi:
preview is informational and does not reserve an allowance or
guarantee node availability.
heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything
- content: 'The inbounds are applied concurrently and independently: one that
- content: 'An omitted `flow` leaves every attached inbound on its own flow. Send
`"reverse": null` to remove the reverse tag. Credentials (`id`,
`password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG
`allowedIPs` are never cleared: an empty value keeps the stored one.
The inbounds are applied concurrently and independently: one that
fails no longer stops the others. Every inbound error names the
inbound it came from (`inbound 7: <message>`), and several failures
are reported together, one per line. So a `success:false` response can
@@ -649,7 +835,22 @@ _openapi:
record is written after the inbounds, so a failure there is reported
without an `inbound <id>:` prefix and leaves the inbound edits in
place.'
heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- content: 'Query-parameter alias for the path endpoint. Use email=. or email=..
to manage legacy reserved names without URL dot-segment normalization.
An omitted `flow` leaves every attached inbound on its own flow. Send
`"reverse": null` to remove the reverse tag. Credentials (`id`,
`password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG
`allowedIPs` are never cleared: an empty value keeps the stored one.
The inbounds are applied concurrently and independently: one that
fails no longer stops the others. Every inbound error names the
inbound it came from (`inbound 7: <message>`), and several failures
are reported together, one per line. So a `success:false` response can
still have applied the edit to the remaining inbounds. The client
record is written after the inbounds, so a failure there is reported
without an `inbound <id>:` prefix and leaves the inbound edits in
place.'
heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1
- content: 'The inbounds are applied concurrently and independently: one that
fails no longer stops the others. Every inbound error names the
inbound it came from (`inbound 7: <message>`), and several failures
@@ -660,6 +861,18 @@ _openapi:
inbounds, so a failure there is reported without an `inbound <id>:`
prefix and leaves the client already removed from every inbound.'
heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: 'Query-parameter alias for the path endpoint. Use email=. or email=..
to manage legacy reserved names without URL dot-segment normalization.
The inbounds are applied concurrently and independently: one that
fails no longer stops the others. Every inbound error names the
inbound it came from (`inbound 7: <message>`), and several failures
are reported together, one per line. So a `success:false` response can
still have removed the client from the remaining inbounds; the client
record is kept in that case, so re-running the call retries exactly
the leftovers. The record and traffic rows are dropped after the
inbounds, so a failure there is reported without an `inbound <id>:`
prefix and leaves the client already removed from every inbound.'
heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1
- content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound
instead of being given a fresh address, so the call fails with
`inbound <id>: wireguard: allowedIPs entry <entry> overlaps <address>
@@ -676,6 +889,26 @@ _openapi:
still have detached the remaining inbounds. Detach writes nothing
beyond the inbounds, so every error carries the prefix.'
heading: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client
- content: The original credentials remain the primary device. Additional devices
share their parent client email, traffic quota, expiry and enable
state. Keep each device configuration on one device. Device-specific
subscriptions use the existing subscription URL with the wgDevice
query parameter set to the device ID.
heading: list-wireguard-devices-and-their-per-inbound-addresses
- content: Keys are generated once and each inbound allocates an available tunnel
address. All inbounds commit together. The default limit is 5 devices
including primary.
heading: create-a-wireguard-device-on-every-attached-wireguard-inbound
- content: The limit includes primary and disabled devices. Choose 1 to 32. Values
below the current device count are rejected.
heading: set-the-maximum-number-of-wireguard-devices
- content: The primary device is managed through the parent client. Disabled
additional devices retain their reserved addresses.
heading: rename-or-enable-a-wireguard-device
- content: The device is removed from every attached WireGuard inbound. Its
previously downloaded configuration loses access after the
configuration is applied.
heading: delete-an-additional-wireguard-device-and-release-its-address
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
@@ -685,7 +918,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
</>
);
}
@@ -0,0 +1,39 @@
---
title: MCP
description: Model Context Protocol endpoint for AI agents (Claude, Cursor, VS
Code). Point an MCP client at this URL with an admin Bearer token; restricted
token scopes are refused.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: 'Stateless streamable-HTTP MCP endpoint (JSON-RPC 2.0). Exposes panel
tools for inbounds, clients, server, Xray, nodes, hosts and settings;
each tool call runs the matching /panel/api route with the caller’s
credentials. Off by default: answers 404 until the MCP server is enabled
under Settings → Security → API Token.'
url: '#stateless-streamable-http-mcp-endpoint-json-rpc-20-exposes-panel-tools-for-inbounds-clients-server-xray-nodes-hosts-and-settings-each-tool-call-runs-the-matching-panelapi-route-with-the-callers-credentials-off-by-default-answers-404-until-the-mcp-server-is-enabled-under-settings--security--api-token'
structuredData:
headings:
- content: 'Stateless streamable-HTTP MCP endpoint (JSON-RPC 2.0). Exposes panel
tools for inbounds, clients, server, Xray, nodes, hosts and settings;
each tool call runs the matching /panel/api route with the caller’s
credentials. Off by default: answers 404 until the MCP server is
enabled under Settings → Security → API Token.'
id: stateless-streamable-http-mcp-endpoint-json-rpc-20-exposes-panel-tools-for-inbounds-clients-server-xray-nodes-hosts-and-settings-each-tool-call-runs-the-matching-panelapi-route-with-the-callers-credentials-off-by-default-answers-404-until-the-mcp-server-is-enabled-under-settings--security--api-token
contents: []
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
export default function Layout(props) {
const { OpenAPIPage } = props.components ?? {};
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/mcp","method":"post"}]} showTitle />
</>
);
}
@@ -13,8 +13,10 @@
"subscription-server",
"subscription-balancers",
"hosts",
"reality-watch",
"nodes",
"backup",
"mcp",
"websocket"
]
}
+27 -1
View File
@@ -69,6 +69,20 @@ _openapi:
- depth: 2
title: Probe an existing node, updating its cached health state.
url: '#probe-an-existing-node-updating-its-cached-health-state'
- depth: 2
title: Restart Xray on one enabled, directly configured node. Active Xray
connections are interrupted. Uses the node runtime and accepts admin,
node-admin or node-sync credentials on the node. A stale heartbeat does
not prevent the request.
url: '#restart-xray-on-one-enabled-directly-configured-node-active-xray-connections-are-interrupted-uses-the-node-runtime-and-accepts-admin-node-admin-or-node-sync-credentials-on-the-node-a-stale-heartbeat-does-not-prevent-the-request'
- depth: 2
title: Request a restart of the panel and subscription services on one enabled,
directly configured node. Requires admin or node-admin credentials on
the node; mTLS requires an explicit node-admin bearer token. Success
acknowledges scheduling, before the three-second restart delay. A stale
heartbeat does not prevent the request. Older nodes may reject
node-admin access until upgraded.
url: '#request-a-restart-of-the-panel-and-subscription-services-on-one-enabled-directly-configured-node-requires-admin-or-node-admin-credentials-on-the-node-mtls-requires-an-explicit-node-admin-bearer-token-success-acknowledges-scheduling-before-the-three-second-restart-delay-a-stale-heartbeat-does-not-prevent-the-request-older-nodes-may-reject-node-admin-access-until-upgraded'
- depth: 2
title: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
@@ -130,6 +144,18 @@ _openapi:
id: use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
- content: Probe an existing node, updating its cached health state.
id: probe-an-existing-node-updating-its-cached-health-state
- content: Restart Xray on one enabled, directly configured node. Active Xray
connections are interrupted. Uses the node runtime and accepts admin,
node-admin or node-sync credentials on the node. A stale heartbeat
does not prevent the request.
id: restart-xray-on-one-enabled-directly-configured-node-active-xray-connections-are-interrupted-uses-the-node-runtime-and-accepts-admin-node-admin-or-node-sync-credentials-on-the-node-a-stale-heartbeat-does-not-prevent-the-request
- content: Request a restart of the panel and subscription services on one
enabled, directly configured node. Requires admin or node-admin
credentials on the node; mTLS requires an explicit node-admin bearer
token. Success acknowledges scheduling, before the three-second
restart delay. A stale heartbeat does not prevent the request. Older
nodes may reject node-admin access until upgraded.
id: request-a-restart-of-the-panel-and-subscription-services-on-one-enabled-directly-configured-node-requires-admin-or-node-admin-credentials-on-the-node-mtls-requires-an-explicit-node-admin-bearer-token-success-acknowledges-scheduling-before-the-three-second-restart-delay-a-stale-heartbeat-does-not-prevent-the-request-older-nodes-may-reject-node-admin-access-until-upgraded
- content: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
updated; offline/disabled ones are reported as skipped. Set "dev":
@@ -149,7 +175,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/restartXray/{id}","method":"post"},{"path":"/panel/api/nodes/restartPanel/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
</>
);
}
@@ -0,0 +1,68 @@
---
title: REALITY watch
description: Spare targets per REALITY inbound. Every 10 minutes the panel
checks each watched target from this server; after 3 failed checks in a row,
an inbound with auto switch on moves to the first spare that passes the same
check and a real REALITY connection through a throwaway Xray server and
client. Inbounds on nodes, and targets on this machine or the LAN (a bare
port, a unix socket, a private address), are not checked.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: 'Status of every watched inbound: current target, spares, last check and
the switch history.'
url: '#status-of-every-watched-inbound-current-target-spares-last-check-and-the-switch-history'
- depth: 2
title: Status of one REALITY inbound.
url: '#status-of-one-reality-inbound'
- depth: 2
title: Set the spare targets (host[:port], in order of preference, at most 10;
the current target is dropped) and whether a dead target is replaced
automatically.
url: '#set-the-spare-targets-hostport-in-order-of-preference-at-most-10-the-current-target-is-dropped-and-whether-a-dead-target-is-replaced-automatically'
- depth: 2
title: Move the inbound to this target now and return its new status. Refused
for a node inbound, or unless the target passes the server check and a
real REALITY connection. Only target and serverNames change, plus any
Hosts of this inbound that pin an old server name.
url: '#move-the-inbound-to-this-target-now-and-return-its-new-status-refused-for-a-node-inbound-or-unless-the-target-passes-the-server-check-and-a-real-reality-connection-only-target-and-servernames-change-plus-any-hosts-of-this-inbound-that-pin-an-old-server-name'
- depth: 2
title: Check a target from this server and through a real REALITY connection;
feasible is false with a reason when either fails.
url: '#check-a-target-from-this-server-and-through-a-real-reality-connection-feasible-is-false-with-a-reason-when-either-fails'
structuredData:
headings:
- content: 'Status of every watched inbound: current target, spares, last check
and the switch history.'
id: status-of-every-watched-inbound-current-target-spares-last-check-and-the-switch-history
- content: Status of one REALITY inbound.
id: status-of-one-reality-inbound
- content: Set the spare targets (host[:port], in order of preference, at most 10;
the current target is dropped) and whether a dead target is replaced
automatically.
id: set-the-spare-targets-hostport-in-order-of-preference-at-most-10-the-current-target-is-dropped-and-whether-a-dead-target-is-replaced-automatically
- content: Move the inbound to this target now and return its new status. Refused
for a node inbound, or unless the target passes the server check and a
real REALITY connection. Only target and serverNames change, plus any
Hosts of this inbound that pin an old server name.
id: move-the-inbound-to-this-target-now-and-return-its-new-status-refused-for-a-node-inbound-or-unless-the-target-passes-the-server-check-and-a-real-reality-connection-only-target-and-servernames-change-plus-any-hosts-of-this-inbound-that-pin-an-old-server-name
- content: Check a target from this server and through a real REALITY connection;
feasible is false with a reason when either fails.
id: check-a-target-from-this-server-and-through-a-real-reality-connection-feasible-is-false-with-a-reason-when-either-fails
contents: []
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
export default function Layout(props) {
const { OpenAPIPage } = props.components ?? {};
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/realityWatch/list","method":"get"},{"path":"/panel/api/realityWatch/status/{id}","method":"get"},{"path":"/panel/api/realityWatch/save/{id}","method":"post"},{"path":"/panel/api/realityWatch/switch/{id}","method":"post"},{"path":"/panel/api/realityWatch/test","method":"post"}]} showTitle />
</>
);
}
+33 -13
View File
@@ -23,23 +23,34 @@ _openapi:
panel uses it to gate the "IP Limit" field, since enforcement depends on
Fail2ban being installed.
url: '#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed'
- depth: 2
title: List network interface names and resolve the primary default-route
interface in this panel network namespace. Requires an admin session or
admin API token. No addresses or hardware identifiers are returned.
url: '#list-network-interface-names-and-resolve-the-primary-default-route-interface-in-this-panel-network-namespace-requires-an-admin-session-or-admin-api-token-no-addresses-or-hardware-identifiers-are-returned'
- depth: 2
title: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.'
url: '#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape'
- depth: 2
title: Aggregated time-series for one metric. Returns an array of {t, v} samples
covering the last ~6 hours.
url: '#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours'
title: Aggregated time-series for one system metric. Returns up to 60 {t, v}
samples; supported bucket sizes cover windows from 2 minutes up to 7
days.
url: '#aggregated-time-series-for-one-system-metric-returns-up-to-60-t-v-samples-supported-bucket-sizes-cover-windows-from-2-minutes-up-to-7-days'
- depth: 2
title: 'Aggregated history for all overview charts in one response: up to 60 {t,
v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown,
tcpCount and udpCount.'
url: '#aggregated-history-for-all-overview-charts-in-one-response-up-to-60-t-v-samples-for-each-of-cpu-mem-swap-diskusage-netup-netdown-tcpcount-and-udpcount'
- depth: 2
title: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
url: '#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured'
- depth: 2
title: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
url: '#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket'
title: Aggregated history for one Xray runtime metric. Returns up to 60 {t, v}
samples for bucket windows up to 7 days.
url: '#aggregated-history-for-one-xray-runtime-metric-returns-up-to-60-t-v-samples-for-bucket-windows-up-to-7-days'
- depth: 2
title: Latest snapshot from the Xray observatory — per-outbound latency, health
status, and last-probe time. Only populated when the Xray config has an
@@ -195,19 +206,28 @@ _openapi:
panel uses it to gate the "IP Limit" field, since enforcement depends
on Fail2ban being installed.
id: reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: List network interface names and resolve the primary default-route
interface in this panel network namespace. Requires an admin session
or admin API token. No addresses or hardware identifiers are returned.
id: list-network-interface-names-and-resolve-the-primary-default-route-interface-in-this-panel-network-namespace-requires-an-admin-session-or-admin-api-token-no-addresses-or-hardware-identifiers-are-returned
- content: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead —
same data with a uniform {t, v} shape.'
id: legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
- content: Aggregated time-series for one metric. Returns an array of {t, v}
samples covering the last ~6 hours.
id: aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
- content: Aggregated time-series for one system metric. Returns up to 60 {t, v}
samples; supported bucket sizes cover windows from 2 minutes up to 7
days.
id: aggregated-time-series-for-one-system-metric-returns-up-to-60-t-v-samples-supported-bucket-sizes-cover-windows-from-2-minutes-up-to-7-days
- content: 'Aggregated history for all overview charts in one response: up to 60
{t, v} samples for each of cpu, mem, swap, diskUsage, netUp, netDown,
tcpCount and udpCount.'
id: aggregated-history-for-all-overview-charts-in-one-response-up-to-60-t-v-samples-for-each-of-cpu-mem-swap-diskusage-netup-netdown-tcpcount-and-udpcount
- content: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
id: xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
- content: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
id: time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
- content: Aggregated history for one Xray runtime metric. Returns up to 60 {t, v}
samples for bucket windows up to 7 days.
id: aggregated-history-for-one-xray-runtime-metric-returns-up-to-60-t-v-samples-for-bucket-windows-up-to-7-days
- content: Latest snapshot from the Xray observatory — per-outbound latency,
health status, and last-probe time. Only populated when the Xray
config has an observatory configured.
@@ -325,7 +345,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/openapi.json","method":"get"},{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getUpdateStatus","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/amneziawglogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/scanRealityTarget","method":"post"},{"path":"/panel/api/server/scanRealityTargets","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/openapi.json","method":"get"},{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/networkInterfaces","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/overviewHistory/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getUpdateStatus","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/amneziawglogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/scanRealityTarget","method":"post"},{"path":"/panel/api/server/scanRealityTargets","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
</>
);
}
@@ -56,6 +56,11 @@ _openapi:
title: Test Discord bot connection by sending a test embed to the configured
channel.
url: '#test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel'
- depth: 2
title: Send a text test notification using the saved WeChat destination.
Supports WeCom group robots and compatible personal WeChat webhook
gateways. Requires WeChat notifications to be enabled.
url: '#send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled'
- depth: 2
title: Return the built-in default Xray JSON config template that ships with
this panel version.
@@ -100,10 +105,20 @@ _openapi:
- content: Test Discord bot connection by sending a test embed to the configured
channel.
id: test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel
- content: Send a text test notification using the saved WeChat destination.
Supports WeCom group robots and compatible personal WeChat webhook
gateways. Requires WeChat notifications to be enabled.
id: send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled
- content: Return the built-in default Xray JSON config template that ships with
this panel version.
id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
contents: []
contents:
- content: The answer names the listener that took the call (port, tls) and the
one the restarted panel opens (nextPort, nextTls), with XUI_PORT and
an unloadable certificate pair already applied. A client reaching the
panel through a proxy or a port mapping compares port and tls with the
address it used, and follows a change only where they match.
heading: restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
@@ -113,7 +128,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/factoryDefaults","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/validateRegex","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/tgBotCapabilities","method":"post"},{"path":"/panel/api/setting/testDiscord","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/factoryDefaults","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/validateRegex","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/tgBotCapabilities","method":"post"},{"path":"/panel/api/setting/testDiscord","method":"post"},{"path":"/panel/api/setting/testWechat","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
</>
);
}
@@ -10,8 +10,9 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: List all subscription balancers in sort order (sort_order asc, id asc).
url: '#list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc'
title: List all subscription balancers in sort order, with problems[]
advisories.
url: '#list-all-subscription-balancers-in-sort-order-with-problems-advisories'
- depth: 2
title: Create a subscription balancer. It appears in the JSON subscription of
every client that sits on at least one selected inbound.
@@ -30,8 +31,9 @@ _openapi:
url: '#delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete'
structuredData:
headings:
- content: List all subscription balancers in sort order (sort_order asc, id asc).
id: list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc
- content: List all subscription balancers in sort order, with problems[]
advisories.
id: list-all-subscription-balancers-in-sort-order-with-problems-advisories
- content: Create a subscription balancer. It appears in the JSON subscription of
every client that sits on at least one selected inbound.
id: create-a-subscription-balancer-it-appears-in-the-json-subscription-of-every-client-that-sits-on-at-least-one-selected-inbound
@@ -44,7 +46,14 @@ _openapi:
- content: Delete a balancer by id (POST alias of DELETE for clients that cannot
send DELETE).
id: delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete
contents: []
contents:
- content: 'Each balancer carries a problems[] array of diagnostic advisories:
unknown_inbound, disabled_inbound, json_incapable_protocol,
inbound_without_clients, hosts_excluded_from_json, no_members.
Advisories never change the emitted config — a balancer with no
resolvable member is still omitted from the JSON subscription.
sort_order asc, id asc.'
heading: list-all-subscription-balancers-in-sort-order-with-problems-advisories
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
+7 -1
View File
@@ -108,6 +108,12 @@ icon: Network
`sessionIDLength`) و کلیدهای `scMin/MaxEachPostBytes` پیشرفته‌اند؛ آن‌ها را خالی
بگذارید مگر آنکه با یک بالادست مشخص هماهنگ می‌شوید.
برای فرستادن درخواست‌های دانلود کلاینت به مقصدی جداگانه، **استفاده از مسیر دانلود جداگانه**
را فعال کنید. آدرس و پورت مقصد را وارد کنید و مقادیر `host` و `path` در HTTP و
تنظیمات امنیتی را مطابق آن مقصد تنظیم کنید. هر دو مسیر باید به یک شنوندهٔ XHTTP
برسند. اگر این گزینه را در اتصال ورودی فعال کنید، پنل این تنظیمات را در اشتراک
کلاینت‌ها قرار می‌دهد. این گزینه در حالت‌های `auto`، `packet-up` و `stream-up` در دسترس است.
### Hysteria — `hysteriaSettings`
تنها زمانی معتبر است که پروتکل **Hysteria2** باشد.
@@ -138,7 +144,7 @@ inbound به مقدار `decryption` نیاز دارد و outbound به `encrypt
| `secrets` | — | Google Drive: دقیقاً سه مقدار ClientID، ClientSecret و RefreshToken به همین ترتیب. Template: مقادیری که با `{secret0}`، `{secret1}`، … خوانده می‌شوند. S3: ‏AccessKeyID، SecretAccessKey و در صورت نیاز SessionToken. |
| `template` | — | فقط برای سرویس template: عملیات `auth`، `put`، `get`، `list` و `delete` در API ذخیره‌ساز. |
| `s3` | — | فقط برای سرویس s3: `endpoint` (یک URL از نوع http(s))، `region`، `bucket` و `pathStyle` (پیش‌فرض `true`؛ با `false` نام باکت در نام میزبان می‌آید). `remoteFolder` پیشوند اشیاء است. |
| تنظیمات دقیق | پیش‌فرض هسته | `segmentBytes` (512 KiB)، `flushIntervalMs` (20)، `pollIntervalMs`/`maxPollIntervalMs` (50/500)، `eagerWindowMs` (2000)، `holeTimeoutMs` (30000)، `sessionTtlSeconds` (300)، `concurrency` (8). |
| تنظیمات دقیق | پیش‌فرض هسته | `segmentBytes` (512 KiB)، `flushIntervalMs` (20)، `pollIntervalMs`/`maxPollIntervalMs` (50/500)، `eagerWindowMs` (2000)، `holeTimeoutMs` (30000)، `sessionTtlSeconds` (300)، `concurrency` (8). پیش‌فرض Google Drive: ‏`flushIntervalMs` برابر 10، `maxPollIntervalMs` برابر 200 و `concurrency` برابر 64 (xray-core 26.11.9). |
**آدرس/پورت Front** اختیاری (کلیدهای `address`/`port` در سطح stream) یک domain front
است که API ذخیره‌ساز از طریق آن وصل می‌شود؛ نام TLS همچنان میزبان API است. XDRIVE لایهٔ
@@ -3,6 +3,7 @@
"icon": "ServerCog",
"pages": [
"reverse-proxy",
"system-monitoring",
"multi-node",
"outbounds-routing",
"backup-restore",
@@ -20,7 +20,7 @@ icon: Boxes
| **Scheme** | `https` (پیش‌فرض) یا `http`. |
| **Address / Port**| میزبان و پورت پنل نود. |
| **Base path** | مسیر پایهٔ وب نود. |
| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS لازم نیست). |
| **API token** | یک توکن Bearer که روی نود ساخته می‌شود (در حالت mTLS اختیاری است، به‌جز **به‌روزرسانی پنل** که به توکن `node-admin` نیاز دارد). |
| **TLS verify** | `verify` (پیش‌فرض)، `skip`، `pin` (پین‌کردن SHA-256 گواهی) یا `mtls`. |
| **Inbound sync** | همهٔ inboundها (`all`) یا انتخاب‌شده (`selected`) بر اساس تگ. |
| **Outbound tag** | به‌اختیار از طریق یک outbound نام‌دار به نود برسید (پل خروجی). |
@@ -59,6 +59,14 @@ icon: Boxes
حالت TLS verify نود را روی `mtls` تنظیم کنید. اکنون مستر به‌جای یک توکن API یک
گواهی کلاینت ارائه می‌دهد.
<Callout type="warn">
نودی که بدون توکن و از طریق mTLS متصل شده فقط دامنهٔ `node-sync` را دارد و نمی‌تواند
**به‌روزرسانی پنل** را اجرا کند (نود پاسخ HTTP 403 با پیام
«this API token is not permitted to access this endpoint» می‌دهد). برای به‌روزرسانی
چنین نودی از مستر، روی نود یک توکن API با دامنهٔ `node-admin` بسازید و آن را در
فیلد **API token** همان نود در مستر وارد کنید. حالت TLS verify را روی `mtls` نگه دارید.
</Callout>
</Step>
</Steps>
@@ -129,7 +129,7 @@ Reset یا حذف، peer مربوط به WireGuard را در حساب PIA باط
حفظ می‌کند، بنابراین انتخاب‌گرهای مسیریابی/متعادل‌کننده مبتنی بر برچسب دقیق پایدار می‌مانند —
در حالی که انتخاب‌گرهای پیشوندی/wildcard (مثلاً `hk-*`) با تغییر مجموعه، به‌صورت خودکار سرورهای
جدید را در بر می‌گیرند. طرح‌های پیوند پشتیبانی‌شده: `vmess`، `vless`، `trojan`، `ss`،
`hysteria2` (`hy2`) و `wireguard` (`wg`). پنل اشتراک‌های فعال را روی یک زمان‌سنج تازه می‌کند و
`hysteria2` (`hy2`)، `wireguard` (`wg`) و `vpn` (AmneziaWG، از پنل 3x-ui یا کلید برنامه AmneziaVPN). پنل اشتراک‌های فعال را روی یک زمان‌سنج تازه می‌کند و
هنگام تغییر چیزی، Xray را بارگذاری مجدد می‌کند.
## قواعد مسیریابی
+1 -1
View File
@@ -17,7 +17,7 @@ icon: ShieldCheck
## Fail2ban و محدودیت‌های IP
برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینت‌ها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام می‌شود که 3x-ui آن را برای شما نصب و پیکربندی می‌کند (در نصب‌های اسکریپتی به‌طور پیش‌فرض فعال است و در Docker از طریق `XUI_ENABLE_FAIL2BAN=true`).
برای هر کلاینت یک **محدودیت IP** تنظیم کنید (به [کلاینت‌ها](/docs/config/clients) مراجعه کنید) تا تعداد IPهای مبدأ همزمان محدود شود. اعمال این محدودیت توسط **Fail2ban** انجام می‌شود که 3x-ui پس از موافقت شما آن را نصب و پیکربندی می‌کند. در نصب تازه با اسکریپت، برای فعال‌کردن اعمال محدودیت **Yes** را انتخاب کنید. در نصب خودکار و Docker، `XUI_ENABLE_FAIL2BAN=true` را تنظیم کنید. انتخاب شما در به‌روزرسانی و نصب مجدد حفظ می‌شود. ردیابی IP مبدأ مستقل از اعمال محدودیت ادامه دارد.
آن را از منوی `x-ui` مدیریت کنید (**۲۲ — IP Limit Management**): نصب/پیکربندی، تغییر مدت مسدودسازی (پیش‌فرض **۳۰ دقیقه**)، مسدودسازی/رفع مسدودی یک IP، مشاهده لاگ‌های مسدودسازی و بررسی وضعیت. در پشت صحنه:
@@ -0,0 +1,47 @@
---
title: پایش سیستم
description: نمودارهای نمای کلی، انتخاب بازهٔ زمانی و نحوهٔ نگهداری تاریخچهٔ سیستم در 3x-ui.
icon: ChartNoAxesCombined
---
صفحهٔ نمای کلی، وضعیت فعلی سرور را همراه نمودارهای زمانی نشان می‌دهد: پردازنده، حافظه، سوآپ، فضای ذخیره‌سازی، نرخ ترافیک شبکه و اتصال‌های TCP/UDP. برای شاخص‌های بیشتر مثل نرخ بسته‌ها، ورودی/خروجی دیسک، میانگین بار سیستم و کلاینت‌های آنلاین Xray، پنجرهٔ **تاریخچهٔ سیستم** را باز کنید.
## انتخاب بازهٔ نمودار
هر نمودار نمای کلی یک سلکت بازهٔ زمانی در گوشهٔ بالای سمت راست دارد. مقدار پیش‌فرض **2m** است. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. تغییر بازه در هر نمودار، بازهٔ همهٔ نمودارهای نمای کلی را تغییر می‌دهد.
تعداد نقطه‌های نمودار حداکثر ۶۰ نقطه است. بازه‌های کوتاه‌تر از نمونه‌های دقیق‌تر و بازه‌های بلندتر از میانگین نمونه‌ها استفاده می‌کنند. در بازهٔ **2m** نمودارها زنده‌اند: هر بار دریافت وضعیت، یعنی هر ۲ ثانیه، یک نقطه اضافه می‌کند. بازه‌های بلندتر از تاریخچهٔ ذخیره‌شده در سرور خوانده می‌شوند و به‌ازای هر نقطه یک بار، و حداکثر دقیقه‌ای یک بار، به‌روزرسانی می‌شوند.
پنجرهٔ **تاریخچهٔ سیستم** برای هر شاخص زبانه‌ای جدا دارد و بازه‌های بلندتر **2m**، **1h**، **3h**، **6h**، **12h**، **24h**، **2d** و **7d** را ارائه می‌کند. فقط شاخص فعال به‌روزرسانی می‌شود و با بزرگ‌تر شدن بازه، فاصلهٔ دریافت اطلاعات بیشتر می‌شود.
## شاخص‌ها و محدودهٔ منابع
نمودارهای نمای کلی این موارد را نشان می‌دهند:
- مصرف پردازنده، حافظه، سوآپ و دیسک به‌صورت درصد.
- نرخ ارسال و دریافت شبکه به بایت بر ثانیه.
- تعداد فعلی اتصال‌های TCP و UDP.
تاریخچهٔ سیستم نرخ بسته‌ها، نرخ خواندن/نوشتن دیسک، کلاینت‌های آنلاین Xray و میانگین بار ۱، ۵ و ۱۵ دقیقه را هم دارد. وقتی پنل داخل کانتینر اجرا می‌شود، مصرف پردازنده و سوآپ از محدودهٔ منابع همان کانتینر گرفته می‌شوند. اگر این شاخص‌ها در دسترس نباشند، نمودار خالی می‌ماند و از دادهٔ میزبان به‌جای آن‌ها استفاده نمی‌شود.
خلاصهٔ هر نمودار، میانگین و بیشینهٔ مقدار را در بازهٔ انتخاب‌شده نشان می‌دهد. برچسب و مقدار عددی فارسی جدا از هم نمایش داده می‌شوند تا جهت راست‌به‌چپ، ترتیب رقم‌ها و علامت درصد را جابه‌جا نکند.
## جمع‌آوری و نگهداری داده
پنل هر **۲ ثانیه** یک نمونه از وضعیت سرور می‌گیرد. هر شاخص در سه سطح تجمیع با اندازهٔ ثابت نگهداری می‌شود:
| دقت داده | مدت نگهداری | کاربرد |
| --- | --- | --- |
| ۲ ثانیه | ۱ ساعت | نمودارهای نزدیک به زمان حال |
| ۱ دقیقه | ۴۸ ساعت | بازه‌های میان‌مدت |
| ۱۰ دقیقه | ۷ روز | تاریخچهٔ بلندمدت |
هنگام انتقال داده به سطح بعدی، نمونه‌ها با هم میانگین‌گیری می‌شوند. هر شاخص حدود ۵٬۷۰۰ نقطه (نزدیک به ۹۰ کیلوبایت پیش از سریال‌سازی) نگه می‌دارد؛ بنابراین مصرف حافظه با زمان کارکرد سرور رشد نامحدود ندارد. یک درخواست، حداکثر ۶۰ نقطه از همهٔ شاخص‌های نمای کلی را می‌گیرد تا برای هر نمودار درخواست جداگانه ارسال نشود.
تاریخچهٔ سیستم هر دقیقه در فایل `system_metrics.gob` کنار داده‌های پایگاه‌دادهٔ پنل ذخیره می‌شود و هنگام خاموش شدن پنل نیز ذخیرهٔ نهایی انجام می‌شود. داده‌ها هنگام راه‌اندازی بعدی بازیابی می‌شوند. نصب تازه از زمان شروع پنل داده جمع می‌کند و نمی‌تواند شاخص‌های پیش از فعال شدن این جمع‌آوری را بازسازی کند.
## API
نمای کلی برای بازه‌های بلندتر از **2m** از `GET /panel/api/server/overviewHistory/{bucket}` استفاده می‌کند. مقدار `bucket` تعداد ثانیه‌هایی است که هر نقطه پوشش می‌دهد: مقادیر `5`، `30`، `60`، `360` و `720` بازه‌های ۵ دقیقه تا ۱۲ ساعت را می‌دهند. پاسخ برای هر شاخص نمای کلی حداکثر ۶۰ نقطه با قالب `{ "t": unixSeconds, "v": value }` دارد.
پنجرهٔ تاریخچهٔ سیستم برای شاخص فعال، `GET /panel/api/server/history/{metric}/{bucket}` را فراخوانی می‌کند. قالب هر نقطه همان `{t, v}` است؛ مقدارهای بزرگ‌تر `bucket` در [مرجع API سرور](/docs/reference/api/server) آمده‌اند.
@@ -6,7 +6,7 @@ icon: Send
3x-ui می‌تواند یک ربات Telegram را برای پایش، هشدار، پشتیبان‌گیری و مدیریت از راه دور
به کار گیرد. ادمین‌ها کنترل کامل دارند؛ کاربران عادی (که با Telegram ID پیوند خورده‌اند)
می‌توانند مصرف و لینک‌های خودشان را بررسی کنند.
می‌توانند مصرف خودشان را بررسی کنند و لینک‌ها و راهنمای نصب را بگیرند.
<Callout type="info">
دنبال اخبار و پشتیبانی انجمن هستید؟ به کانال رسمی Telegram یعنی
@@ -79,7 +79,9 @@ icon: Send
کلاینت‌های آنلاین، «به‌زودی تمام‌شونده» و یک جادوگر کامل **افزودن کلاینت** را در اختیار دارند.
کارت **کلاینت** در اختیار ادمین است و لینک اشتراک، لینک‌های منفرد و کد QR کلاینت را
نشان می‌دهد، تا کانفیگ را بتوان به کلاینتی که هنوز به Telegram دسترسی ندارد هم داد.
کاربران عادی دکمه‌هایی برای مصرف خودشان، لینک‌های اشتراک، لینک‌های منفرد و کدهای QR دارند.
کاربران عادی دکمه‌هایی برای مصرف خودشان، لینک‌های اشتراک، لینک‌های منفرد، کدهای QR،
**دریافت یکی** (انتخاب یک لینک و دریافت جداگانه‌ی آن همراه با کد QR خودش) و **راهنمای نصب**
برای هر پلتفرم دارند. هر صفحه‌ی لینک با تاریخ انقضای کانفیگ و ترافیک باقی‌مانده‌ی آن شروع می‌شود.
## گزارش‌ها و هشدارها
+14 -13
View File
@@ -44,10 +44,11 @@ _openapi:
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields
you want to keep (the server replaces the row, it does not patch).
inbound. Body is the JSON client payload: omitted fields keep their
current values, and an explicit zero, empty or null value clears a
field, except as noted below.
url: >-
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- depth: 2
title: >-
Delete a client by email. Removes it from every attached inbound and
@@ -215,7 +216,7 @@ _openapi:
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
@@ -229,7 +230,7 @@ _openapi:
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
@@ -237,7 +238,7 @@ _openapi:
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
@@ -358,11 +359,11 @@ _openapi:
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload — supply the full
set of fields you want to keep (the server replaces the row, it does
not patch).
attached inbound. Body is the JSON client payload: omitted fields keep
their current values, and an explicit zero, empty or null value clears
a field, except as noted below.
id: >-
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- content: >-
Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
@@ -513,7 +514,7 @@ _openapi:
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
@@ -525,14 +526,14 @@ _openapi:
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
+28
View File
@@ -33,6 +33,34 @@ icon: Users
(`restartXrayOnClientDisable`, включено по умолчанию).
</Callout>
## Блокировка устройства в подписке
Откройте список **HWID устройств** в форме редактирования или карточке клиента
и нажмите **Заблокировать** рядом с устройством. Кнопка **Разблокировать**
возвращает доступ. Бан действует для этого ID подписки, в том числе для клиентов
с тем же ID, даже при **лимите HWID** `0` (без ограничений). Другая подписка
того же устройства продолжает работать.
![HWID device blocking](/images/hwid-device-blocking.png)
Пример списка с разрешённым и заблокированным устройством. На скриншоте показаны тестовые данные Storybook.
Заблокированные устройства отмечены красным и не занимают слоты. Очистка списка
и уменьшение лимита сохраняют баны. Чтобы удалить заблокированную запись,
сначала разблокируйте её. После обновления существующие устройства не блокируются.
При совпадении `X-HWID` запрос тела подписки Raw/Base64, JSON, Clash/Mihomo
или legacy Clash получает HTTP `404` и заголовок `X-Hwid-Blocked: true`.
Блокировка зависит от HWID, который передаёт приложение: изменённый или
отсутствующий HWID не позволяет распознать заблокированное устройство.
Уже загруженные конфиги и скопированные ключи не отзываются: приложение может
сохранить их после неудачного обновления подписки.
Авторизованный API панели:
`POST /panel/api/clients/hwids/:email/:id/block`, JSON `{"blocked": true}`
для блокировки и `{"blocked": false}` для разблокировки. В списке устройств
добавлен флаг `blocked`. Отсутствующее или не булево значение отклоняется.
## Лимиты и контроль IP
- Ограничения по **трафику / сроку действия** отключают клиента при достижении;
+1
View File
@@ -11,6 +11,7 @@
"transports",
"clients",
"subscription",
"routing-profiles",
"share-links"
]
}
@@ -0,0 +1,411 @@
---
title: Маршрутизация для Happ, Clash/Mihomo и Incy
description: Как писать JSON и YAML профили маршрутизации для подписок — формат Happ, правила Clash/Mihomo и профиль Incy, плюс как панель их принимает и проверяет.
icon: GitBranch
---
Панель умеет отдавать клиентам готовый профиль маршрутизации: какие сайты и
IP идут напрямую, какие через прокси, а какие блокируются. Формат профиля
зависит от приложения:
| Приложение | Формат профиля | Где задаётся в панели |
| ----------------- | ------------------------------------ | ------------------------------------- |
| **Happ** | JSON (в виде `happ://` ссылки) | Настройки подписки → вкладка **Happ** |
| **Clash / Mihomo**| YAML (правила, группы, провайдеры) | Вкладка **Clash / Mihomo** |
| **Incy** | JSON (в виде `incy://` ссылки) | Вкладка **Incy** → **Маршрутизация** |
Во всех трёх полях можно указать **либо сам профиль** (inline), **либо одну
постоянную HTTPS‑ссылку** на файл — например, на raw‑gist. Ссылку удобно
использовать, чтобы менять правила, не заходя в панель.
## Как панель работает с удалённой ссылкой
В полях Happ и Clash / Mihomo значение из одной строки `https://...` считается
удалённым источником, который панель скачивает сама:
- панель скачивает файл **в фоне** и кэширует его на 10 минут; запрос подписки
никогда не ждёт источник;
- файл проверяется; если он невалиден, панель **продолжает отдавать последнее
рабочее значение** и пишет предупреждение в лог;
- допустим только `https://`, без логина/пароля в URL, адрес должен вести на
публичный хост (локальные и внутренние адреса блокируются);
- редиректы допускаются (до 5), но только на `https://`;
- лимиты: Clash — 2 МиБ; Happ — 16 КиБ ответа и 8 КиБ значения после
кодирования в Base64 (около 6 КиБ JSON); таймаут запроса 6 секунд.
Поле Incy работает иначе: панель никогда не скачивает ссылку Incy. Она только
проверяет, что это `https://` без логина/пароля, и передаёт ссылку приложению,
которое само загружает и обновляет профиль (см. раздел про Incy ниже).
Совет: используйте **raw**‑ссылку (`gist.githubusercontent.com/.../raw/...`),
а не страницу gist.
---
## Happ
### Где вводить
**Настройки → Подписка → Happ → Маршрутизация и правила**:
1. включите **Включить маршрутизацию** (заголовок `Routing-Enable: true`);
2. вставьте в поле **Правила маршрутизации** одно из:
- готовую ссылку `happ://routing/onadd/<base64>`;
- постоянную HTTPS‑ссылку на **JSON** или на файл с `happ://` ссылкой;
- `happ://routing/off` — чтобы отключить маршрутизацию на клиенте.
Панель отправляет значение клиенту в заголовке `Routing`. Если в файле по
HTTPS лежит обычный JSON, панель сама превращает его в
`happ://routing/onadd/<base64>`. Источник может также отвечать редиректом
на `happ://...` — это тоже принимается (так работают сервисы вроде
routing.help).
Если поле пустое, но заполнен **профиль маршрутизации JSON‑подписки**
(`subJsonRoutingRules`), то он же автоматически уходит в заголовок `Routing`.
Быстрее всего начать с **Пресетов маршрутизации** (Iran Bypass, China Direct,
Global, LAN bypass; опционально с блокировкой рекламы) или с
**Визуального конструктора правил** — он загружает текущий профиль и позволяет
править списки или весь JSON.
### Формат JSON
Профиль — это один JSON‑объект. Значения‑флаги Happ записывает строками
(`"true"`, `"false"`), а списки — массивами строк.
```json
{
"Name": "My Routing",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"RemoteDNSType": "DoH",
"RemoteDNSDomain": "https://cloudflare-dns.com/dns-query",
"RemoteDNSIP": "1.1.1.1",
"DomesticDNSType": "DoH",
"DomesticDNSDomain": "https://dns.alidns.com/dns-query",
"DomesticDNSIP": "223.5.5.5",
"DnsHosts": {
"cloudflare-dns.com": "1.1.1.1",
"dns.alidns.com": "223.5.5.5"
},
"DirectSites": ["geosite:private", "geosite:cn", "domain:example.cn"],
"DirectIp": ["geoip:cn", "geoip:private", "192.168.0.0/16"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch",
"FakeDNS": "false",
"UseChunkFiles": "true"
}
```
| Поле | Тип | Смысл |
| ---- | --- | ----- |
| `Name` | строка | Название профиля в приложении. |
| `GlobalProxy` | `"true"`/`"false"` | Глобальный режим: всё, что не попало в правила, идёт через прокси. |
| `RouteOrder` | строка | Порядок проверки групп через дефис: `block-proxy-direct`, `block-direct-proxy` и т. п. Побеждает **первая** сработавшая группа. Допустимые слова: `block`, `proxy`, `direct`; повторы игнорируются. |
| `DirectSites` / `ProxySites` / `BlockSites` | массив строк | Домены: напрямую / через прокси / блокировать. |
| `DirectIp` / `ProxyIp` / `BlockIp` | массив строк | IP и подсети — те же три группы. |
| `RemoteDNSDomain`, `RemoteDNSIP`, `RemoteDNSType` | строка | DNS для проксируемого трафика (`DoH` и адрес `https://.../dns-query`). |
| `DomesticDNSDomain`, `DomesticDNSIP`, `DomesticDNSType` | строка | DNS для «прямых» доменов. |
| `DnsHosts` | объект «имя → IP» | Статические записи, чтобы не резолвить DoH‑хосты через сам DNS. |
| `DomainStrategy` | строка | Стратегия Xray: `AsIs`, `IPIfNonMatch`, `IPOnDemand`. |
| `FakeDNS`, `UseChunkFiles` | `"true"`/`"false"` | Расширения Happ; панель передаёт их клиенту как есть. |
Неизвестные поля **не теряются** — панель и редактор сохраняют их и передают
Happ.
### Формат записей в списках
Записи — синтаксис Xray‑маршрутизации:
| Запись | Что совпадает |
| ------ | ------------- |
| `geosite:category-ads-all` | Категория из `geosite.dat`. |
| `geosite:private`, `geoip:private` | Локальные/приватные адреса. |
| `geoip:ir`, `geoip:cn` | Страна из `geoip.dat`. |
| `domain:example.com` | Домен и все его поддомены. |
| `full:www.example.com` | Только этот домен. |
| `keyword:ads` | Домен, содержащий подстроку. |
| `regexp:\\.ru$` | Регулярное выражение. |
| `10.0.0.0/8`, `1.2.3.4` | Подсеть CIDR или один IP. |
Запись без префикса трактуется как подстрока домена — для точности пишите
`domain:`. Категории `geosite:`/`geoip:` должны существовать в `.dat` файлах
на клиенте; панель передаёт их в заголовке `Routing`, чтобы Happ подтянул
нужные гео‑файлы.
### Как собрать `happ://` ссылку вручную
Ссылка — это префикс и JSON в Base64 (UTF‑8):
```text
happ://routing/onadd/<base64 от JSON>
```
`onadd` добавляет профиль и сразу включает его; `add` — только добавляет.
Панель принимает base64 в обычном и URL‑safe виде, с `=` и без. Из PowerShell:
```powershell
$json = Get-Content .\routing.json -Raw -Encoding UTF8
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
"happ://routing/onadd/$b64"
```
Итоговое значение не должно превышать 8 КиБ, ссылка должна быть в одну строку.
### Что панель делает с этим JSON в JSON‑подписках
Для клиентов, которые читают конфиг из тела JSON‑подписки, профиль **вшивается**
в разделы `dns` и `routing`. Правила такие:
- порядок групп — из `RouteOrder`, по умолчанию `block`, `direct`, `proxy`;
- пустые списки пропускаются, в конце всегда добавляется правило «всё остальное
→ `proxy`»;
- `DomainStrategy` по умолчанию `IPIfNonMatch`;
- DNS: для `DirectSites` добавляется «внутренний» DNS (`DomesticDNS*`, по
умолчанию `https://77.88.8.8/dns-query`), для остального — `RemoteDNS*`
(по умолчанию `https://8.8.8.8/dns-query`); `DnsHosts` копируется в `dns.hosts`.
Поля должны иметь точный тип: строка — строка, список — массив строк, `DnsHosts` —
объект «строка → строка». Иначе профиль отбрасывается и подписка отдаётся с
маршрутизацией по умолчанию (в лог пишется предупреждение).
---
## Clash / Mihomo
### Где вводить
**Настройки → Подписка → Clash / Mihomo**:
1. включите **Включить маршрутизацию**;
2. заполните **Глобальные правила маршрутизации** — inline‑текстом или одной
HTTPS‑ссылкой на YAML.
Правила применяются к профилям по адресам `subClashPath` и `/mihomo/<sub-id>`.
Эндпоинт `/clash-legacy/` (Clash for Windows) всегда отдаёт минимальный профиль
и **игнорирует** эти настройки.
### Что уже есть в профиле
Панель собирает базу сама:
```yaml
proxies: # все ваши узлы, имена — их ремарки
- { name: "node-1", type: vless, ... }
proxy-groups:
- name: PROXY # select: все узлы + DIRECT
type: select
proxies: [node-1, DIRECT]
rules:
- MATCH,PROXY
```
Ваши правила можно направлять на группу **`PROXY`**, на `DIRECT`, на `REJECT`
либо на любую группу, которую вы сами объявили.
### Вариант 1: inline‑значение
Три допустимых формы.
**А) Просто строки правил** (можно с комментариями `#`):
```text
# рекламу блокируем
GEOSITE,category-ads-all,REJECT
DOMAIN-SUFFIX,example.com,DIRECT
GEOIP,RU,DIRECT,no-resolve
```
**Б) YAML‑список:**
```yaml
- GEOSITE,category-ads-all,REJECT
- DOMAIN-SUFFIX,example.com,DIRECT
- GEOIP,RU,DIRECT,no-resolve
```
**В) YAML‑карта.** Ключ `rules` объединяется с базовыми правилами, любые другие
ключи (`proxy-groups`, `rule-providers`, `dns`, `sniffer`, …) **заменяют**
одноимённые ключи профиля целиком:
```yaml
proxy-groups:
- name: PROXY
type: select
proxies: [DIRECT] # осторожно: заменяет группу PROXY целиком
rule-providers:
ads:
type: http
behavior: domain
format: yaml
url: https://example.com/ads.yaml
path: ./ruleset/ads.yaml
interval: 86400
rules:
- RULE-SET,ads,REJECT
- GEOIP,RU,DIRECT
```
Как объединяются правила:
- если в ваших правилах **нет** `MATCH`, они ставятся **перед** базовым
`MATCH,PROXY` — всё остальное пойдёт через прокси;
- если `MATCH` есть, ваш список **полностью заменяет** базовые правила.
В inline‑режиме проверка мягкая: содержимое YAML‑карты копируется как есть,
поэтому ошибки в именах групп вы увидите только в клиенте.
### Вариант 2: HTTPS‑ссылка на YAML
Здесь панель строже — она **проверяет** файл и только затем использует.
Из документа берутся только три ключа:
| Ключ | Что делает |
| ---- | ---------- |
| `rules` | Правила — объединяются по тем же правилам, что выше. |
| `proxy-groups` | Группы: одноимённые заменяют базовые, остальные базовые сохраняются. |
| `rule-providers` | Провайдеры правил. |
Ключи `dns` и `sniffer` берутся, **только если включён** переключатель
**DNS из удалённых правил** (`subClashRemoteDNS`) — включайте его лишь для
шаблона, которому доверяете: он меняет DNS клиента. Все остальные ключи
(`proxies`, `proxy-providers`, `port` и т. д.) игнорируются. Узлы всегда
остаются вашими.
Рабочий пример файла:
```yaml
proxy-groups:
- name: Streaming
type: select
proxies: [PROXY, DIRECT]
- name: Auto
type: url-test
url: https://www.gstatic.com/generate_204
interval: 300
proxies: [PROXY]
rule-providers:
ru-direct:
type: http
behavior: domain
format: yaml
url: https://example.com/ru-direct.yaml
path: ./ruleset/ru-direct.yaml
interval: 86400
rules:
- RULE-SET,ru-direct,DIRECT
- DOMAIN-SUFFIX,netflix.com,Streaming
- GEOIP,PRIVATE,DIRECT,no-resolve
- MATCH,PROXY
```
Что обязательно проверяется (при нарушении файл отклоняется, остаётся прошлая
рабочая версия):
- документ — YAML‑карта хотя бы с одним из `rules`, `proxy-groups`,
`rule-providers`;
- каждая группа — карта с непустыми `name` и `type`, имена **уникальны**;
- в группах **нельзя** использовать `use:` (proxy‑providers не поддерживаются);
- каждая ссылка в `proxies:` группы, цель каждого правила и `proxy:` у
провайдера должны указывать на группу из этого же файла, на `PROXY` или на
встроенные `DIRECT`, `REJECT`, `REJECT-DROP`, `REJECT-TINYGIF`, `PASS`,
`GLOBAL`. Удалённый файл проверяется сам по себе, поэтому имя конкретного
узла в нём не пройдёт проверку;
- `RULE-SET,<имя>,<цель>` требует провайдера с таким именем в `rule-providers`;
- каждое правило — непустая строка вида `ТИП,значение,цель`; после цели
допускаются флаги `no-resolve` и `src`;
- ограничения размера: 2 МиБ ответа и ограничение на вложенность и объём после
разворота YAML‑алиасов.
Так как имена узлов зависят от ремарок клиентов, надёжнее всего ссылаться на
группу **`PROXY`**, которая содержит все узлы.
---
## Incy
### Где вводить
**Настройки → Подписка → Incy → Маршрутизация**:
1. включите **Включить маршрутизацию**;
2. заполните **Правила маршрутизации**:
- готовая ссылка `incy://routing/onadd/<base64>` — тот же JSON, что и у
Happ, закодированный в Base64;
- **или одна HTTPS‑ссылка** на JSON‑файл. Панель превращает её в ссылку
`incy://autorouting/onadd/<url>`, и приложение **само** периодически
перекачивает профиль.
Профиль для Incy уходит строкой в **теле** подписки (только когда User‑Agent —
INCY). Заголовок `Routing` для Incy панель в этом случае не отправляет, чтобы
он не перебил профиль из тела.
### Формат JSON
Формат профиля Incy совпадает с форматом Happ — используйте те же поля
(`Name`, `RouteOrder`, `DirectSites`, `DirectIp`, `ProxySites`, `BlockSites`,
`DomainStrategy` и т. д., см. таблицу выше):
```json
{
"Name": "RU bypass",
"GlobalProxy": "true",
"RouteOrder": "block-proxy-direct",
"DirectSites": ["geosite:private", "domain:ru", "geosite:category-ru"],
"DirectIp": ["geoip:ru", "geoip:private"],
"ProxySites": [],
"ProxyIp": [],
"BlockSites": ["geosite:category-ads-all"],
"BlockIp": [],
"DomainStrategy": "IPIfNonMatch"
}
```
Закодированная форма: `incy://routing/onadd/<base64 от JSON>` (кодирование
как в примере для Happ).
> Если поле Incy пустое, Incy получает общий профиль **JSON‑подписки**
> (`subJsonRoutingRules`). Поле Happ Incy не читает.
### Остальные вкладки Incy
Вкладки **Приложение**, **Баннеры**, **Приватность** и **Сеть** не относятся к
маршрутизации: они задают заголовки управления приложением (описание профиля,
баннер, скрытие URL, фрагментация и т. д.) и отправляются только при включённом
**Автоопределении заголовков Incy**.
---
## Какой формат выбрать
| Нужно | Решение |
| ----- | ------- |
| Один набор правил для Happ и Incy | Один JSON, вставить в Happ как `happ://...`, в Incy как `incy://...` либо дать обоим одну HTTPS‑ссылку на JSON. |
| Правила для Clash/Mihomo | Отдельный YAML. JSON и YAML взаимно не конвертируются. |
| Менять правила без правки панели | Постоянная raw‑ссылка (gist, репозиторий) в нужном поле. |
| Проверить результат | Откройте подписку клиентским User‑Agent (`curl -A "Happ/1.0"`, `-A "INCY/1.0"`, `-A "clash.meta"`) и посмотрите заголовок `Routing` / тело ответа. |
## Частые проблемы
- **Правила не применились, в логе «Remote happ routing refresh from … failed»**
(или `clash`; для профиля JSON-подписки — «remote source unavailable»).
Ссылка ещё не
скачана (первая загрузка идёт в фоне — обновите подписку через минуту) или
источник вернул невалидный файл.
- **Файл отклонён из‑за размера.** Happ — максимум 8 КиБ после кодирования в Base64
(около 6 КиБ JSON); вынесите длинные
списки в `geosite`/`geoip` категории или в `rule-providers` (Clash).
- **Ошибка `references unknown proxy or group`.** Правило или группа ссылаются
на имя, которого нет в профиле. Используйте `PROXY`, `DIRECT`, `REJECT` или
объявите группу в том же файле.
- **Ссылка на страницу gist не работает.** Нужен `raw`‑URL.
- **Clash for Windows игнорирует правила.** Эндпоинт `/clash-legacy/` не
поддерживает пользовательскую маршрутизацию — используйте `/mihomo/`.
@@ -9,6 +9,24 @@ icon: Rss
входящего соединения клиенты подхватывают изменения автоматически. Сервер
подписок работает как **отдельный** сервер от панели.
## Замена узлов при отказе по HWID
В разделе **Настройки панели → Подписка** включите **Заменять конфиги при
отказе по HWID** (`subHwidRejectWithConfig`, по умолчанию выключено).
При отсутствии HWID или достижении лимита устройств сервер вернёт HTTP 200
с нерабочим узлом вместо 404. Поддерживаются обычные и base64-ссылки, Xray JSON,
Clash/Mihomo, старый Clash и автоматическое определение формата. Совместимое
приложение сможет принять обновление и заменить ранее загруженные узлы.
При выключенной настройке сохраняются ответ 404 и заголовки ошибки HWID.
![Настройка замены конфигов при отказе по HWID](/images/subscription-hwid-rejection.png)
Замена происходит только после обновления подписки приложением. Она не
отзывает скопированные ключи и не разрывает существующие соединения.
Удаление устройства освобождает место: если лимит позволяет, устройство
сможет зарегистрироваться снова. Чтобы оно получило отказ после удаления,
оставшиеся устройства должны заполнять установленный лимит.
## Включение и настройка
Сервер подписок **включён по умолчанию** (`subEnable`). Настройте его в
+8 -1
View File
@@ -110,6 +110,13 @@ HTTPUpgrade — это одноразовый HTTP/1.1 `Upgrade` без фрей
`sessionIDLength`) и параметры `scMin/MaxEachPostBytes` — продвинутые; оставьте
их пустыми, если только вы не подстраиваетесь под конкретный upstream.
Включите **Использовать отдельный канал загрузки**, чтобы клиент отправлял запросы
на скачивание на другой адрес. Укажите адрес и порт, затем задайте HTTP-параметры
`host` и `path` и настройки безопасности для этой точки подключения. Оба маршрута
должны вести к одному и тому же обработчику XHTTP. Если задать эти параметры для
входящего подключения, панель включит их в клиентские подписки. Переключатель
доступен в режимах `auto`, `packet-up` и `stream-up`.
### Hysteria — `hysteriaSettings`
Допустимо, только когда протокол — **Hysteria2**.
@@ -140,7 +147,7 @@ Mux. Панель предлагает XDRIVE только для VLESS, не с
| `secrets` | — | Google Drive: ровно три значения — ClientID, ClientSecret, RefreshToken, в этом порядке. Template: значения, доступные как `{secret0}`, `{secret1}`, …. S3: AccessKeyID, SecretAccessKey и при необходимости SessionToken. |
| `template` | — | Только для template: операции `auth`, `put`, `get`, `list` и `delete` API хранилища. |
| `s3` | — | Только для s3: `endpoint` (URL http(s)), `region`, `bucket` и `pathStyle` (по умолчанию `true`; `false` переносит бакет в имя хоста). `remoteFolder` — префикс объектов. |
| тонкая настройка | значения ядра | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). |
| тонкая настройка | значения ядра | `segmentBytes` (512 KiB), `flushIntervalMs` (20), `pollIntervalMs`/`maxPollIntervalMs` (50/500), `eagerWindowMs` (2000), `holeTimeoutMs` (30000), `sessionTtlSeconds` (300), `concurrency` (8). Для Google Drive по умолчанию `flushIntervalMs` 10, `maxPollIntervalMs` 200 и `concurrency` 64 (xray-core 26.11.9). |
Необязательные **адрес/порт фронтинга** (`address`/`port` на уровне stream) — домен-фронт,
через который идёт подключение к API хранилища; в TLS по-прежнему указывается хост API.
+10 -1
View File
@@ -24,7 +24,7 @@ API этого узла. Главная панель опрашивает каж
| **Схема** | `https` (по умолчанию) или `http`. |
| **Адрес / Порт** | Хост и порт панели узла. |
| **Базовый путь** | Веб-базовый путь узла. |
| **API-токен** | Bearer-токен, созданный на узле (не нужен в режиме mTLS). |
| **API-токен** | Bearer-токен, созданный на узле (в режиме mTLS необязателен, кроме **Обновления панели** — нужен `node-admin`). |
| **Проверка TLS** | `verify` (по умолчанию), `skip`, `pin` (закрепить SHA-256 сертификата) или `mtls`. |
| **Синхронизация inbound** | `all` (все) inbound-соединения или `selected` (выбранные) по тегу. |
| **Тег исходящего**| При необходимости обращаться к узлу **через** именованное исходящее соединение (мост исходящего трафика). |
@@ -67,6 +67,15 @@ API этого узла. Главная панель опрашивает каж
Задайте на узле режим проверки TLS `mtls`. Теперь главная панель предъявляет
клиентский сертификат вместо API-токена.
<Callout type="warn">
Узел, подключённый по mTLS без токена, имеет только область `node-sync`, которая
не позволяет выполнить **Обновление панели** (узел отвечает HTTP 403,
«this API token is not permitted to access this endpoint»). Чтобы обновить такой
узел с главной панели, создайте на узле API-токен с областью `node-admin` и
вставьте его в поле **API-токен** этого узла на главной панели. Режим проверки
TLS оставьте `mtls`.
</Callout>
</Step>
</Steps>
@@ -140,7 +140,7 @@ hostname получает уникальный тег `nord-<hostname>` и не
маршрутизации/балансировщиков по точному тегу остаются привязанными — в то время
как селекторы по префиксу/шаблону (например, `hk-*`) автоматически подхватывают
новые серверы по мере изменения пула. Поддерживаемые схемы ссылок: `vmess`,
`vless`, `trojan`, `ss`, `hysteria2` (`hy2`) и `wireguard` (`wg`). Панель
`vless`, `trojan`, `ss`, `hysteria2` (`hy2`), `wireguard` (`wg`) и `vpn` (AmneziaWG: из панели 3x-ui или ключ приложения AmneziaVPN). Панель
обновляет включённые подписки по таймеру и перезагружает Xray при любых
изменениях.
+4 -2
View File
@@ -21,8 +21,10 @@ icon: ShieldCheck
Задайте **ограничение IP** для каждого клиента (см. [Клиенты](/docs/config/clients)), чтобы
ограничить число одновременных исходных IP. Применением правил занимается **Fail2ban**, который
3x-ui устанавливает и настраивает за вас (включён по умолчанию при установке через скрипт, а
в Docker — через `XUI_ENABLE_FAIL2BAN=true`).
3x-ui устанавливает и настраивает по вашему согласию. При новой установке через
скрипт ответьте **Да**, чтобы включить применение ограничений. Для автоматической
установки и Docker задайте `XUI_ENABLE_FAIL2BAN=true`. Скрипт сохраняет выбор при
обновлении и переустановке. Отслеживание исходных IP работает независимо.
Управляйте им из меню `x-ui` (**22 — IP Limit Management**): установка/настройка,
изменение длительности блокировки (по умолчанию **30 минут**), блокировка/разблокировка IP, просмотр журналов блокировок
@@ -7,7 +7,7 @@ icon: Send
3x-ui умеет управлять Telegram-ботом для мониторинга, оповещений, резервного
копирования и удалённого управления. Администраторы получают полный контроль;
обычные пользователи (привязанные по Telegram ID) могут проверять собственный
расход трафика и ссылки.
расход трафика и получать ссылки и инструкции по настройке.
<Callout type="info">
Ищете новости и поддержку сообщества? Присоединяйтесь к официальному
@@ -84,7 +84,9 @@ ID темы после двоеточия, например `-1001234567890:42`.
клиента администратор получает ссылку на подписку, отдельные ссылки и QR-код —
конфигурацию можно передать клиенту, который ещё не может открыть Telegram.
Обычным пользователям доступны кнопки для своего расхода, ссылок на подписку,
отдельных ссылок и QR-кодов.
отдельных ссылок, QR-кодов, **Получить один** (выбрать одну ссылку и получить её
отдельно, со своим QR-кодом) и **Инструкция** по настройке для каждой платформы.
Каждая страница ссылок начинается с даты окончания конфигурации и остатка трафика.
## Отчёты и оповещения
+14 -13
View File
@@ -44,10 +44,11 @@ _openapi:
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields
you want to keep (the server replaces the row, it does not patch).
inbound. Body is the JSON client payload: omitted fields keep their
current values, and an explicit zero, empty or null value clears a
field, except as noted below.
url: >-
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- depth: 2
title: >-
Delete a client by email. Removes it from every attached inbound and
@@ -215,7 +216,7 @@ _openapi:
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
@@ -229,7 +230,7 @@ _openapi:
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
@@ -237,7 +238,7 @@ _openapi:
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
@@ -358,11 +359,11 @@ _openapi:
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload — supply the full
set of fields you want to keep (the server replaces the row, it does
not patch).
attached inbound. Body is the JSON client payload: omitted fields keep
their current values, and an explicit zero, empty or null value clears
a field, except as noted below.
id: >-
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- content: >-
Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
@@ -513,7 +514,7 @@ _openapi:
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
@@ -525,14 +526,14 @@ _openapi:
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
+4
View File
@@ -40,6 +40,10 @@ icon: ArrowDownToLine
选择 `monthly` 时,可以指定每月 1 至 31 日重置。如果当月没有指定日期,
则在该月最后一天重置。
开启**保留客户端用量**后,定时任务仅清零入站计数,客户端继续按自己的周期累计用量。
关闭时,定时任务也会清零关联客户端在所有入站上的累计用量。
为纳管入站开启此选项前,请先升级主面板及承载该入站的节点。
</Step>
</Steps>
+1 -1
View File
@@ -57,7 +57,7 @@ Shadowsocks 节点,并排除 VLESS、Hysteria2、Reality、XHTTP、HTTPUpgrade
如果管理员已经把 `/mihomo/` 或 `/clash-legacy/` 分配给其他可配置订阅路径,
系统会保留原有路径,并在启动时记录警告、跳过发生冲突的别名。
Clash 格式自动识别保留原有的 `(?i)(clash|mihomo)` 默认匹配器,确保已有订阅 URL
Clash 格式自动识别默认使用 `(?i)(clash|mihomo|rabbit-hole)` 匹配器,确保已有订阅 URL
继续返回 YAML。它不区分旧版客户端与 Mihomo 系客户端;Clash for Windows 用户
必须使用 `/clash-legacy/<sub-id>` 获取兼容配置。
+6 -1
View File
@@ -103,6 +103,11 @@ Session-ID 字段(`sessionIDPlacement`、`sessionIDKey`、`sessionIDTable`、
`sessionIDLength`)以及 `scMin/MaxEachPostBytes` 旋钮属于高级项;除非要匹配某个特定的
上游,否则保持为空。
启用**使用独立下载通道**后,客户端会向另一个端点发送下载请求。填写该端点的地址和端口,
并按其要求设置 HTTP 主机名、路径和安全参数。上传和下载两条路由必须通往同一个 XHTTP
监听器。在入站配置中启用此选项后,面板会将这些设置加入客户端订阅。此开关适用于
`auto`、`packet-up` 和 `stream-up` 模式。
### Hysteria — `hysteriaSettings`
仅当协议为 **Hysteria2** 时有效。
@@ -129,7 +134,7 @@ XDRIVE 把数据流作为文件存放在双方都能访问的文件夹中:服
| `secrets` | — | Google Drive:恰好三项,依次为 ClientID、ClientSecret、RefreshToken。Template:以 `{secret0}`、`{secret1}`… 引用的值。S3:AccessKeyID、SecretAccessKey,以及可选的 SessionToken。 |
| `template` | — | 仅用于 template 服务:存储 API 的 `auth`、`put`、`get`、`list` 和 `delete` 操作。 |
| `s3` | — | 仅用于 s3 服务:`endpoint`(http(s) URL)、`region`、`bucket` 和 `pathStyle`(默认 `true`;为 `false` 时存储桶名放在主机名中)。`remoteFolder` 为对象前缀。 |
| 调优参数 | 内核默认值 | `segmentBytes`(512 KiB)、`flushIntervalMs`(20)、`pollIntervalMs`/`maxPollIntervalMs`(50/500)、`eagerWindowMs`(2000)、`holeTimeoutMs`(30000)、`sessionTtlSeconds`(300)、`concurrency`(8)。 |
| 调优参数 | 内核默认值 | `segmentBytes`(512 KiB)、`flushIntervalMs`(20)、`pollIntervalMs`/`maxPollIntervalMs`(50/500)、`eagerWindowMs`(2000)、`holeTimeoutMs`(30000)、`sessionTtlSeconds`(300)、`concurrency`(8)。Google Drive 的默认值为 `flushIntervalMs` 10、`maxPollIntervalMs` 200、`concurrency` 64(xray-core 26.11.9)。 |
可选的**前置地址/端口**(stream 级的 `address`/`port`)是连接存储 API 时使用的域前置;TLS 中仍使用 API 主机名。
XDRIVE 没有自己的 TLS/REALITY 层——其流量就是存储 API 自身的 HTTPS。在出站上,**TLS**
@@ -8,6 +8,7 @@
"backup-restore",
"telegram-bot",
"discord-bot",
"wechat-notifications",
"security"
]
}
@@ -20,7 +20,7 @@ icon: Boxes
| **Scheme** | `https`(默认)或 `http`。 |
| **Address / Port**| 节点面板的主机和端口。 |
| **Base path** | 节点的 Web 基础路径。 |
| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下不需要)。 |
| **API token** | 在节点上创建的 Bearer 令牌(mTLS 模式下可选,但**更新面板**需要 `node-admin` 令牌)。 |
| **TLS verify** | `verify`(默认)、`skip`、`pin`(固定证书 SHA-256)或 `mtls`。 |
| **Inbound sync** | `all` 入站,或按标签 `selected`。 |
| **Outbound tag** | 可选地**通过**指定的出站到达节点(出口桥接)。 |
@@ -53,6 +53,10 @@ icon: Boxes
### 将节点切换到 mTLS
将节点的 TLS 验证模式设置为 `mtls`。现在主控将出示客户端证书而非 API 令牌。
<Callout type="warn">
通过 mTLS 连接且未提供令牌的节点只具有 `node-sync` 权限范围,无法执行**更新面板**(节点返回 HTTP 403,“this API token is not permitted to access this endpoint”)。要从主控更新此类节点,请在节点上创建具有 `node-admin` 权限范围的 API 令牌,并将其填入主控中该节点的 **API token** 字段。TLS 验证模式保持为 `mtls`。
</Callout>
</Step>
</Steps>
@@ -117,7 +117,7 @@ Xray 配置中——而不会改动你已保存的模板。这是订阅一*池*
导入的出站会获得**稳定的标签**:同一台服务器在多次刷新之间始终保持同一个标签,
因此精确标签的路由/均衡器选择器会保持固定——而前缀/通配符选择器(例如 `hk-*`)
则会随着服务器池的变化自动纳入新的服务器。支持的链接协议:`vmess`、`vless`、`trojan`、`ss`、
`hysteria2`(`hy2`)以及 `wireguard`(`wg`)。面板会按定时器刷新已启用的
`hysteria2`(`hy2`)、`wireguard`(`wg`)以及 `vpn`(AmneziaWG,来自 3x-ui 面板或 AmneziaVPN 应用密钥)。面板会按定时器刷新已启用的
订阅,并在内容发生变化时重载 Xray。
## 路由规则
+3 -2
View File
@@ -19,8 +19,9 @@ icon: ShieldCheck
## Fail2ban 与 IP 限制
为每个客户端设置一个 **IP 限制**(参见[客户端](/docs/config/clients)),以限制同时使用的源
IP 数量。限制的执行由 **Fail2ban** 负责,3x-ui 会为你安装并配置好它(脚本安装时默认启用,
Docker 安装时通过 `XUI_ENABLE_FAIL2BAN=true` 启用)。
IP 数量。由 **Fail2ban** 执行限制,3x-ui 会在你同意后安装并配置它。首次通过脚本安装时,
选择 **Yes** 以启用限制。对于无人值守和 Docker 安装,请设置 `XUI_ENABLE_FAIL2BAN=true`。
脚本会在更新和重新安装时保留你的选择。源 IP 跟踪独立运行。
可从 `x-ui` 菜单(**22 — IP Limit Management**)进行管理:安装/配置、修改封锁时长
(默认 **30 分钟**)、封锁/解封某个 IP、查看封锁日志,以及检查状态。其底层机制如下:
@@ -6,7 +6,7 @@ icon: Send
3x-ui 可以驱动一个 Telegram 机器人,用于监控、告警、备份和远程管理。
管理员拥有完全的控制权;普通用户(通过 Telegram ID 关联)则可以
查询自己的用量和链接。
查询自己的用量,获取链接和使用指南。
<Callout type="info">
想获取最新动态和社区支持?欢迎加入官方 Telegram 频道
@@ -74,7 +74,9 @@ ID 的所有客户端。订阅 ID 就是邀请码,因此请保持其足够长
“即将耗尽”,以及完整的**添加客户端**向导。管理员的**客户端卡片**上还带有该客户端的
订阅链接、单条链接和 QR 码,因此可以把配置交给暂时还无法打开 Telegram 的客户端。
普通用户则可以使用按钮查看
自己的用量、订阅链接、单条链接和 QR 码。
自己的用量、订阅链接、单条链接和 QR 码,使用**获取单个**(挑选一条链接,
单独获取它及其专属 QR 码),以及按平台分类的**使用指南**。每个链接页面
开头都会显示该配置的到期日期和剩余流量。
## 报告与告警
@@ -0,0 +1,60 @@
---
title: 微信通知
description: 通过企业微信群机器人或兼容的个人微信网关接收面板告警和定时状态报告。
icon: MessageCircle
---
微信是独立、默认关闭的文字通知通道,可与 Telegram、Discord、邮件同时使用。它有自己的语言、事件选择、CPU 和内存阈值,以及独立的定时报告计划。
企业微信模式向企业微信群机器人发送消息。个人微信需要另外部署兼容下文协议的桥接服务,并由该服务维护可用的微信连接。面板不包含这个桥接服务,也不提供直接登录个人微信机器人的入口。
## 配置
1. 打开 **面板设置 → 微信**,启用通知。
2. 选择发送方式。
- **企业微信群机器人**:在企业微信群中添加消息推送机器人,填写其 HTTPS Webhook 地址。见[企业微信官方说明](https://developer.work.weixin.qq.com/document/path/99110)。
- **自定义 Webhook 网关**:填写自己实现的兼容 HTTPS 接口,按需配置接收端校验的 Bearer Token,再由该服务向个人微信投递。接口必须实现下文协议,微信联系人或任意第三方推送 URL 不能直接作为接收端。
3. 选择通知语言,该设置独立于 Telegram 机器人语言。
4. 在 **通知** 中选择事件和指标阈值。阈值为 `0` 时关闭对应指标告警。
5. 按需启用定时报告并设置计划。`@daily` 使用面板调度器的时区。
6. 先 **保存**,再 **发送测试通知**。测试使用已保存的配置;通道关闭或存在未保存的设置修改时,测试按钮不可用。
地址可能包含机器人密钥,因此地址和 Token 均在返回浏览器时隐藏。留空保留原值,点击 **清空** 后保存才会删除。清除必填地址前应先关闭通知。保存后会更新报告计划和指标采样任务,无需重启面板。
![已保存自定义网关、隐藏凭据的微信通知设置页面](/images/wechat-settings.png)
## 内容和频率
可选事件包括登录尝试、CPU 和内存超阈值、Xray 崩溃、节点离线与恢复、出站不可达与恢复。默认选择登录尝试和 CPU 告警。登录通知包含尝试的用户名、来源 IP、结果和可用的失败原因,不包含密码。
同类事件和来源每分钟最多成功发送一次;同一来源的登录失败和成功分别限频。发送失败不占用成功发送的冷却时间。
报告汇总主机、面板和 Xray 版本、CPU、内存、磁盘、运行时间,以及入站和客户端的总数、禁用、过期、流量耗尽数量。Xray 停止时仍能报告状态。此通道不提供远程命令或文件备份,报告不包含订阅链接和客户端配置文件。
流量只汇总本面板管理的客户端统计,按客户端邮箱去重。已用流量为上传与下载之和;剩余流量为每个客户端额度扣除已用量后的非负余额之和,运行统计中未设置额度时回退到客户端配置的额度。没有客户端统计,或任意客户端未配置额度时,剩余流量显示 **未配置额度**。这不是 VPS 服务商的计费额度,也不包含绕过 3x-ui 的流量。
## 自定义网关协议
HTTPS `POST`,`Content-Type: application/json`。配置 Token 时发送 `Authorization: Bearer <token>`。
```json
{
"version": 1,
"id": "8f793626-a0e0-4a28-bddf-84c077a1bd21",
"type": "event",
"event": "cpu.high",
"hostname": "my-server",
"occurred_at": "2026-11-04T12:00:00Z",
"text": "3x-ui · my-server\nCPU 使用率:92.00%;阈值:80%"
}
```
`type` 为 `event`、`report` 或 `test`。事件键为 `login.attempt`、`cpu.high`、`memory.high`、`xray.crash`、`node.down`、`node.up`、`outbound.down`、`outbound.up`;报告和测试分别使用 `report`、`test`。`occurred_at` 保留事件发生的 UTC 时间,缺失时才使用发送时间。正文最多 20,480 个 UTF-8 字节。
接收端应校验认证和版本,以 `id` 为唯一键可靠入队,再返回 `2xx`。这代表网关接受投递责任,最终微信消息的发送及重试由网关负责。
连接失败或 `5xx` 时,面板最多重试一次,沿用相同 ID 和正文;其他失败响应不重试。接收端应按 ID 去重,避免响应丢失造成重复消息。每次请求超时 10 秒,响应最多 4 KiB,不跟随重定向。协议不依赖特定的网关服务。
企业微信模式只接受官方机器人 HTTPS 地址,并要求响应 `errcode: 0`。长消息按 UTF-8 字节边界拆分,每段最多 2,048 字节、最多十段,发送间隔至少 3.1 秒。该接口不能按本通道的 ID 去重,因此不自动重试。
两种方式均直接通过 HTTPS 连接、校验证书,不继承面板出站代理。自定义地址必须指向公网,实际连接时再次阻止回环、私网、链路本地和元数据服务地址。微信适配器位于内网时,应提供公开的 HTTPS 接收网关。
+12 -12
View File
@@ -35,10 +35,10 @@ _openapi:
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- depth: 2
title: >-
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷——
请提供你希望保留的完整字段集(服务端会替换整条记录,而非局部更新)。
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷:
省略的字段保留当前值,显式的零值、空值或 null 会清除该字段(例外见下文)。
url: >-
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- depth: 2
title: >-
按 email 删除客户端。将其从每个挂载的入站中移除,并删除其流量记录,除非传入
@@ -175,7 +175,7 @@ _openapi:
列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符)
与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需
@@ -187,14 +187,14 @@ _openapi:
创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选
抽屉中变为可选。若已存在同名分组,则报错。
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端
(包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回
标签被更新的客户端数量。
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括
@@ -292,10 +292,10 @@ _openapi:
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷——
请提供你希望保留的完整字段集(服务端会替换整条记录,而非局部更新)。
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷:
省略的字段保留当前值,显式的零值、空值或 null 会清除该字段(例外见下文)。
id: >-
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below
- content: >-
按 email 删除客户端。将其从每个挂载的入站中移除,并删除其流量记录,除非传入
keepTraffic=1。
@@ -412,7 +412,7 @@ _openapi:
列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符)
与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需
往返获取完整的客户端列表。
@@ -422,13 +422,13 @@ _openapi:
创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选
抽屉中变为可选。若已存在同名分组,则报错。
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端
(包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回
标签被更新的客户端数量。
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括
clients.group_name 以及入站 settings JSON)。客户端本身不会被删除——如需删除请先按
+11
View File
@@ -1,3 +1,4 @@
import { readFileSync } from 'node:fs';
import { describe, it, expect } from 'vitest';
import {
buildSubscriptionUrls,
@@ -121,6 +122,16 @@ describe('buildJsonSubscription', () => {
expect(cfg.remarks).toBe('HK-01');
});
// A key the panel drops from its template stays behind in this copy, deprecation warning and all.
it("carries the panel's embedded template around the proxy outbound", () => {
const template = JSON.parse(
readFileSync(new URL('../../../internal/sub/default.json', import.meta.url), 'utf8'),
);
const cfg = JSON.parse(buildJsonSubscription([vlessClient]));
expect(cfg.outbounds.slice(1)).toEqual(template.outbounds);
expect({ ...cfg, remarks: '', outbounds: template.outbounds }).toEqual(template);
});
it('keeps the Mihomo-only ML-KEM hint out of the Xray realitySettings', () => {
const cfg = JSON.parse(buildJsonSubscription([vlessClient]));
expect(cfg.outbounds[0].streamSettings.realitySettings.publicKey).toBe(vlessClient.publicKey);
+1 -1
View File
@@ -182,7 +182,7 @@ function skeletonOutbounds(): Record<string, unknown>[] {
{
tag: 'direct',
protocol: 'freedom',
settings: { domainStrategy: 'AsIs', redirect: '', noises: [] },
settings: { redirect: '' },
},
{ tag: 'block', protocol: 'blackhole', settings: { response: { type: 'http' } } },
];
+16 -16
View File
@@ -18,34 +18,34 @@
"test:watch": "vitest"
},
"dependencies": {
"fumadocs-core": "^16.17.9",
"fumadocs-core": "^16.19.7",
"fumadocs-docgen": "^3.2.0",
"fumadocs-mdx": "^15.4.10",
"fumadocs-openapi": "^12.5.7",
"fumadocs-ui": "^16.17.9",
"lucide-react": "^1.66.0",
"mermaid": "^12.2.0",
"next": "16.4.3",
"fumadocs-mdx": "^15.6.4",
"fumadocs-openapi": "^12.6.7",
"fumadocs-ui": "^16.19.7",
"lucide-react": "^1.77.0",
"mermaid": "^12.3.0",
"next": "16.4.6",
"next-themes": "^0.4.6",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-qr-code": "^2.2.0",
"tailwind-merge": "^3.7.0",
"zbsearch": "4.0.1",
"tailwind-merge": "^3.7.1",
"zbsearch": "4.0.4",
"zod": "^4.6.7"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
"@tailwindcss/postcss": "^4.3.5",
"@types/mdx": "^2.0.14",
"@types/node": "^26.6.6",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"oxfmt": "0.75.0",
"oxlint": "1.90.0",
"postcss": "^8.5.32",
"tailwindcss": "^4.3.3",
"oxfmt": "0.79.0",
"oxlint": "1.94.0",
"postcss": "^8.5.33",
"tailwindcss": "^4.3.5",
"typescript": "7.0.2",
"vitest": "^5.0.5"
"vitest": "^5.1.1"
},
"packageManager": "pnpm@12.16.1"
"packageManager": "pnpm@12.16.1+sha512.091d1dee7927575661b25dab3c2ae31cafc1c54d6b71ed6a6600cf0c1cb10434a447eae14015f1b23e2e6bedeed79df94a932e2164d2832280dce3fb32f656d1"
}
+1171 -1439
View File
File diff suppressed because it is too large Load Diff
-13
View File
@@ -10,16 +10,3 @@ overrides:
# @tailwindcss/node 4.3.3 pins 1.32.0, which rejects fumadocs-ui's ::highlight(fd-search).
'lightningcss@<1.33.0': '^1.33.0'
minimumReleaseAgeExcludePrune: true
minimumReleaseAgeExclude:
- '@fumadocs/json-schema@0.3.5'
- '@next/env@16.4.3'
- '@next/swc-darwin-arm64@16.4.3'
- '@next/swc-darwin-x64@16.4.3'
- '@next/swc-linux-arm64-gnu@16.4.3'
- '@next/swc-linux-arm64-musl@16.4.3'
- '@next/swc-linux-x64-gnu@16.4.3'
- '@next/swc-linux-x64-musl@16.4.3'
- '@next/swc-win32-arm64-msvc@16.4.3'
- '@next/swc-win32-x64-msvc@16.4.3'
- fumadocs-mdx@15.4.10
- next@16.4.3
Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+2933 -75
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,4 +1,4 @@
node_modules/
node_modules
.vite/
*.log
*.tsbuildinfo
+27
View File
@@ -47,6 +47,33 @@ production-style links work without round-tripping through Go.
CI runs `typecheck`, `lint`, `format:check`, `test`, `build`, and
`build-storybook` on every PR (see `../.github/workflows/ci.yml`).
### Inbound accessibility verification
`npm test` includes the real inbound form and native-select regression fixtures.
After `npm run build-storybook`, serve the built stories with
`npx vite preview --outDir storybook-static --host 127.0.0.1 --port 6006` and, in
another terminal, run `node tools/check-inbound-keyboard.mjs`. CI runs this check
too. It uses real Chromium Tab/Arrow/Enter input, checks native selected values
in the accessibility tree, captures create/edit requests, and verifies focus
containment and return. Its HTTP boundary is stubbed; backend configuration
generation and server validation are unchanged.
Mobile viewport emulation and accessibility-tree checks do not prove TalkBack
or NVDA compatibility. On actual Android TalkBack/Chrome and Windows NVDA:
1. Open Add Inbound, explore Protocol, open the native picker, choose Shadowsocks
and confirm the control announces its selected value. Cancel another picker
and confirm the value and focus stay unchanged.
2. Visit Protocol, select an encryption method, then Stream; choose RAW,
WebSocket, gRPC and XHTTP and verify the dependent fields and their labels.
3. Check Security's None/TLS/REALITY radios; try certificate/uTLS selections and
the ALPN multi-select, searchable node/fallback fields, clearing and custom tags.
4. Trigger a custom-share-address validation error from another tab. Confirm
the form reveals/focuses the field and reads its hint/error. Correct it and save.
5. Edit the inbound, confirm Protocol remains disabled, save a transport change,
and close/reopen with keyboard and touch exploration. Focus must return to
the opener and Tab/Shift+Tab must stay inside the open dialog.
### One-off: scan for deprecated APIs
Run this command to sweep the codebase for usages of APIs marked
+1214 -1266
View File
File diff suppressed because it is too large Load Diff
+29 -29
View File
@@ -38,50 +38,50 @@
"@ant-design/icons": "^6.3.4",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^7.0.1",
"@hookform/resolvers": "^7.0.8",
"@noble/hashes": "^2.4.0",
"@tanstack/react-query": "^5.105.1",
"@tanstack/react-query-devtools": "^5.105.1",
"antd": "^6.6.8",
"@tanstack/react-query": "^5.108.3",
"@tanstack/react-query-devtools": "^5.108.3",
"antd": "^6.7.2",
"codemirror": "^6.0.2",
"dayjs": "^1.11.23",
"i18next": "^26.6.0",
"otpauth": "^9.5.2",
"i18next": "^27.2.4",
"otpauth": "^9.6.0",
"persian-calendar-suite": "^1.5.6",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-hook-form": "^7.91.0",
"react-i18next": "^17.1.10",
"react-router": "^8.5.1",
"swagger-ui-react": "^5.34.1",
"react-hook-form": "^7.92.0",
"react-i18next": "^18.0.3",
"react-router": "^8.5.2",
"swagger-ui-react": "^5.36.0",
"uplot": "^1.6.32",
"zod": "^4.6.7"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.6.5",
"@storybook/addon-docs": "^10.6.5",
"@storybook/addon-vitest": "^10.6.5",
"@storybook/react-vite": "^10.6.5",
"@storybook/addon-a11y": "^10.6.8",
"@storybook/addon-docs": "^10.6.8",
"@storybook/addon-vitest": "^10.6.8",
"@storybook/react-vite": "^10.6.8",
"@testing-library/dom": "^10.4.2",
"@testing-library/react": "^16.3.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.1.2",
"@vitest/browser-playwright": "5.0.5",
"@vitest/coverage-v8": "^5.0.5",
"@vitejs/plugin-react": "^6.3.0",
"@vitest/browser-playwright": "5.1.1",
"@vitest/coverage-v8": "^5.1.1",
"husky": "^9.1.7",
"jsdom": "^30.1.3",
"lint-staged": "^17.6.0",
"msw": "^3.0.3",
"oxfmt": "0.75.0",
"jsdom": "^31.0.1",
"lint-staged": "^17.6.2",
"msw": "^3.0.7",
"oxfmt": "0.78.0",
"oxlint": "1.90.0",
"oxlint-tsgolint": "^7.0.2005",
"playwright": "^1.64.1",
"storybook": "^10.6.5",
"oxlint-tsgolint": "^7.0.2008",
"playwright": "^1.65.1",
"storybook": "^10.6.8",
"typescript": "7.0.2",
"vite": "8.3.5",
"vitest": "^5.0.5"
"vite": "8.3.8",
"vitest": "^5.1.1"
},
"overrides": {
"dompurify": "^3.4.17",
@@ -104,9 +104,9 @@
"valibot": "^1.1.0"
},
"@storybook/addon-vitest": {
"vitest": "5.0.5",
"@vitest/browser-playwright": "5.0.5",
"@vitest/browser": "5.0.5"
"vitest": "5.1.1",
"@vitest/browser-playwright": "5.1.1",
"@vitest/browser": "5.1.1"
},
"remarkable": {
"argparse": "^2.0.1"
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
export function clientManagementPath(action: 'get' | 'update' | 'del', email: string): string {
const base = `/panel/api/clients/${action}`;
const encoded = encodeURIComponent(email);
return email === '.' || email === '..' ? `${base}?email=${encoded}` : `${base}/${encoded}`;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { parseMsg } from '@/utils/zodValidate';
import { AllSetting } from '@/models/setting';
import {
AllSettingResponseSchema,
AllSettingSchema,
AllSettingFieldsSchema,
type AllSettingInput,
} from '@/schemas/setting';
import { keys } from '@/api/queryKeys';
@@ -63,7 +63,7 @@ export function useAllSettings() {
saved?: AllSetting;
}): Promise<SettingSaveResult> => {
const next = { ...payload };
const body = AllSettingSchema.partial().safeParse(next);
const body = AllSettingFieldsSchema.partial().safeParse(next);
if (!body.success) {
console.warn('[zod] setting/update body failed validation', body.error.issues);
}
@@ -0,0 +1,30 @@
import { useQuery } from '@tanstack/react-query';
import { keys } from '@/api/queryKeys';
import {
normalizeClientUsageHistory,
type ClientUsageHistoryInfo,
} from '@/lib/clients/usage-history';
import { HttpUtil } from '@/utils';
async function fetchClientUsageHistory(email: string): Promise<ClientUsageHistoryInfo> {
const msg = await HttpUtil.get<unknown>(
`/panel/api/clients/usageHistory/${encodeURIComponent(email)}`,
undefined,
{ silent: true },
);
if (!msg?.success || !msg.obj) {
throw new Error(msg?.msg || 'Failed to load the usage history');
}
return normalizeClientUsageHistory(msg.obj);
}
// The edit modal's usage-history fetch: runs only while the modal is open
// for a real client, and caches per email so a reopen is instant.
export function useClientUsageHistoryQuery(email: string | undefined, enabled: boolean) {
return useQuery({
queryKey: keys.clients.usageHistory(email ?? ''),
enabled: enabled && !!email,
queryFn: () => fetchClientUsageHistory(email as string),
});
}
@@ -0,0 +1,21 @@
import { useQuery } from '@tanstack/react-query';
import { NetworkInterfacesResponseSchema } from '@/generated/zod';
import { keys } from '@/api/queryKeys';
import { HttpUtil } from '@/utils';
export function useNetworkInterfaces(enabled: boolean) {
return useQuery({
enabled,
queryKey: keys.server.networkInterfaces(),
queryFn: async () => {
const msg = await HttpUtil.get('/panel/api/server/networkInterfaces', undefined, {
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load network interfaces');
return NetworkInterfacesResponseSchema.parse(msg.obj);
},
staleTime: 10_000,
refetchInterval: 15_000,
});
}
@@ -83,12 +83,29 @@ export function useNodeMutations() {
},
});
const restartMut = useMutation({
mutationFn: ({ id, target }: { id: number; target: 'xray' | 'panel' }) =>
HttpUtil.post(
`/panel/api/nodes/${target === 'xray' ? 'restartXray' : 'restartPanel'}/${id}`,
undefined,
{
silent: true,
timeout: 12000,
},
),
retry: false,
onSuccess: (msg) => {
if (msg?.success) queryClient.invalidateQueries({ queryKey: keys.nodes.root() });
},
});
return {
create: (payload: Partial<NodeRecord>) => createMut.mutateAsync(payload),
update: (id: number, payload: Partial<NodeRecord>) => updateMut.mutateAsync({ id, payload }),
remove: (id: number) => removeMut.mutateAsync(id),
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
probe: (id: number) => probeMut.mutateAsync(id),
restart: (id: number, target: 'xray' | 'panel') => restartMut.mutateAsync({ id, target }),
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> =>
updatePanelsMut.mutateAsync({ ids, dev }),
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
+2
View File
@@ -2,6 +2,7 @@ export const keys = {
sponsors: () => ['sponsors'] as const,
server: {
status: () => ['server', 'status'] as const,
networkInterfaces: () => ['server', 'networkInterfaces'] as const,
fail2banStatus: () => ['server', 'fail2banStatus'] as const,
},
nodes: {
@@ -40,6 +41,7 @@ export const keys = {
activeInbounds: () => ['clients', 'activeInbounds'] as const,
lastOnline: () => ['clients', 'lastOnline'] as const,
groups: () => ['clients', 'groups'] as const,
usageHistory: (email: string) => ['clients', 'usageHistory', email] as const,
},
xray: {
root: () => ['xray'] as const,
@@ -0,0 +1,55 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import ClientHwidListModal from './ClientHwidList';
const meta = {
title: 'Clients/HWID Devices',
component: ClientHwidListModal,
args: {
open: true,
email: 'subscriber@example.com',
loading: false,
clearing: false,
deletingId: null,
blockingId: null,
formatDate: (ts: number) => new Date(ts).toISOString().replace('T', ' ').slice(0, 16),
onRefresh: fn(),
onClearAll: fn(),
onDelete: fn(),
onSetBlocked: fn(),
onClose: fn(),
},
} satisfies Meta<typeof ClientHwidListModal>;
export default meta;
type Story = StoryObj<typeof meta>;
export const AllowedAndBlocked: Story = {
args: {
hwids: [
{
id: 1,
blocked: false,
firstSeen: 1794225600000,
lastSeen: 1794484800000,
userAgent: 'Happ/4.0',
deviceOs: 'Android',
osVersion: '15',
deviceModel: 'Pixel 9',
fingerprint: '6ad17c93e821',
},
{
id: 2,
blocked: true,
firstSeen: 1794225600000,
lastSeen: 1794398400000,
userAgent: 'Happ/4.0',
deviceOs: 'iOS',
osVersion: '18',
deviceModel: 'iPhone',
fingerprint: '9d241cb7e506',
},
],
},
};
@@ -1,5 +1,5 @@
import { Button, Modal, Popconfirm, Tag, Typography } from 'antd';
import { DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import { DeleteOutlined, ReloadOutlined, StopOutlined, UnlockOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { ClientHwidInfo } from '@/lib/clients/hwid-log';
@@ -11,10 +11,12 @@ interface ClientHwidListModalProps {
loading: boolean;
clearing: boolean;
deletingId: number | null;
blockingId: number | null;
formatDate: (ts: number) => string;
onRefresh: () => void;
onClearAll: () => void;
onDelete: (id: number) => void;
onSetBlocked: (id: number, blocked: boolean) => void;
onClose: () => void;
}
@@ -28,10 +30,12 @@ export default function ClientHwidListModal({
loading,
clearing,
deletingId,
blockingId,
formatDate,
onRefresh,
onClearAll,
onDelete,
onSetBlocked,
onClose,
}: ClientHwidListModalProps) {
const { t } = useTranslation();
@@ -60,7 +64,16 @@ export default function ClientHwidListModal({
okText={t('delete')}
cancelText={t('cancel')}
>
<Button danger loading={clearing} disabled={hwids.length === 0}>
<Button
danger
loading={clearing}
disabled={
loading ||
blockingId !== null ||
deletingId !== null ||
!hwids.some((entry) => !entry.blocked)
}
>
{t('pages.clients.clearAll')}
</Button>
</Popconfirm>,
@@ -69,6 +82,9 @@ export default function ClientHwidListModal({
</Button>,
]}
>
<Typography.Paragraph type="secondary">
{t('pages.clients.hwidBlockHint')}
</Typography.Paragraph>
{hwids.length > 0 ? (
<div style={{ maxHeight: 360, overflowY: 'auto' }}>
{hwids.map((entry) => (
@@ -86,6 +102,7 @@ export default function ClientHwidListModal({
<Typography.Text strong>
{entry.deviceModel || entry.userAgent || t('pages.clients.hwidDevice')}
</Typography.Text>
{entry.blocked && <Tag color="red">{t('pages.clients.hwidBlocked')}</Tag>}
<br />
<Typography.Text type="secondary">
{[entry.deviceOs, entry.osVersion].filter(Boolean).join(' ')}
@@ -115,6 +132,29 @@ export default function ClientHwidListModal({
</>
)}
</div>
<Popconfirm
title={t(
entry.blocked
? 'pages.clients.unblockHwidConfirm'
: 'pages.clients.blockHwidConfirm',
)}
onConfirm={() => onSetBlocked(entry.id, !entry.blocked)}
okType={entry.blocked ? 'primary' : 'danger'}
okText={t(entry.blocked ? 'pages.clients.unblockHwid' : 'pages.clients.blockHwid')}
cancelText={t('cancel')}
>
<Button
danger={!entry.blocked}
size="small"
icon={
entry.blocked ? <UnlockOutlined aria-hidden /> : <StopOutlined aria-hidden />
}
loading={blockingId === entry.id}
disabled={clearing || loading || deletingId !== null || blockingId !== null}
>
{t(entry.blocked ? 'pages.clients.unblockHwid' : 'pages.clients.blockHwid')}
</Button>
</Popconfirm>
<Popconfirm
title={t('pages.clients.deleteHwidConfirm')}
onConfirm={() => onDelete(entry.id)}
@@ -129,6 +169,13 @@ export default function ClientHwidListModal({
aria-label={t('pages.clients.deleteHwid')}
icon={<DeleteOutlined aria-hidden />}
loading={deletingId === entry.id}
disabled={
entry.blocked ||
clearing ||
loading ||
blockingId !== null ||
deletingId !== null
}
/>
</Popconfirm>
</div>
@@ -0,0 +1,268 @@
import { useTranslation } from 'react-i18next';
import { Modal, Spin, Table, Tag, Typography } from 'antd';
import { useClientUsageHistoryQuery } from '@/api/queries/useClientUsageHistoryQuery';
import { useDatepicker } from '@/hooks/useDatepicker';
import { IntlUtil, SizeFormatter } from '@/utils';
interface ClientUsageHistoryModalProps {
open: boolean;
email?: string;
zIndex?: number;
onClose: () => void;
}
// Reason label for each closed traffic window; unknown reasons stay raw so a
// future reason still renders instead of blanking out.
const REASON_KEYS: Record<string, string> = {
reset: 'pages.clients.reasonReset',
renew: 'pages.clients.reasonRenew',
earlier: 'pages.clients.reasonEarlier',
};
// Human labels for the change-log field names; unknown fields fall back to the
// raw key so a future field still renders instead of blanking out.
const FIELD_KEYS: Record<string, string> = {
name: 'pages.clients.fieldName',
subId: 'pages.clients.fieldSubId',
expiry: 'pages.clients.fieldExpiry',
dataLimit: 'pages.clients.fieldDataLimit',
enable: 'pages.clients.fieldEnable',
renewalPlan: 'pages.clients.fieldRenewalPlan',
limitIp: 'pages.clients.fieldLimitIp',
limitHwid: 'pages.clients.fieldLimitHwid',
adTag: 'pages.clients.fieldAdTag',
group: 'pages.clients.fieldGroup',
};
function fieldLabel(t: (key: string) => string, field: string): string {
const key = FIELD_KEYS[field];
return key ? t(key) : field;
}
function changeValueText(field: string, value: string, formatDate: (ts: number) => string): string {
if (value === '') return '—';
if (field === 'expiry') {
const n = Number(value);
if (Number.isFinite(n) && n > 0) return formatDate(n);
} else if (field === 'dataLimit') {
const n = Number(value);
if (Number.isFinite(n)) return SizeFormatter.sizeFormat(n);
}
return value;
}
export default function ClientUsageHistoryModal({
open,
email,
zIndex,
onClose,
}: ClientUsageHistoryModalProps) {
const { t } = useTranslation();
const { data: history, isFetching, isError } = useClientUsageHistoryQuery(email, open);
const { datepicker } = useDatepicker();
const formatDate = (ts: number) => IntlUtil.formatDate(ts, datepicker);
const bytesCell = (value: number) => SizeFormatter.sizeFormat(value);
const nodeColumns = [
{
title: t('pages.clients.node'),
dataIndex: 'nodeName',
key: 'nodeName',
render: (value: string, row: { nodeId: number }) => value || `#${row.nodeId}`,
},
{
title: t('pages.clients.upload'),
dataIndex: 'up',
key: 'up',
width: 140,
align: 'right' as const,
render: bytesCell,
},
{
title: t('pages.clients.download'),
dataIndex: 'down',
key: 'down',
width: 140,
align: 'right' as const,
render: bytesCell,
},
];
const windowColumns = [
{
title: t('pages.clients.time'),
dataIndex: 'at',
key: 'at',
width: 160,
render: formatDate,
},
{
title: t('pages.clients.upload'),
dataIndex: 'up',
key: 'up',
width: 110,
align: 'right' as const,
render: bytesCell,
},
{
title: t('pages.clients.download'),
dataIndex: 'down',
key: 'down',
width: 110,
align: 'right' as const,
render: bytesCell,
},
{
title: t('pages.clients.reason'),
dataIndex: 'reason',
key: 'reason',
width: 90,
render: (value: string) => <Tag>{REASON_KEYS[value] ? t(REASON_KEYS[value]) : value}</Tag>,
},
];
const changeColumns = [
{
title: t('pages.clients.time'),
dataIndex: 'at',
key: 'at',
width: 160,
render: formatDate,
},
{
title: t('pages.clients.field'),
dataIndex: 'field',
key: 'field',
width: 100,
render: (value: string) => fieldLabel(t, value),
},
{
title: t('pages.clients.oldValue'),
dataIndex: 'oldValue',
key: 'oldValue',
render: (value: string, row: { field: string }) =>
changeValueText(row.field, value, formatDate),
},
{
title: t('pages.clients.newValue'),
dataIndex: 'newValue',
key: 'newValue',
render: (value: string, row: { field: string }) =>
changeValueText(row.field, value, formatDate),
},
{
title: t('pages.clients.source'),
dataIndex: 'source',
key: 'source',
width: 90,
render: (value: string) => <Tag>{value}</Tag>,
},
];
const hasContent =
history !== undefined &&
(history.lifetimeUp > 0 ||
history.lifetimeDown > 0 ||
history.windows.length > 0 ||
history.nodes.length > 0 ||
history.changes.length > 0);
return (
<Modal
open={open}
title={`${t('pages.clients.usageHistory')}${email ? ` — ${email}` : ''}`}
width={720}
zIndex={zIndex}
onCancel={onClose}
footer={null}
destroyOnHidden
>
{isFetching ? (
<div style={{ padding: 48, textAlign: 'center' }}>
<Spin />
</div>
) : isError ? (
<Typography.Text type="secondary">{t('pages.clients.historyError')}</Typography.Text>
) : !hasContent ? (
<Typography.Text type="secondary">{t('pages.clients.noUsageHistory')}</Typography.Text>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<section>
<Typography.Title level={5} style={{ marginBottom: 8 }}>
{t('pages.clients.lifetimeTraffic')}
</Typography.Title>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<tbody>
<tr>
<td style={{ padding: '2px 12px 2px 0' }}>{t('pages.clients.upload')}</td>
<td style={{ textAlign: 'right' }}>
{SizeFormatter.sizeFormat(history!.lifetimeUp)}
</td>
<td style={{ padding: '2px 12px' }}>{t('pages.clients.download')}</td>
<td style={{ textAlign: 'right' }}>
{SizeFormatter.sizeFormat(history!.lifetimeDown)}
</td>
</tr>
<tr>
<td colSpan={4} style={{ color: 'var(--ant-color-text-secondary)' }}>
{t('pages.clients.currentCycle')}: ↑{' '}
{SizeFormatter.sizeFormat(history!.currentUp)} / ↓{' '}
{SizeFormatter.sizeFormat(history!.currentDown)}
</td>
</tr>
</tbody>
</table>
</section>
{history!.nodes.length > 0 && (
<section>
<Typography.Title level={5} style={{ marginBottom: 8 }}>
{t('pages.clients.usageByNode')}
</Typography.Title>
<Table
rowKey="nodeId"
size="small"
columns={nodeColumns}
dataSource={history!.nodes}
pagination={false}
/>
</section>
)}
{history!.windows.length > 0 && (
<section>
<Typography.Title level={5} style={{ marginBottom: 8 }}>
{t('pages.clients.pastCycles')}
</Typography.Title>
<div style={{ maxHeight: 200, overflowY: 'auto' }}>
<Table
rowKey="id"
size="small"
columns={windowColumns}
dataSource={history!.windows}
pagination={false}
/>
</div>
</section>
)}
{history!.changes.length > 0 && (
<section>
<Typography.Title level={5} style={{ marginBottom: 8 }}>
{t('pages.clients.changes')}
</Typography.Title>
<div style={{ maxHeight: 240, overflowY: 'auto' }}>
<Table
rowKey="id"
size="small"
columns={changeColumns}
dataSource={history!.changes}
pagination={false}
/>
</div>
</section>
)}
</div>
)}
</Modal>
);
}
@@ -14,6 +14,7 @@ import {
CopyOutlined,
DashboardOutlined,
DatabaseOutlined,
DesktopOutlined,
DiscordOutlined,
ExportOutlined,
FileTextOutlined,
@@ -36,7 +37,7 @@ import { ClipboardManager, HttpUtil, SizeFormatter } from '@/utils';
import { activateOnKey } from '@/utils/a11y';
import { useInboundOptions } from '@/api/queries/useInboundOptions';
import { useAllSettings } from '@/api/queries/useAllSettings';
import { useTheme } from '@/hooks/useTheme';
import { themeModeKey, useTheme } from '@/hooks/useTheme';
import { PANEL_ROUTES } from '@/routes/panelRoutes';
import type { ClientRecord, InboundOption } from '@/schemas/client';
import { commandPaletteStore, useCommandPalette } from './useCommandPalette';
@@ -90,7 +91,7 @@ export default function CommandPalette() {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const navigate = useNavigate();
const { isDark, isUltra, toggleTheme, toggleUltra, antdThemeConfig } = useTheme();
const { mode, isDark, isUltra, cycleTheme: advanceTheme, antdThemeConfig } = useTheme();
const { isOpen, close } = useCommandPalette();
const { allSetting } = useAllSettings();
const { data: inbounds = [] } = useInboundOptions();
@@ -240,17 +241,9 @@ export default function CommandPalette() {
}, [close, messageApi, t]);
const cycleTheme = useCallback(() => {
if (!isDark) {
toggleTheme();
if (isUltra) toggleUltra();
} else if (!isUltra) {
toggleUltra();
} else {
toggleUltra();
toggleTheme();
}
advanceTheme();
close();
}, [isDark, isUltra, toggleTheme, toggleUltra, close]);
}, [advanceTheme, close]);
const trimmedQuery = query.trim();
const isDebouncing = isOpen && trimmedQuery.length > 0 && trimmedQuery !== debouncedQuery;
@@ -551,9 +544,16 @@ export default function CommandPalette() {
id: 'act-cycle-theme',
category: 'actions',
title: t('menu.theme'),
subtitle: isUltra ? 'Ultra Dark' : isDark ? 'Dark' : 'Light',
keywords: ['theme', 'light', 'dark', 'ultra'],
icon: isDark ? <SunOutlined aria-hidden /> : <MoonOutlined aria-hidden />,
subtitle: t(themeModeKey(mode, isUltra)),
keywords: ['theme', 'light', 'dark', 'ultra', 'system', 'auto'],
icon:
mode === 'system' ? (
<DesktopOutlined aria-hidden />
) : isDark ? (
<MoonOutlined aria-hidden />
) : (
<SunOutlined aria-hidden />
),
action: cycleTheme,
},
{
@@ -589,6 +589,7 @@ export default function CommandPalette() {
query,
clientSearch,
inbounds,
mode,
isDark,
isUltra,
allSetting.subURI,

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