mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-17 02:25:02 +03:00
Compare commits
69 Commits
v3.4.2
..
5a7b3b7370
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a7b3b7370 | |||
| 9d1a21b484 | |||
| 0753f5ee83 | |||
| 837cf5f24e | |||
| b1fa76f9b6 | |||
| b6873c7a73 | |||
| b6183271da | |||
| 11e45e81b6 | |||
| 579a9daaa0 | |||
| 0add63984f | |||
| b6d1caf95d | |||
| 1bf9e5d544 | |||
| 26e88c7b10 | |||
| a0989e0f4d | |||
| 07d66aa6dc | |||
| b177e30714 | |||
| e11e587c60 | |||
| 5c725df702 | |||
| d105b2741c | |||
| 05cb70d8a8 | |||
| 323cf09d10 | |||
| 1f04912b6f | |||
| 220dcb1579 | |||
| a13a79b230 | |||
| ff3bd63656 | |||
| 052dd85ad3 | |||
| b2ceb854f5 | |||
| dd4f55f690 | |||
| f90e4a6962 | |||
| dbdecda03f | |||
| 6e0067fca3 | |||
| ed95acdd47 | |||
| 1afab47f04 | |||
| 258d8b7344 | |||
| 9f760cf0fa | |||
| 1bf6f606bc | |||
| ccd56a56a8 | |||
| 7a844682b3 | |||
| 6626bf4a07 | |||
| c0df365524 | |||
| 5361b56e5e | |||
| 9e13b32c34 | |||
| ade74eb321 | |||
| 97e2c9e7ba | |||
| 5e8327e728 | |||
| 7c12700c7d | |||
| c0d17e132d | |||
| fc5be5b9e4 | |||
| c3cc8b4374 | |||
| 97588dd0b9 | |||
| fb1d055b06 | |||
| 4fc301682f | |||
| 28f7690224 | |||
| 92303094fd | |||
| fb3a1559b2 | |||
| a335456cd3 | |||
| 9a3a12b260 | |||
| 4d6f2ddd97 | |||
| 62f303905e | |||
| c8ef1b1f68 | |||
| 64c306037f | |||
| 8dd3b31ee8 | |||
| e5b56c9444 | |||
| 1153d5db8c | |||
| 539bcc897c | |||
| 273f88721e | |||
| 1f2e3e1447 | |||
| 49773c18de | |||
| 427613b308 |
+171
-13
@@ -1,19 +1,177 @@
|
||||
# This file serves a dual purpose:
|
||||
# 1. Developer Bootstrap: The active (uncommented) variables directly below
|
||||
# configure a safe, unprivileged local environment for 'go run .'.
|
||||
# This allows 'cp .env.example .env' to work out-of-the-box without root.
|
||||
# 2. Production Reference: All available XUI_* configuration options are
|
||||
# documented and commented out in the reference section further below.
|
||||
#
|
||||
# 3x-ui reads its runtime configuration from XUI_* environment variables.
|
||||
# On a script install, the installer writes them to the service environment file
|
||||
# (/etc/default/x-ui, /etc/conf.d/x-ui, or /etc/sysconfig/x-ui depending on the distro).
|
||||
# For Docker, you set them in docker-compose.yml or via 'docker run -e'.
|
||||
#
|
||||
# Defaults are sensible — set only what you need to change, then restart:
|
||||
# systemctl restart x-ui
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# LOCAL DEVELOPMENT OVERRIDES (ACTIVE BY DEFAULT)
|
||||
# ------------------------------------------------------------------------------
|
||||
XUI_DEBUG=true
|
||||
XUI_DB_FOLDER=x-ui
|
||||
XUI_LOG_FOLDER=x-ui
|
||||
XUI_BIN_FOLDER=x-ui
|
||||
XUI_INIT_WEB_BASE_PATH=/
|
||||
# XUI_PORT=8080
|
||||
|
||||
# Optional tunnel health monitor (disabled by default). It periodically probes a
|
||||
# URL and restarts xray-core after repeated failures. Point XUI_TUNNEL_HEALTH_PROXY
|
||||
# at a local xray inbound so the probe tests the tunnel; without it the probe only
|
||||
# checks host connectivity and a restart will not fix host network issues. A restart
|
||||
# drops every connected client.
|
||||
# XUI_TUNNEL_HEALTH_MONITOR=true
|
||||
# XUI_TUNNEL_HEALTH_PROXY=socks5://127.0.0.1:1080
|
||||
# XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
|
||||
# XUI_TUNNEL_HEALTH_INTERVAL=30s
|
||||
# XUI_TUNNEL_HEALTH_TIMEOUT=10s
|
||||
# XUI_TUNNEL_HEALTH_FAILURES=3
|
||||
# XUI_TUNNEL_HEALTH_COOLDOWN=5m
|
||||
# ==============================================================================
|
||||
# REFERENCE CONFIGURATION (ALL OPTIONS)
|
||||
# ==============================================================================
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Database
|
||||
# ------------------------------------------------------------------------------
|
||||
# Backend database type: sqlite, or postgres (also accepts postgresql / pg)
|
||||
# Default: sqlite
|
||||
#XUI_DB_TYPE=sqlite
|
||||
|
||||
# Folder for the SQLite database file (x-ui.db)
|
||||
# Default: /etc/x-ui (Overridden to 'x-ui' in the development block above)
|
||||
#XUI_DB_FOLDER=/etc/x-ui
|
||||
|
||||
# PostgreSQL connection string (used when XUI_DB_TYPE=postgres)
|
||||
# Example: postgres://user:password@localhost:5432/dbname?sslmode=disable
|
||||
#XUI_DB_DSN=
|
||||
|
||||
# Max open connections in the PostgreSQL pool
|
||||
#XUI_DB_MAX_OPEN_CONNS=
|
||||
|
||||
# Max idle connections in the PostgreSQL pool
|
||||
#XUI_DB_MAX_IDLE_CONNS=
|
||||
|
||||
# PostgreSQL Docker Container Settings
|
||||
# Default credentials used if you are running PostgreSQL via docker-compose
|
||||
#POSTGRES_USER=xui
|
||||
#POSTGRES_PASSWORD=xui
|
||||
#POSTGRES_DB=xui
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Panel
|
||||
# ------------------------------------------------------------------------------
|
||||
# Override the panel port (1–65535). Takes precedence over the stored setting.
|
||||
#XUI_PORT=
|
||||
|
||||
# Initial web base path on FIRST launch (e.g., /panel)
|
||||
# Default: /
|
||||
#XUI_INIT_WEB_BASE_PATH=/
|
||||
|
||||
# Enable Fail2ban-based IP-limit enforcement
|
||||
# Default: true
|
||||
#XUI_ENABLE_FAIL2BAN=true
|
||||
|
||||
# Skip the HSTS header — set true when TLS is terminated by a reverse proxy
|
||||
# Default: false
|
||||
#XUI_SKIP_HSTS=false
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Logging & binaries
|
||||
# ------------------------------------------------------------------------------
|
||||
# Logging level: debug, info, notice, warning, or error
|
||||
# Default: info
|
||||
#XUI_LOG_LEVEL=info
|
||||
|
||||
# Debug mode. Forces log level to debug, enables Gin debug mode,
|
||||
# and ensures frontend assets are served directly from disk (see CLAUDE.md).
|
||||
# Default: false (Overridden to 'true' in the development block at the top)
|
||||
#XUI_DEBUG=false
|
||||
|
||||
# Log output directory
|
||||
# Default: /var/log/x-ui (Overridden to 'x-ui' in the development block above)
|
||||
#XUI_LOG_FOLDER=/var/log/x-ui
|
||||
|
||||
# Folder for the Xray-core binary and geosite/geoip files
|
||||
# Default: bin (Overridden to 'x-ui' in the development block above)
|
||||
#XUI_BIN_FOLDER=bin
|
||||
|
||||
# Legacy Path Settings
|
||||
# Main installation folder (Default: /usr/local/x-ui for Linux, /app for Docker)
|
||||
#XUI_MAIN_FOLDER=/usr/local/x-ui
|
||||
# Path to the systemd service file (Default: /etc/systemd/system)
|
||||
#XUI_SERVICE=/etc/systemd/system
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Memory & profiling
|
||||
# ------------------------------------------------------------------------------
|
||||
# Go GC target percentage; lower = less RAM, slightly more CPU.
|
||||
# Default: 75
|
||||
#XUI_GOGC=
|
||||
|
||||
# Minutes between FreeOSMemory calls; 0 disables.
|
||||
# Default: 10
|
||||
#XUI_MEMORY_RELEASE_INTERVAL=
|
||||
|
||||
# Go soft memory limit in MiB
|
||||
#XUI_MEMORY_LIMIT=
|
||||
|
||||
# Go-syntax soft limit (e.g., 400MiB); takes precedence over XUI_MEMORY_LIMIT
|
||||
#GOMEMLIMIT=
|
||||
|
||||
# Expose pprof profiling on 127.0.0.1:6060
|
||||
# Default: false
|
||||
#XUI_PPROF=false
|
||||
|
||||
# Automatically set to 'true' inside the official Docker image.
|
||||
# Consumed by internal scripts (x-ui.sh) to detect the environment.
|
||||
# There is normally no need to set or toggle this variable manually.
|
||||
# Default: false (automatically 'true' in Docker environments)
|
||||
#XUI_IN_DOCKER=false
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Xray
|
||||
# ------------------------------------------------------------------------------
|
||||
# Force VMess AEAD
|
||||
# Default: false
|
||||
#XRAY_VMESS_AEAD_FORCED=false
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Tunnel health monitor
|
||||
# ------------------------------------------------------------------------------
|
||||
# Optional watchdog: probes a URL (optionally through a local Xray inbound)
|
||||
# and restarts Xray after repeated failures. A restart drops all connected clients.
|
||||
# Default: false
|
||||
#XUI_TUNNEL_HEALTH_MONITOR=false
|
||||
|
||||
# Proxy to send the probe through, e.g., socks5://127.0.0.1:1080
|
||||
# Empty = only checks host connectivity
|
||||
#XUI_TUNNEL_HEALTH_PROXY=
|
||||
|
||||
# URL to probe
|
||||
# Default: https://www.cloudflare.com/cdn-cgi/trace
|
||||
#XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
|
||||
|
||||
# Interval between probes
|
||||
# Default: 30s
|
||||
#XUI_TUNNEL_HEALTH_INTERVAL=30s
|
||||
|
||||
# Per-probe timeout
|
||||
# Default: 10s
|
||||
#XUI_TUNNEL_HEALTH_TIMEOUT=10s
|
||||
|
||||
# Consecutive failures before a restart
|
||||
# Default: 3
|
||||
#XUI_TUNNEL_HEALTH_FAILURES=3
|
||||
|
||||
# Minimum delay between restarts
|
||||
# Default: 5m
|
||||
#XUI_TUNNEL_HEALTH_COOLDOWN=5m
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Unattended install
|
||||
# ------------------------------------------------------------------------------
|
||||
# Set to 1 (or run with no TTY) to install with zero prompts.
|
||||
# Generated credentials will be written to /etc/x-ui/install-result.env
|
||||
#XUI_NONINTERACTIVE=1
|
||||
|
||||
@@ -30,7 +30,8 @@ jobs:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
allowed_non_write_users: "*"
|
||||
claude_args: |
|
||||
--model claude-sonnet-4-6
|
||||
--model claude-sonnet-5
|
||||
--effort xhigh
|
||||
--max-turns 300
|
||||
--allowedTools "Bash(gh:*),Read,Glob,Grep"
|
||||
prompt: |
|
||||
@@ -282,7 +283,8 @@ jobs:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
allowed_non_write_users: "*"
|
||||
claude_args: |
|
||||
--model claude-opus-4-8
|
||||
--model claude-sonnet-5
|
||||
--effort max
|
||||
--max-turns 250
|
||||
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep"
|
||||
prompt: |
|
||||
@@ -500,7 +502,8 @@ jobs:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
claude_args: |
|
||||
--model claude-opus-4-8
|
||||
--model claude-sonnet-5
|
||||
--effort max
|
||||
--max-turns 250
|
||||
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep,Edit,Write"
|
||||
--append-system-prompt "You are replying to an @claude mention in the MHSanaei/3x-ui repository, an open-source web panel for managing Xray-core servers. The full repo source is checked out in the working directory; use Read, Glob and Grep to open and verify the relevant files before stating any default, path, flag, option name, or behavior.
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
name: Deploy Smoke Tests
|
||||
|
||||
# Container smoke test for the unattended (cloud-init) install path.
|
||||
# Runs only when the install/deploy assets change.
|
||||
# Runs when the install/deploy assets change on a branch push or PR, and
|
||||
# again after a release-tag build finishes uploading its assets — pinned to
|
||||
# that tag, so the green result verifies the release actually being shipped.
|
||||
# Tag pushes must NOT trigger the unpinned job directly: at that moment
|
||||
# releases/latest still points at the previous release (#5756), and a `paths`
|
||||
# filter alone cannot exclude them because a brand-new tag ref has no diff
|
||||
# base, so it runs on every tag push.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- "**"
|
||||
paths:
|
||||
- "install.sh"
|
||||
- "deploy/**"
|
||||
@@ -14,12 +22,16 @@ on:
|
||||
- "install.sh"
|
||||
- "deploy/**"
|
||||
- ".github/workflows/smoke.yml"
|
||||
workflow_run:
|
||||
workflows: ["Release 3X-UI"]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
noninteractive-install:
|
||||
if: github.event_name != 'workflow_run'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -30,3 +42,25 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
- name: Non-interactive install smoke test
|
||||
run: bash deploy/test/smoke-noninteractive.sh
|
||||
|
||||
release-tag-install:
|
||||
if: >-
|
||||
github.event_name == 'workflow_run' &&
|
||||
github.event.workflow_run.conclusion == 'success' &&
|
||||
github.event.workflow_run.event == 'push' &&
|
||||
startsWith(github.event.workflow_run.head_branch, 'v') &&
|
||||
contains(github.event.workflow_run.head_branch, '.')
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runner: [ubuntu-latest, ubuntu-24.04-arm]
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event.workflow_run.head_sha }}
|
||||
- name: Pinned release install smoke test
|
||||
env:
|
||||
XUI_SMOKE_VERSION: ${{ github.event.workflow_run.head_branch }}
|
||||
run: bash deploy/test/smoke-noninteractive.sh "$XUI_SMOKE_VERSION"
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
.idea/
|
||||
.vscode/
|
||||
.cursor/
|
||||
.claude/
|
||||
.claude/*
|
||||
.cache/
|
||||
.sync*
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
Operational guide for AI agents working in this repo. Long-form human docs:
|
||||
`CONTRIBUTING.md` (setup, testing philosophy) and `frontend/README.md`.
|
||||
Read those before large changes. This file is the short, must-follow version.
|
||||
For a deep navigation map (request lifecycle, cron-job table, symptom → file
|
||||
index, layering rules), read `docs/architecture.md` on demand — do not guess
|
||||
file locations when it can answer in one hop.
|
||||
|
||||
## Stack
|
||||
- Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
|
||||
|
||||
@@ -69,5 +69,14 @@ EOF
|
||||
fail2ban-client -x start
|
||||
fi
|
||||
|
||||
# Certificate auto-renewal: acme.sh (installed by the panel's SSL menu) relies
|
||||
# on a root crontab entry, but the crontab is lost when the container is
|
||||
# recreated and crond was never started. Re-register the job and run crond so
|
||||
# renewals actually fire; mount /root/.acme.sh as a volume to keep acme state.
|
||||
if [ -f /root/.acme.sh/acme.sh ]; then
|
||||
/root/.acme.sh/acme.sh --install-cronjob >/dev/null 2>&1
|
||||
crond
|
||||
fi
|
||||
|
||||
# Run x-ui
|
||||
exec /app/x-ui
|
||||
|
||||
@@ -7,35 +7,51 @@
|
||||
# * /etc/x-ui/install-result.env exists (mode 600) with random, non-default creds
|
||||
# * the panel reports hasDefaultCredential: false (no admin/admin remains)
|
||||
# * the panel HTTP server actually serves on the generated port/base path
|
||||
# * with a [version] argument: the installed binary reports exactly that version
|
||||
#
|
||||
# Requires Docker and network access (install.sh downloads the released binary).
|
||||
# Usage: bash deploy/test/smoke-noninteractive.sh
|
||||
# Usage: bash deploy/test/smoke-noninteractive.sh [version]
|
||||
# With no argument install.sh resolves releases/latest. Pass an explicit tag
|
||||
# (e.g. v3.4.2) to verify that exact release — the tag-triggered CI run does
|
||||
# this so it cannot silently validate the previous release (#5756).
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
|
||||
XUI_SMOKE_VERSION="${1:-}"
|
||||
|
||||
if ! command -v docker > /dev/null 2>&1; then
|
||||
echo "ERROR: docker is required for this smoke test." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "== non-interactive install smoke test (image: $IMAGE) =="
|
||||
echo "== non-interactive install smoke test (image: $IMAGE, version: ${XUI_SMOKE_VERSION:-latest}) =="
|
||||
|
||||
docker run --rm \
|
||||
-v "${REPO_ROOT}/install.sh:/root/install.sh:ro" \
|
||||
-e XUI_NONINTERACTIVE=1 \
|
||||
-e XUI_SSL_MODE=none \
|
||||
-e XUI_SMOKE_VERSION="$XUI_SMOKE_VERSION" \
|
||||
-e DEBIAN_FRONTEND=noninteractive \
|
||||
"$IMAGE" bash -euo pipefail -c '
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq curl tar openssl ca-certificates > /dev/null
|
||||
|
||||
echo "--- running install.sh piped (no TTY) ---"
|
||||
echo "--- running install.sh piped (no TTY), version: ${XUI_SMOKE_VERSION:-latest} ---"
|
||||
# Piping guarantees stdin is not a TTY, exercising the auto non-interactive path.
|
||||
cat /root/install.sh | bash
|
||||
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
|
||||
cat /root/install.sh | bash -s -- "$XUI_SMOKE_VERSION"
|
||||
else
|
||||
cat /root/install.sh | bash
|
||||
fi
|
||||
|
||||
echo "--- assertions ---"
|
||||
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
|
||||
installed=$(/usr/local/x-ui/x-ui -v)
|
||||
[ "$installed" = "${XUI_SMOKE_VERSION#v}" ] \
|
||||
|| { echo "FAIL: installed version $installed, want ${XUI_SMOKE_VERSION#v}"; exit 1; }
|
||||
fi
|
||||
|
||||
RESULT=/etc/x-ui/install-result.env
|
||||
test -f "$RESULT" || { echo "FAIL: $RESULT missing"; exit 1; }
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ services:
|
||||
volumes:
|
||||
- $PWD/db/:/etc/x-ui/
|
||||
- $PWD/cert/:/root/cert/
|
||||
# Persists acme.sh state so certificate auto-renewal survives container
|
||||
# recreation (the entrypoint re-registers the renewal cron job from it).
|
||||
- $PWD/acme/:/root/.acme.sh/
|
||||
environment:
|
||||
XRAY_VMESS_AEAD_FORCED: "false"
|
||||
XUI_ENABLE_FAIL2BAN: "true"
|
||||
|
||||
@@ -0,0 +1,581 @@
|
||||
# 3x-ui — Architecture & Code Map
|
||||
|
||||
> Navigation map for contributors and AI coding agents (referenced from `CLAUDE.md`).
|
||||
> Goal: jump to the right file in one hop instead of grepping the whole tree.
|
||||
> Tracks the `main` branch — paths reflect the latest changes, so verify against the live
|
||||
> tree rather than a pinned release (Go module `github.com/mhsanaei/3x-ui/v3`).
|
||||
>
|
||||
> **How to use this file:** read "Mental model" + "Request lifecycle" first, then
|
||||
> use the **Symptom → File index** to locate work. Respect the **Layering rules**
|
||||
> when adding code. Verify with the commands in **Build / Test / Lint**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Mental model (the 30-second version)
|
||||
|
||||
3x-ui is a **web control panel for [Xray-core](https://github.com/XTLS/Xray-core)**. The Go
|
||||
backend is the source of truth: it stores inbounds/clients/settings in a DB, renders an
|
||||
Xray JSON config from that state, supervises the Xray child process, and exposes a REST +
|
||||
WebSocket API. A React SPA (built by Vite, embedded into the Go binary) is the UI. A second,
|
||||
separate HTTP server serves **subscription links** to end users.
|
||||
|
||||
The panel supervises **two managed child processes**: Xray-core itself and — when MTProto
|
||||
inbounds exist — the `mtg` Telegram-proxy binary (`internal/mtproto/`).
|
||||
|
||||
Servers and processes, all launched from `main.go`:
|
||||
|
||||
| Server / process | Package | Purpose | Default port |
|
||||
|---|---|---|---|
|
||||
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
|
||||
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
|
||||
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
|
||||
| **mtg** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds | per inbound |
|
||||
|
||||
Two key ideas that explain most of the complexity:
|
||||
|
||||
1. **The DB → Xray config pipeline.** Inbounds/clients live in the DB. On every change the
|
||||
backend regenerates the Xray config and applies it — preferring a *hot diff* (live gRPC
|
||||
API mutation) over a full process restart. See §5.1.
|
||||
2. **The Runtime abstraction (multi-node).** A panel can manage remote "nodes" (other 3x-ui
|
||||
instances). Every state-changing inbound/client operation is dispatched through a
|
||||
`runtime.Runtime` interface that is either **`Local`** (this box's Xray gRPC API) or
|
||||
**`Remote`** (HTTPS call to a child node, with `verify`/`skip`/`pin`/`mtls` TLS modes).
|
||||
This is the single most important abstraction in the project. See §5.2.
|
||||
|
||||
---
|
||||
|
||||
## 2. Tech stack
|
||||
|
||||
**Backend (Go 1.26):**
|
||||
- Web framework: **Gin** (`gin-gonic/gin`) + sessions (cookie store), gzip.
|
||||
- ORM: **GORM** with **SQLite** (default) or **PostgreSQL** (`XUI_DB_TYPE=postgres`).
|
||||
- Scheduler: **robfig/cron/v3** (seconds-precision) for all background jobs.
|
||||
- Xray: **xtls/xray-core** vendored as a library; the panel talks to the running core over
|
||||
its **gRPC API** and also shells out to manage the process.
|
||||
- Telegram bot: **mymmrac/telego**. i18n: **nicksnyder/go-i18n**.
|
||||
- Misc: gorilla/websocket, gopsutil (system stats), go-qrcode, gotp (2FA TOTP).
|
||||
|
||||
**Frontend (`frontend/`):**
|
||||
- **React 19** + **Ant Design 6** + **Vite 8** + **TypeScript**.
|
||||
- Data layer: **TanStack Query** (`@tanstack/react-query`) over **axios**; **Zod 4** schemas.
|
||||
- Router: **react-router-dom 7**. Charts: **recharts**. Editor: **CodeMirror 6**.
|
||||
- **Build output goes to `internal/web/dist/`** (see `vite.config.js` → `outDir`) and is
|
||||
embedded into the Go binary with `go:embed`. Three HTML entries: `index.html` (panel SPA),
|
||||
`login.html`, `subpage.html`. The Go server serves the SPA; there is no separate frontend
|
||||
deployment.
|
||||
|
||||
**Important:** the legacy Go-template UI and `web/assets/` are **gone**. All HTML/JS comes
|
||||
from the embedded Vite `dist/`. Don't look for `.html` templates in `internal/web`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Request lifecycle (follow the data)
|
||||
|
||||
### 3.1 Admin API request (e.g. "add a client")
|
||||
|
||||
```
|
||||
Browser (React, axios)
|
||||
→ POST {basePath}/panel/api/...
|
||||
→ Gin engine (internal/web/web.go: initRouter)
|
||||
→ middleware chain: SecurityHeaders → MaxBodyBytes (10 MiB; importDB exempt)
|
||||
→ [DomainValidator, if webDomain set] → gzip → sessions("3x-ui")
|
||||
→ base-path/cache-control context → Localizer
|
||||
→ API routes add: ConfigEnvelope (zstd + SHA-256) → CSRF
|
||||
→ Controller (internal/web/controller/*.go) // HTTP concerns only: bind, validate, respond
|
||||
→ Service (internal/web/service/*.go) // business logic + transactions
|
||||
→ GORM → DB (internal/database) // persistence
|
||||
→ runtime.Runtime dispatch // apply to Xray (Local) or node (Remote)
|
||||
→ Local: internal/xray (gRPC API or config regen + restart)
|
||||
→ Remote: internal/web/runtime/remote.go → HTTPS → child node's API
|
||||
```
|
||||
|
||||
The controller layer is thin. **Business logic lives in services.** When something is wrong
|
||||
with *behavior*, the bug is almost always in a service file, not a controller.
|
||||
|
||||
### 3.2 Subscription request (end-user fetching their config)
|
||||
|
||||
```
|
||||
End user → GET {subPath}/{subId} (separate server, internal/sub)
|
||||
→ internal/sub/controller.go (routes: raw / JSON / Clash variants, feature-flagged)
|
||||
→ internal/sub/service.go (~2.5k lines — the link/config builder)
|
||||
→ reads inbounds+clients+hosts from DB, renders per-protocol share links /
|
||||
Clash YAML / JSON (Host rows can override address/SNI/path per inbound)
|
||||
```
|
||||
|
||||
### 3.3 Background work (cron jobs)
|
||||
|
||||
Scheduled in `internal/web/web.go` → `startTask()`. Each job is a struct in
|
||||
`internal/web/job/`. Examples: poll Xray traffic every 5s, check client IP limits every 10s,
|
||||
node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly). See §5.4.
|
||||
|
||||
---
|
||||
|
||||
## 4. Directory map (what lives where)
|
||||
|
||||
```
|
||||
3x-ui/
|
||||
├── main.go # Entry point: CLI (run / migrate / migrate-db / setting / cert),
|
||||
│ # bootstrap, signal handling, restart loop
|
||||
├── go.mod / go.sum # Go deps (module path ends in /v3)
|
||||
│
|
||||
├── internal/ # ALL backend Go code (private packages)
|
||||
│ ├── config/ # Env-var config: paths, DB kind/DSN, log level, version
|
||||
│ │ # Every XUI_* env var is read here (config.go)
|
||||
│ ├── database/
|
||||
│ │ ├── db.go # InitDB: connect, AutoMigrate, seeders (~1.4k lines). DB hotspot.
|
||||
│ │ ├── migrate_data.go # Data migrations (seeders/normalizers beyond AutoMigrate)
|
||||
│ │ ├── dialect.go # SQLite vs Postgres SQL differences
|
||||
│ │ ├── dump_sqlite.go # DB export/backup
|
||||
│ │ └── model/ # **ALL GORM models** (model.go ~1.1k lines + siblings:
|
||||
│ │ # node_client_traffic.go, node_client_ip.go,
|
||||
│ │ # client_global_traffic.go). ⭐ Start here for data shape.
|
||||
│ ├── eventbus/ # In-process pub/sub (buffered channel): outbound.down|up,
|
||||
│ │ # xray.crash, node.down|up, cpu.high, memory.high, login.attempt
|
||||
│ ├── tunnelmonitor/ # Optional tunnel health probe (XUI_TUNNEL_HEALTH_* env vars):
|
||||
│ │ # HTTP probe (default Cloudflare trace); repeated failures
|
||||
│ │ # trigger an Xray restart hook. Independent of panel settings.
|
||||
│ ├── xray/ # Xray-core integration (the proxy engine wrapper)
|
||||
│ │ ├── process.go # Spawn/supervise the Xray child process (~750 lines)
|
||||
│ │ ├── api.go # gRPC client to a running Xray (add/remove user, stats) (~800 lines)
|
||||
│ │ ├── hot_diff.go # ⭐ Compute minimal live changes to avoid full restart (~500 lines)
|
||||
│ │ ├── config.go # Xray config object model
|
||||
│ │ ├── inbound.go # Inbound JSON shaping
|
||||
│ │ ├── client_traffic.go # ClientTraffic model (persisted as client_traffics)
|
||||
│ │ ├── traffic.go # Traffic type helpers
|
||||
│ │ └── log_writer.go # Pipe Xray stdout/stderr into the panel logger
|
||||
│ │
|
||||
│ ├── web/ # The panel server
|
||||
│ │ ├── web.go # ⭐ Server bootstrap: initRouter (all routes) + startTask (all cron jobs)
|
||||
│ │ ├── controller/ # HTTP handlers (thin). One file per resource:
|
||||
│ │ │ ├── inbound.go # /panel/api/inbounds
|
||||
│ │ │ ├── client.go # /panel/api/clients (CRUD + bulk + ips + onlines)
|
||||
│ │ │ ├── group.go # client-group endpoints
|
||||
│ │ │ ├── node.go # /panel/api/nodes (multi-node management)
|
||||
│ │ │ ├── host.go # /panel/api/hosts (per-inbound subscription host overrides)
|
||||
│ │ │ ├── server.go # /panel/api/server (status, xray version, certs, logs, DB import/export)
|
||||
│ │ │ ├── setting.go # /panel/api/setting (settings + API tokens)
|
||||
│ │ │ ├── xray_setting.go # /panel/api/xray (raw Xray config editor, WARP/Nord)
|
||||
│ │ │ ├── api.go # /panel/api gateway (token auth, envelope + CSRF wiring)
|
||||
│ │ │ ├── index.go # login/logout/csrf/2FA
|
||||
│ │ │ ├── spa.go # SPA fallback for /panel UI routes
|
||||
│ │ │ └── websocket.go # WS upgrade endpoint
|
||||
│ │ ├── service/ # ⭐⭐ Business logic. This is where most real work happens.
|
||||
│ │ │ ├── inbound.go # Inbound CRUD core (~1.4k lines)
|
||||
│ │ │ ├── inbound_node.go # ⭐ Node sync for inbounds: reconcile, traffic merge (~1.1k lines)
|
||||
│ │ │ ├── inbound_traffic.go # Per-client traffic accounting (~1.1k lines)
|
||||
│ │ │ ├── inbound_clients.go # Client-within-inbound operations
|
||||
│ │ │ ├── inbound_sublink.go # Inbound-level subscription link helpers
|
||||
│ │ │ ├── inbound_migration.go # Inbound schema/format migrations
|
||||
│ │ │ ├── client_crud.go # Client create/read/update/delete
|
||||
│ │ │ ├── client_bulk.go # Bulk client ops (~1.6k lines)
|
||||
│ │ │ ├── client_inbound_apply.go # ⭐ Apply client changes to runtime (Local/Remote) (~1.2k lines)
|
||||
│ │ │ ├── client_groups.go # Client grouping
|
||||
│ │ │ ├── client_link.go # Per-client share-link generation
|
||||
│ │ │ ├── client_external_link.go # External links attached to clients
|
||||
│ │ │ ├── client_wireguard.go # WireGuard client specifics
|
||||
│ │ │ ├── client_paging.go # Server-side pagination/sort/filter for client lists
|
||||
│ │ │ ├── node.go # ⭐ NodeService: CRUD, probe, heartbeat, dirty-tracking (~1.1k lines)
|
||||
│ │ │ ├── node_mtls.go # Node mTLS certificate management (master side)
|
||||
│ │ │ ├── node_tree.go # Node hierarchy / descendants
|
||||
│ │ │ ├── host.go # Host rows (subscription output overrides)
|
||||
│ │ │ ├── server.go # ServerService: status, certs, xray install, DB ops (~2.2k lines)
|
||||
│ │ │ ├── setting.go # SettingService: all panel settings + defaults (~1.3k lines)
|
||||
│ │ │ ├── setting_mtls.go # mTLS settings (node hardening)
|
||||
│ │ │ ├── traffic_writer.go # Batched persistence of traffic deltas to the DB
|
||||
│ │ │ ├── xray.go # ⭐ XrayService: config gen + restart/hot-apply (~1.2k lines)
|
||||
│ │ │ ├── xray_setting.go # Raw Xray config persistence
|
||||
│ │ │ ├── xray_metrics.go # Xray observability metrics
|
||||
│ │ │ ├── metric_history.go # Historical system/xray metrics
|
||||
│ │ │ ├── reality_scan.go # REALITY target scanner
|
||||
│ │ │ ├── url_safety.go # Outbound URL validation (SSRF guards)
|
||||
│ │ │ ├── outbound_subscription.go# Outbound subscription (e.g. Warp/Nord provider configs)
|
||||
│ │ │ ├── port_conflict.go # Detect inbound port collisions
|
||||
│ │ │ ├── fallback.go # Xray fallback (SNI/ALPN routing on shared port)
|
||||
│ │ │ ├── email/ # Email notification service (SMTP)
|
||||
│ │ │ ├── integration/ # External providers: warp.go (Cloudflare WARP), nord.go (NordVPN)
|
||||
│ │ │ ├── outbound/ # Outbound config service
|
||||
│ │ │ ├── panel/ # Cross-cutting panel services:
|
||||
│ │ │ │ ├── panel.go # panel-level helpers
|
||||
│ │ │ │ ├── user.go # admin user auth (bcrypt)
|
||||
│ │ │ │ ├── api_token.go # API token CRUD (SHA-256 hashed)
|
||||
│ │ │ │ └── websocket.go # WS hub / push service
|
||||
│ │ │ └── tgbot/ # Telegram bot command handlers
|
||||
│ │ ├── runtime/ # ⭐⭐ The Local/Remote node abstraction (see §5.2)
|
||||
│ │ │ ├── runtime.go # the Runtime interface (the contract)
|
||||
│ │ │ ├── local.go # Local impl → this box's Xray gRPC API
|
||||
│ │ │ ├── remote.go # Remote impl → HTTPS calls to a child node
|
||||
│ │ │ ├── tls_client.go # per-node HTTP client: verify / skip / pin / mtls
|
||||
│ │ │ └── manager.go # RuntimeFor(nodeID) → picks Local or Remote
|
||||
│ │ ├── job/ # Cron job structs (one file per job — see §5.4)
|
||||
│ │ ├── middleware/ # Gin middleware: security.go (headers/HSTS), bodylimit.go,
|
||||
│ │ │ # domainValidator.go, validate.go (CSRF), config_envelope.go
|
||||
│ │ ├── global/ # Global singletons: web server + sub server handles, restart hook
|
||||
│ │ ├── network/ # Custom net listeners (e.g. proxy-protocol aware)
|
||||
│ │ ├── session/ # Session/cookie helpers
|
||||
│ │ ├── websocket/ # WS hub implementation
|
||||
│ │ ├── locale/ + translation/ # i18n middleware + 13 locale JSON catalogs
|
||||
│ │ ├── entity/ # Shared request/response DTOs
|
||||
│ │ └── dist/ # ⚠️ Vite build output, embedded via go:embed (generated — do not hand-edit)
|
||||
│ │
|
||||
│ ├── sub/ # The subscription server (separate from panel)
|
||||
│ │ ├── sub.go # server bootstrap
|
||||
│ │ ├── controller.go # routes for raw / JSON / Clash subscription formats
|
||||
│ │ ├── service.go # ⭐ The link/config builder (~2.5k lines — share-link logic lives here)
|
||||
│ │ ├── json_service.go # JSON subscription format
|
||||
│ │ ├── clash_service.go # Clash/Mihomo YAML format
|
||||
│ │ ├── clash_external.go # external Clash config integration
|
||||
│ │ ├── external_subscription.go / external_config.go # external sub import/aggregation
|
||||
│ │ ├── host_sub.go # Host-row overrides applied to subscription output
|
||||
│ │ ├── endpoint.go # subscription endpoint configuration
|
||||
│ │ ├── vless_route.go # VLESS route shaping
|
||||
│ │ ├── remark_vars.go # remark variable expansion
|
||||
│ │ └── links.go # link helpers
|
||||
│ │
|
||||
│ ├── mtproto/ # Embedded MTProto (Telegram) proxy: manager.go + per-OS
|
||||
│ │ # process supervision + orphan cleanup
|
||||
│ ├── logger/ # App logger (op/go-logging + lumberjack rotation)
|
||||
│ └── util/ # Leaf helpers (no business logic):
|
||||
│ ├── common/ # errors, misc
|
||||
│ ├── crypto/ # key/cert generation (x25519, ML-KEM/ML-DSA, ECH)
|
||||
│ ├── link/ # outbound share-link building primitives
|
||||
│ ├── wirecodec/ + wireguard/ # WireGuard codec + integration helpers
|
||||
│ └── random/, json_util/, reflect_util/, sys/, netproxy/, netsafe/, ldap/
|
||||
│
|
||||
├── frontend/ # React SPA (built into internal/web/dist)
|
||||
│ ├── vite.config.js # ⭐ Build config: outDir → ../internal/web/dist, dev on :5173
|
||||
│ │ # (strict) proxying to :2053, entries index/login/subpage.html
|
||||
│ ├── package.json # scripts: dev / build / preview / lint / typecheck / test / gen
|
||||
│ └── src/
|
||||
│ ├── main.tsx / routes.tsx / queryClient.ts # SPA entry, router, query client
|
||||
│ ├── entries/ # Extra HTML entry points: login.tsx, subpage.tsx
|
||||
│ ├── pages/ # ⭐ Route screens. Mirrors the panel's feature areas:
|
||||
│ │ ├── inbounds/ # inbound list + the big inbound form (protocols/security/transport)
|
||||
│ │ ├── clients/ # client management screens
|
||||
│ │ ├── nodes/ # multi-node UI
|
||||
│ │ ├── hosts/ # subscription host-override UI
|
||||
│ │ ├── xray/ # raw Xray config UI (routing, dns, outbounds, balancers, overrides)
|
||||
│ │ ├── index/ # dashboard/home
|
||||
│ │ └── settings/, groups/, sub/, login/, api-docs/
|
||||
│ ├── api/ # ⭐ Data layer: axios-init, QueryProvider, queryKeys, websocket bridge
|
||||
│ │ └── queries/ # TanStack Query hooks (useNodesQuery, useStatusQuery, …)
|
||||
│ ├── schemas/ # Zod schemas: protocols, forms, api, primitives
|
||||
│ ├── generated/ # ⚠️ GENERATED from Go (see §5.5): schemas.ts, types.ts, zod.ts, examples.ts
|
||||
│ ├── components/ # Reusable UI (clients/ form/ ui/ viz/ feedback/ utility/)
|
||||
│ ├── lib/ # Frontend domain logic (xray/ inbounds/ clients/)
|
||||
│ ├── hooks/, models/, layouts/, i18n/, utils/, styles/
|
||||
│ └── test/ # Vitest + golden fixtures (config-generation snapshot tests)
|
||||
│
|
||||
├── tools/openapigen/ # ⭐ Go program that emits frontend/src/generated/* from Go types (§5.5)
|
||||
├── docs/ # Markdown docs (this file, custom-subscription-templates.md, …)
|
||||
├── media/ # README images
|
||||
│
|
||||
├── Dockerfile / docker-compose.yml / DockerEntrypoint.sh / DockerInit.sh # Container build/run
|
||||
├── install.sh / update.sh / x-ui.sh # VPS install + management CLI
|
||||
├── x-ui.service.* / x-ui.rc # systemd units (debian/rhel/arch) + rc script
|
||||
├── windows_files/ # Windows service support
|
||||
└── .github/workflows/ # CI: ci.yml, codeql.yml, docker.yml, release.yml, smoke.yml,
|
||||
# mutation.yml, cleanup_caches.yml, claude-bot.yml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Cross-cutting subsystems (the parts that span many files)
|
||||
|
||||
### 5.1 DB → Xray config pipeline (config generation & application)
|
||||
|
||||
The panel never edits Xray's running config directly from controllers. The flow is:
|
||||
|
||||
1. A service mutates DB state (inbound/client/setting).
|
||||
2. `XrayService` (`service/xray.go`) builds a fresh `xray.Config` from DB state
|
||||
(`GetXrayConfig`).
|
||||
3. It tries a **hot apply** (`tryHotApply` → `xray/hot_diff.go`): diff old vs new config and
|
||||
push only the deltas over the Xray gRPC API (add/remove inbound, add/remove user) — **no
|
||||
process restart**, so live connections survive.
|
||||
4. If the diff isn't hot-applicable (structural change), it falls back to a **full restart**
|
||||
of the Xray process (`xray/process.go`).
|
||||
|
||||
Restart is debounced via an atomic "need restart" flag (`SetToNeedRestart` /
|
||||
`IsNeedRestartAndSetFalse`), consumed by a `@every 30s` cron task registered in `startTask()`
|
||||
— any number of mutations inside the window causes at most one restart.
|
||||
|
||||
**Key files:** `service/xray.go` (orchestration), `xray/hot_diff.go` (the diff algorithm),
|
||||
`xray/process.go` (process lifecycle), `xray/api.go` (gRPC calls), `xray/config.go` (config model).
|
||||
|
||||
### 5.2 Runtime abstraction — Local vs Remote (multi-node) ⭐ most important
|
||||
|
||||
A "node" (`model.Node`) is another 3x-ui instance this panel controls. Every state-changing
|
||||
inbound/client operation goes through the `runtime.Runtime` interface so the *same service
|
||||
code* works whether the target is the local Xray or a remote node.
|
||||
|
||||
- **Interface:** `internal/web/runtime/runtime.go` — `Name`, `AddInbound`, `DelInbound`,
|
||||
`UpdateInbound`, `AddUser`, `RemoveUser`, `UpdateUser`, `DeleteUser`, `AddClient`,
|
||||
`RestartXray`, `ResetClientTraffic`, `ResetInboundTraffic`, `ResetAllTraffics`.
|
||||
- **`Local`** (`local.go`): calls this box's Xray gRPC API directly.
|
||||
- **`Remote`** (`remote.go`): serializes the operation and sends it over HTTPS to the child
|
||||
node's API.
|
||||
- **TLS modes** (`tls_client.go`, per-node `TlsVerifyMode`):
|
||||
`verify` (system CAs, default) / `skip` (no validation) / `pin` (leaf cert SHA-256 must
|
||||
match `PinnedCertSha256`) / `mtls` (master presents a client certificate; node cert checked
|
||||
against system roots; API token optional). Master-side cert management:
|
||||
`service/node_mtls.go` + `service/setting_mtls.go`.
|
||||
- **Dispatch:** `manager.go` → `Manager.RuntimeFor(nodeID *int)`; `nil` nodeID → `Local`,
|
||||
otherwise a cached/lazy-loaded `Remote`. `InvalidateNode(id)` drops a cached remote client.
|
||||
|
||||
**Node identity & attribution (the hard part).** Inbounds carry a `NodeID` *and* an
|
||||
`OriginNodeGuid`. Because inbounds can be pushed across hops, the panel attributes traffic and
|
||||
online clients back to the originating panel using **stable GUIDs** rather than local IDs.
|
||||
Relevant logic: `service/inbound_node.go` (`ReconcileNode`, `SetRemoteTraffic`, GUID merge,
|
||||
`synthNodeGuid`, `panelGuid`) and `service/node.go` (`effectiveNodeGuid`, heartbeat, dirty
|
||||
tracking). Node "dirty" flags drive an **anti-entropy reconciliation** so an offline node's
|
||||
inbound edits converge once it reconnects.
|
||||
|
||||
**Where to look for node bugs:**
|
||||
- Operation not reaching a node → `runtime/remote.go` + `runtime/manager.go`.
|
||||
- Wrong traffic/online attribution across hops → `service/inbound_node.go` (GUID merge paths).
|
||||
- Node shown offline / stale status → `job/node_heartbeat_job.go` + `service/node.go` (`Probe`, `UpdateHeartbeat`).
|
||||
- Edits to an offline node not applying on reconnect → dirty/reconcile logic in `service/inbound_node.go` + `service/node.go` (`MarkNodeDirty`/`ClearNodeDirty`/`NodeSyncState`).
|
||||
- TLS/mTLS handshake failures → `runtime/tls_client.go`, `service/node_mtls.go`, `service/node.go` (`FetchCertFingerprint`).
|
||||
|
||||
### 5.3 Traffic accounting
|
||||
|
||||
Per-client and per-inbound up/down counters originate from Xray's stats API and are persisted
|
||||
to the DB. The Xray traffic job polls the core; node traffic is pulled from child nodes and
|
||||
merged with GUID-based baselines to avoid double counting after resets.
|
||||
|
||||
**Key files:** `service/inbound_traffic.go`, `service/traffic_writer.go`,
|
||||
`job/xray_traffic_job.go`, `job/node_traffic_sync_job.go`, `service/inbound_node.go`
|
||||
(`SetRemoteTraffic` / `upsertNodeBaseline`), models `xray.ClientTraffic`,
|
||||
`model.NodeClientTraffic`, `model.ClientGlobalTraffic` (cross-master totals).
|
||||
Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.TrafficReset`).
|
||||
|
||||
### 5.4 Background jobs (cron)
|
||||
|
||||
All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` method in `internal/web/job/`:
|
||||
|
||||
| Schedule | Job | Purpose / condition |
|
||||
|---|---|---|
|
||||
| `@every 1s` | `check_xray_running_job` | Restart Xray if it died (2 consecutive down checks) |
|
||||
| `@every 30s` | (inline func in `startTask`) | Debounced Xray restart — consumes the "need restart" flag (§5.1) |
|
||||
| `@every 5s` | `xray_traffic_job` | Pull traffic stats from Xray (5s start delay) |
|
||||
| `@every 5s` | `node_heartbeat_job` | Probe child nodes (online/offline) |
|
||||
| `@every 5s` | `node_traffic_sync_job` | Pull + merge node traffic; push reconciliation |
|
||||
| `@every 10s` | `check_client_ip_job` | Enforce per-client IP limits |
|
||||
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
|
||||
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
|
||||
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
|
||||
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")` | Log cleanup; resets |
|
||||
| `@weekly` / `@monthly` | `periodic_traffic_reset_job(...)` | Weekly/monthly traffic resets |
|
||||
| default `@every 1m` | `ldap_sync_job` | Only if LDAP enabled; schedule configurable |
|
||||
| default `@daily` | `stats_notify_job` | Only if TG bot enabled; schedule configurable |
|
||||
| `@every 2m` | `check_hash_storage` | Only if TG bot enabled; expires bot callback hashes |
|
||||
| `@every 1m` | `check_cpu_usage` | Only if a CPU alarm is configured (TG or email); publishes `cpu.high` |
|
||||
| `@every 1m` | `check_memory_usage` | Only if a memory alarm is configured; publishes `memory.high` |
|
||||
| configurable | `free_os_memory` | Only if `sys.MemoryReleaseIntervalMinutes() > 0`; returns heap to OS |
|
||||
|
||||
To change *when* something runs, edit `startTask()`. To change *what* it does, edit the job file.
|
||||
|
||||
### 5.5 Type generation (Go → TypeScript) ⚠️ don't hand-edit generated files
|
||||
|
||||
The Go backend is the schema source of truth. `tools/openapigen` (a Go program, with a
|
||||
`StructAllow` allowlist of exported types) emits
|
||||
`frontend/src/generated/{schemas,types,zod,examples}.ts`. The frontend build runs this first:
|
||||
|
||||
- `npm run gen:zod` → `go run ./tools/openapigen` (regenerate from Go)
|
||||
- `npm run gen:api` → builds the OpenAPI doc (`scripts/build-openapi.mjs`, driven by the
|
||||
hand-maintained endpoint registry `src/pages/api-docs/endpoints.ts`)
|
||||
- `npm run build` runs `gen:api` then `vite build`.
|
||||
|
||||
**Implication:** if you change a Go model/DTO that crosses the API boundary, regenerate the
|
||||
frontend types (`cd frontend && npm run gen`) instead of editing `src/generated/` by hand.
|
||||
|
||||
### 5.6 Share-link / subscription generation
|
||||
|
||||
Two distinct code paths produce client configs:
|
||||
- **Per-client links in the panel** (the "copy link" / QR in the UI): `service/client_link.go`
|
||||
+ `util/link/outbound.go`.
|
||||
- **Subscription endpoint** (what a client app polls): `internal/sub/service.go` (raw links),
|
||||
`internal/sub/json_service.go` (JSON), `internal/sub/clash_service.go` (Clash YAML).
|
||||
**`Host` rows** (`model.Host`, edited under /panel/api/hosts) override address/SNI/path/
|
||||
security per inbound in subscription output — applied in `sub/host_sub.go`.
|
||||
|
||||
Both paths must agree per protocol. A malformed link for a specific protocol/transport combo
|
||||
(e.g. XHTTP + Reality) is usually a field-lookup mismatch in **`internal/sub/service.go`** (and
|
||||
its tests `service_test.go` / golden fixtures), or in `util/link/outbound.go`. The frontend
|
||||
also has protocol schemas under `frontend/src/schemas/protocols/` and `frontend/src/lib/xray/`.
|
||||
|
||||
### 5.7 Event bus (in-process pub/sub)
|
||||
|
||||
`internal/eventbus/` is a minimal buffered-channel pub/sub. Producers call a non-blocking
|
||||
`Publish(Event)`; all subscribers receive every event. Event types: `outbound.down|up`,
|
||||
`xray.crash`, `node.down|up`, `cpu.high`, `memory.high`, `login.attempt`, with structured
|
||||
payloads (OutboundHealthData, NodeHealthData, LoginEventData, SystemMetricData). Producers
|
||||
include the CPU/memory jobs, node heartbeat, and login handling; consumers include the
|
||||
Telegram bot and the email notifier (`service/email/`). Use it for cross-cutting
|
||||
notifications instead of importing notification services into producers.
|
||||
|
||||
### 5.8 Tunnel health monitor
|
||||
|
||||
`internal/tunnelmonitor/` is an optional watchdog configured **only via env vars**
|
||||
(`XUI_TUNNEL_HEALTH_*`, read in `internal/config/`), deliberately independent of panel
|
||||
settings so it can be enabled from a systemd `EnvironmentFile` even when the panel is
|
||||
unreachable. It periodically probes an HTTP URL (default: Cloudflare trace endpoint) through
|
||||
the tunnel; after N successive failures (default 3) it fires a recovery callback wired to an
|
||||
Xray restart.
|
||||
|
||||
---
|
||||
|
||||
## 6. Data model cheat-sheet
|
||||
|
||||
GORM models in `internal/database/model/` (main file `model.go` + siblings); all registered
|
||||
for AutoMigrate in `internal/database/db.go`.
|
||||
|
||||
| Model | Table role | Notable fields |
|
||||
|---|---|---|
|
||||
| `User` | Admin login | bcrypt password, `LoginEpoch` (invalidates sessions) |
|
||||
| `Inbound` | An Xray inbound | `Tag` (unique), `Port`, `Protocol`, `Settings`/`StreamSettings`/`Sniffing` (JSON), `Enable`, `TrafficReset`, `NodeID`, **`OriginNodeGuid`**, `ClientStats` (assoc) |
|
||||
| `Client` | In-memory client view | UUID/email/flow/limits (parsed from inbound JSON; not persisted) |
|
||||
| `ClientRecord` | Persisted client (`clients`) | `Email` (unique), `SubID`, `UUID`, `TotalGB`, `ExpiryTime`, `LimitIP`, `Group`, `Reset` |
|
||||
| `ClientGroup` / `ClientInbound` | Grouping + client↔inbound join | many-to-many wiring, `FlowOverride` |
|
||||
| `ClientExternalLink` | Extra links attached to a client | `Kind`, `Value`, `Remark`, `SortIndex` |
|
||||
| `Host` | Subscription host overrides (per inbound) | `Address`, `Port`, `Sni`, `Path`, `Security`, `Fingerprint`, `SortOrder`, visibility/exclusion flags |
|
||||
| `Node` | A managed child panel | `Guid`, `Address`, `Status`, `TlsVerifyMode`, `PinnedCertSha256`, `ConfigDirty`, version/heartbeat/metric fields |
|
||||
| `NodeClientTraffic` | Per-node client traffic baseline | cross-node merge (anti-double-count) |
|
||||
| `NodeClientIp` | Per-node client IP attribution | `NodeGuid`, `Email`, `Ips` |
|
||||
| `ClientGlobalTraffic` | Cross-master usage totals | `MasterGuid`, `Email`, `Up`, `Down` |
|
||||
| `xray.ClientTraffic` | Per-client counters (`client_traffics`) | `Email`, `Up`, `Down`, `Total`, `ExpiryTime`, `LastOnline` |
|
||||
| `InboundClientIps` | IP set per client email | drives IP-limit enforcement |
|
||||
| `OutboundTraffics` | Outbound counters | per outbound tag |
|
||||
| `OutboundSubscription` | External provider subs | Warp/Nord style |
|
||||
| `Setting` | Key/value panel settings | everything configurable |
|
||||
| `ApiToken` | REST API tokens | SHA-256 hash (plaintext shown once) |
|
||||
| `InboundFallback` | Fallback routing on a shared port | SNI/ALPN/path → dest |
|
||||
| `HistoryOfSeeders` | Seeder bookkeeping | prevents re-running one-off migrations |
|
||||
|
||||
---
|
||||
|
||||
## 7. Symptom → File index (start here when debugging)
|
||||
|
||||
| Symptom / task | Primary file(s) | Then check |
|
||||
|---|---|---|
|
||||
| Add/modify an **API endpoint** | `controller/<resource>.go` (route registration at top of each file) | corresponding `service/*.go`, `frontend/src/pages/api-docs/endpoints.ts` |
|
||||
| **Inbound** create/update/delete behavior | `service/inbound.go`, `service/inbound_clients.go` | `runtime/*`, `service/xray.go` |
|
||||
| **Client** CRUD / limits / expiry | `service/client_crud.go`, `service/client_inbound_apply.go` | model `ClientRecord`, `service/inbound_traffic.go` |
|
||||
| **Bulk** client operations slow/wrong | `service/client_bulk.go` | `service/client_paging.go` |
|
||||
| Xray **won't apply** a config change | `service/xray.go` (`RestartXray`, `tryHotApply`) | `xray/hot_diff.go`, `xray/process.go` |
|
||||
| Xray **restarts when it shouldn't** (kills connections) | `xray/hot_diff.go` (diff not classified as hot) | `service/xray.go` |
|
||||
| **Traffic** counts wrong / reset behavior | `service/inbound_traffic.go`, `job/xray_traffic_job.go` | `service/traffic_writer.go`, `job/periodic_traffic_reset_job.go` |
|
||||
| **Node** operation not propagating | `runtime/remote.go`, `runtime/manager.go` | `service/inbound_node.go` |
|
||||
| **Multi-hop / cross-node attribution** (traffic or online clients on wrong panel) | `service/inbound_node.go` (GUID merge, `synthNodeGuid`, `effectiveNodeGuid`) | `service/node.go`, model `OriginNodeGuid`/`Node.Guid` |
|
||||
| Node stuck **offline / stale** | `job/node_heartbeat_job.go`, `service/node.go` (`Probe`, `UpdateHeartbeat`) | `runtime/tls_client.go` (TLS verify) |
|
||||
| Node **TLS / mTLS** auth failures | `runtime/tls_client.go`, `service/node_mtls.go`, `service/setting_mtls.go` | `service/node.go` (`FetchCertFingerprint`) |
|
||||
| Offline node edits **not reconciling** on reconnect | `service/inbound_node.go` (`ReconcileNode`, dirty flags) | `service/node.go` (`MarkNodeDirty`/`NodeSyncState`) |
|
||||
| **Share link / QR** malformed (per protocol) | `service/client_link.go`, `util/link/outbound.go` | `frontend/src/lib/xray/`, `frontend/src/schemas/protocols/` |
|
||||
| **Subscription** output wrong (raw/JSON/Clash) | `internal/sub/service.go` | `sub/json_service.go`, `sub/clash_service.go`, sub golden tests |
|
||||
| Subscription **host overrides** not applied | `service/host.go`, `sub/host_sub.go` | model `Host`, `frontend/src/pages/hosts/` |
|
||||
| **External subscription** import/aggregation | `sub/external_subscription.go`, `sub/external_config.go` | `sub/clash_external.go` |
|
||||
| **Settings** not saving / defaults | `service/setting.go`, `controller/setting.go` | model `Setting` |
|
||||
| **Login / 2FA / sessions / CSRF** | `controller/index.go`, `service/panel/user.go`, `middleware/` | `session/` |
|
||||
| **API tokens** | `service/panel/api_token.go`, `controller/setting.go` | model `ApiToken` |
|
||||
| **Port conflict** on inbound add | `service/port_conflict.go` | `controller/inbound.go` |
|
||||
| **Fallbacks** (shared 443, SNI routing) | `service/fallback.go`, `controller/inbound.go` | model `InboundFallback` |
|
||||
| **Telegram bot** commands | `service/tgbot/` | `job/stats_notify_job.go` |
|
||||
| **Email notifications** | `service/email/` | `internal/eventbus/` (consumers) |
|
||||
| **CPU / memory alerts** not firing | `job/check_cpu_usage.go`, `job/check_memory_usage.go` | `internal/eventbus/`, notifier settings in `service/setting.go` |
|
||||
| Xray auto-restart on **dead tunnel** | `internal/tunnelmonitor/` | `XUI_TUNNEL_HEALTH_*` in `internal/config/` |
|
||||
| **WARP / Nord** outbound integration | `service/integration/warp.go` / `nord.go` | `service/outbound_subscription.go` |
|
||||
| **MTProto** proxy issues | `internal/mtproto/manager.go`, `mtproto/process*.go` | `job/mtproto_job.go` |
|
||||
| **DB migration** / new column | `internal/database/db.go` (AutoMigrate list), `migrate_data.go` | `model/model.go` |
|
||||
| **Cron schedule** changes | `web.go` → `startTask()` | the specific `job/*.go` |
|
||||
| **CORS / security headers / HTTPS** | `middleware/`, `web.go` (`initRouter`, TLS setup) | `config/` (env) |
|
||||
| **Env vars / paths / DB type** | `internal/config/config.go` | `.env.example` |
|
||||
| **Frontend route / screen** | `frontend/src/pages/<area>/`, `frontend/src/routes.tsx` | `frontend/src/api/queries/` |
|
||||
| **Frontend ↔ backend type mismatch** | regenerate: `cd frontend && npm run gen` (`tools/openapigen`) | `frontend/src/generated/` |
|
||||
| **System status / CPU / metrics** | `service/server.go`, `service/xray_metrics.go`, `service/metric_history.go` | `controller/server.go`, gopsutil |
|
||||
|
||||
---
|
||||
|
||||
## 8. Layering rules (where new code belongs)
|
||||
|
||||
1. **Controllers are thin.** Only: bind/validate input, call one service, shape the HTTP
|
||||
response. No DB queries, no Xray calls, no business rules in `controller/`.
|
||||
2. **Services own the logic and transactions.** All business rules, DB access, and decisions
|
||||
about applying changes live in `service/`. If you're tempted to query GORM from a
|
||||
controller, move it to a service.
|
||||
3. **Never touch Xray's running state from a controller or job directly.** Go through
|
||||
`XrayService` / the `runtime.Runtime` interface so local vs node dispatch stays correct.
|
||||
4. **Any state-changing inbound/client op must dispatch through `runtime.Runtime`**, not
|
||||
straight to `xray/api.go` — otherwise node deployments silently break.
|
||||
5. **`internal/util/*` is leaf-only** (no imports of `service`/`controller`/`database`). Keep
|
||||
helpers pure.
|
||||
6. **Don't hand-edit generated files:** `frontend/src/generated/*` and `internal/web/dist/*`.
|
||||
Regenerate instead.
|
||||
7. **Models are the contract.** Changing a model field that crosses the API boundary means:
|
||||
update `model.go` → handle migration in `db.go`/`migrate_data.go` → regenerate frontend types.
|
||||
8. **Two servers, two concerns.** Admin features go in `internal/web`; anything an *end user*
|
||||
fetches goes in `internal/sub`. Don't blur them.
|
||||
9. **Cross-cutting notifications go through `internal/eventbus/`** — publish an event instead
|
||||
of importing the Telegram/email services into producers.
|
||||
|
||||
---
|
||||
|
||||
## 9. Build / Test / Lint (verify your changes)
|
||||
|
||||
The canonical gate is the **Makefile** (mirrors CI): `make verify`. Also: `make gen`
|
||||
(regenerate Zod/OpenAPI), `make lint` (Go + frontend), `make test` (Go `-shuffle=on` +
|
||||
frontend), `make race`, `make build`. Run `make help` for everything. Raw commands:
|
||||
|
||||
**Backend (Go):**
|
||||
```bash
|
||||
go build ./... # compile everything
|
||||
go test ./... # run all Go tests (many *_test.go alongside sources)
|
||||
go test ./internal/web/service/... # focused: service-layer tests
|
||||
go test ./internal/xray/... # hot-diff / process / api tests
|
||||
go test ./internal/sub/... # subscription + golden link tests
|
||||
go vet ./... # static checks
|
||||
golangci-lint run # full lint (gofumpt + goimports formatting)
|
||||
go run main.go # run the panel locally (serves embedded dist if built)
|
||||
```
|
||||
|
||||
**Frontend (`cd frontend`, Node ≥ 22):**
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # Vite dev server on :5173; proxies API to Go backend on :2053 (run `go run main.go` too)
|
||||
npm run typecheck # tsc --noEmit
|
||||
npm run lint # eslint src
|
||||
npm run test # vitest (incl. golden config-generation snapshots)
|
||||
npm run gen # regenerate src/generated/* from Go (gen:zod + gen:api)
|
||||
npm run build # gen:api + vite build → outputs to internal/web/dist (then rebuild Go binary to embed)
|
||||
```
|
||||
|
||||
**Full local loop:** `cd frontend && npm run build` (refresh embedded `dist/`) → back to repo
|
||||
root → `go build ./...` / `go run main.go`.
|
||||
|
||||
**Docker:** `docker compose up -d` (uses `Dockerfile` + `DockerEntrypoint.sh`).
|
||||
|
||||
**CI** (`.github/workflows/`): `ci.yml` (build/test/lint), `codeql.yml` (security scan),
|
||||
`smoke.yml` (smoke tests), `mutation.yml` (mutation testing), `docker.yml` + `release.yml`
|
||||
(multi-arch image + release builds), `cleanup_caches.yml`, `claude-bot.yml` (issue bot).
|
||||
|
||||
---
|
||||
|
||||
## 10. Gotchas & conventions
|
||||
|
||||
- **Module path is `.../v3`.** Internal imports use `github.com/mhsanaei/3x-ui/v3/internal/...`.
|
||||
- **SQLite vs Postgres.** Default is SQLite at `{XUI_DB_FOLDER}/x-ui.db`. Postgres via
|
||||
`XUI_DB_TYPE=postgres` + `XUI_DB_DSN`. Some SQL paths are dialect-aware (`database/dialect.go`);
|
||||
test both when touching raw queries (there are `*_scale_postgres_test.go` suites).
|
||||
- **`Inbound.Settings` / `StreamSettings` / `Sniffing` are raw JSON strings**, not structured
|
||||
columns. Parsing/validation happens in services and the `xray` package, not in GORM.
|
||||
- **Hot-reload is the default; full restart is the fallback.** Changes that look config-only
|
||||
but cause a restart usually mean the diff in `xray/hot_diff.go` didn't recognize them as hot.
|
||||
- **Node TLS:** remote calls honor `TlsVerifyMode` (`verify`/`skip`/`pin`/`mtls`). "Works on
|
||||
skip, fails on verify/pin/mtls" → cert/fingerprint handling in `service/node.go`
|
||||
(`FetchCertFingerprint`), `service/node_mtls.go`, and `runtime/tls_client.go`.
|
||||
- **Restart is signal-driven.** `main.go` traps SIGHUP to restart panel+sub servers; the
|
||||
in-process restart hook (`global.SetRestartHook`) funnels into the same path.
|
||||
- **i18n:** backend catalogs in `internal/web/translation/` (13 locales, shared with the
|
||||
frontend); frontend wiring in `frontend/src/i18n/`. Persian (`fa_IR`) is a first-class
|
||||
locale (Jalali calendar via `persian-calendar-suite`).
|
||||
- **Tests live next to code** (`foo.go` ↔ `foo_test.go`), plus golden snapshots in
|
||||
`frontend/src/test/golden/fixtures/` for config generation — update fixtures intentionally,
|
||||
not blindly, when output changes.
|
||||
Generated
+168
-177
@@ -11,21 +11,22 @@
|
||||
"@ant-design/icons": "^6.3.2",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@tanstack/react-query-devtools": "^5.101.2",
|
||||
"antd": "^6.5.0",
|
||||
"axios": "^1.18.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"dayjs": "^1.11.21",
|
||||
"i18next": "^26.3.3",
|
||||
"i18next": "^26.3.4",
|
||||
"otpauth": "^9.5.1",
|
||||
"persian-calendar-suite": "^1.5.5",
|
||||
"qs": "^6.15.3",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-i18next": "^17.0.8",
|
||||
"react-router-dom": "^7.18.0",
|
||||
"recharts": "^3.9.0",
|
||||
"react-router-dom": "^7.18.1",
|
||||
"recharts": "^3.9.1",
|
||||
"swagger-ui-react": "^5.32.8",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -44,8 +45,8 @@
|
||||
"globals": "^17.7.0",
|
||||
"jsdom": "^29.1.1",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.62.0",
|
||||
"vite": "8.1.0",
|
||||
"typescript-eslint": "^8.62.1",
|
||||
"vite": "8.1.3",
|
||||
"vitest": "^4.1.9"
|
||||
},
|
||||
"engines": {
|
||||
@@ -1105,9 +1106,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-project/types": {
|
||||
"version": "0.137.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.137.0.tgz",
|
||||
"integrity": "sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==",
|
||||
"version": "0.138.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.138.0.tgz",
|
||||
"integrity": "sha512-1a7ZKmrRTCoN1XMZ4L0PyyqrMnrNlLyPuOkdSX2MZg7IiIGRUyurNhAm73ptDOraoBcIordsIGKNPKUzy3ZmfA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
@@ -1843,20 +1844,10 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@reduxjs/toolkit/node_modules/immer": {
|
||||
"version": "11.1.8",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.8.tgz",
|
||||
"integrity": "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/immer"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm64": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.3.tgz",
|
||||
"integrity": "sha512-DT6Z3PhvioeHMvxo+xHc3KtqggrI7CCTXCmC2h/5zUlp5jVitv7XEy+9q5/7v8IolhlioawpMo8Kg0EEBy7J0g==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.4.tgz",
|
||||
"integrity": "sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1871,9 +1862,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.3.tgz",
|
||||
"integrity": "sha512-0NwgwsjM7LrsuVnXMK3koTpagBNOhloc/BNjKqZjv4V5zI5r13qx69uVhRx+o5Z0yy4Hzq+lpy7TAgUG/ocvrw==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.4.tgz",
|
||||
"integrity": "sha512-aUi+HBvmYb7j8krl1+qJgkG8C17fO79gk3c+jPw4S8glRFc1DTija9S3EyaTSQUm5GJXYKDAsugBEhFHH2vYiQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1888,9 +1879,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-x64": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.3.tgz",
|
||||
"integrity": "sha512-YtiBp4disu6V560loT6PjMdiRaWmVvDNrUunAalbiFx2ggeJwxdAsgZMcoGP17uyAsTwAj5V1niksxlHnVQ1Sw==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.4.tgz",
|
||||
"integrity": "sha512-F7hHC3gwY11+vByKPRWqwGbeXWVgKmL+pTGCinaEhdihzBV2aQ0fvZOch9cXYUOKuKKq429HeYXOqQLc7wFCEg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1905,9 +1896,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.3.tgz",
|
||||
"integrity": "sha512-yD3EkEdXk2LypPxnf/kSZHirarsI8gcPzc62SukhR9VJTyvV+F9Q/GxWNuCojc7sXyuVC4DxRGhdDK4X8VSsbw==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.4.tgz",
|
||||
"integrity": "sha512-sI5yw+7s92SK6odiEhD5lKCBlWcpjHS5qyqpVQbZAJ0fIzEUXrmbl3DH2ybR3PZogulNJF+COLtmA8hUfvkCCQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1922,9 +1913,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.3.tgz",
|
||||
"integrity": "sha512-c+8vieQbsD7HNAHKIA34w0GJ9FedFFuJGD+7E6vz7Q3uqAIugL5p45fhlsj4UaAsHpcmlqugBWMhA0/j7o0sIg==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.4.tgz",
|
||||
"integrity": "sha512-mCi0OKgEieFircrtVYmQAFGszRtMnZ6fpZAXrxanXAu7lqZcsK1E1RAaZNG0uKAnxox3B1f4EyQNnoyMfN1vAA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -1939,9 +1930,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.3.tgz",
|
||||
"integrity": "sha512-50jD0uUwLvur7Zz9LHz17kaAdTPjn5wN93hEgjvmYFRZwiR7ZJYovTd5ipyWJDAnXKvZ+wgc+/Ika6dwSF5OcA==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.4.tgz",
|
||||
"integrity": "sha512-B9Ial3Kv5sh0SHnB1g/QWcUQCEvCF6QKGAl4zXypYj65mVI+B4AhFBwPtSN7pDrJeIx8Z7zdy4ntx+wQABom7w==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1959,9 +1950,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.3.tgz",
|
||||
"integrity": "sha512-BO9+oPL8K9poZJBfYPsXNtYjPE5uM3qeehT3aFcW4LITOl+iSqhp0abzjR2nWBUNjIZeKXjAEWBZ64WjNoHd6w==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.4.tgz",
|
||||
"integrity": "sha512-lZVym0PuHE1KZ22gmFTC15lAkrg9iTszR617oYRB/iPY1A56ywoJzVKOJBKaot5RiikCObmur6pogpse3gRcng==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1979,9 +1970,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.3.tgz",
|
||||
"integrity": "sha512-f3VpLB1vQ0Eo6ecr/6cekLnvYMFF4YBFoVGkfkvPLq1bAkbAwHYQPZKoAmG6OJyTcxxoC+AvezGx/S1obNC0Mw==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.4.tgz",
|
||||
"integrity": "sha512-t2DNiLJWNTbnEHyUzTumldML6ET4/g16467LZoDDJ3tSxGvguL5/NyC2lCsNKuyRycg9XeDQF5SSv+TNOhQEXg==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -1999,9 +1990,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.3.tgz",
|
||||
"integrity": "sha512-AmurZ26Pqx/RI9N1gzEOCklkKXl927yjfXWUUS0O7Puh8ARM/Ob8qfrD3qnWksScdw6cSrW5PSHE9DyLu7+PtA==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.4.tgz",
|
||||
"integrity": "sha512-0WIRnL1Uw4BvTZRLQt+PVgo6ZKTJadlC2btP+/EOXv2f/DWbY0rEgl+y834mIVwP1FkTlWVTrGGJXf12lru7EQ==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -2019,9 +2010,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.3.tgz",
|
||||
"integrity": "sha512-JJpqs8bRGITDOdbkNKnlojzBabbOHrqjSvDr0IVsZObE1lBcPjxItUEY9eWIDbxaJ3cGrXPWGfGkIxFijg/URg==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.4.tgz",
|
||||
"integrity": "sha512-JWtGshGfX+oENAKonoNkqEJX+7hC8yfhi9GUyPX1VX4mdh1y5r+ZiJLR5XzAB0aoP6s/PcILsGjKq8O0mm24bw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -2039,9 +2030,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.3.tgz",
|
||||
"integrity": "sha512-rSJcdjPxzA/by/6/rYs+v+bXU7UjvnbUWz8MJb6kh6+knqB1dCrtHg0uu7C/4haqJvqdkYHQ5IGn+tCH9GLW/g==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.4.tgz",
|
||||
"integrity": "sha512-rT6yQcxUuXs4CnbofqwHRRV0iem349rLMYpTjkgQGLjrY4ado/eDzwPZPTCgTOlF6Nkp8NEv70yLMTn6qkWxsQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -2059,9 +2050,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.3.tgz",
|
||||
"integrity": "sha512-hQ3/PYkDJICgevvyNcVrihVeqq7k1Pp3VZ9lY+dauAYUJKO+auqApvANhvR1An9BhmqYKvW2Mu1F9u4DXSMLxQ==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.4.tgz",
|
||||
"integrity": "sha512-KXMGoboq5cyaCQjDA4GLuRiOwBQ0EyFnJoVViLeZ45/3rFItRODEr+NdsBcVpll40hhNArlm/speWGRvj08LzA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -2076,9 +2067,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.3.tgz",
|
||||
"integrity": "sha512-Elcv/BtML9lXrV6JuKITc/grN2kYV9gjsQpW8Jfw4ioK0TOkjBjye0nnyqQNy9STNaI20lXNaQBRrD5gSgR0Yg==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.4.tgz",
|
||||
"integrity": "sha512-5K83rb36oJiY7BCyE9zLZtGcPV4g5wvq+xwdO0XPIwDVZI8cyB/AUjkNXGb92/rnmezEkjMOpgY61rtwjQtFwg==",
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
],
|
||||
@@ -2095,9 +2086,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.3.tgz",
|
||||
"integrity": "sha512-2DrEfhluH9yhiaFApmsjsjwrSYbNcY1oFTzYSP1a535jDbV98zCFanA/96TBUd0iDFcxGmw9QRExwGCXz3U+/g==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.4.tgz",
|
||||
"integrity": "sha512-PnWBtw3TV5KOg69HQQDR0mnQuyCmSGR2pAB4DC1rPF808fgKeTUMj2EOEyKATpgiuxuR5APQmiDO7PDgEjTFSA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -2112,9 +2103,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.3.tgz",
|
||||
"integrity": "sha512-OL4OMk7UPXOeVGGd3qo5zJyPIljf4AFgk5QAkPPS+OoLuOOozhuaQGC18MxVTnw/06q93gShAJzlwnSCY9YtqA==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.4.tgz",
|
||||
"integrity": "sha512-M1lpniBePobTfsa7Ks9a199e1akxsXn+GYBUKsEzv3YFzOm1HJAMNwKI3qr0Zq+mxwx9gOZoTdP1yXRYsZUocQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -3108,17 +3099,17 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.62.0.tgz",
|
||||
"integrity": "sha512-o+mpz7EYiMzXoySXiKmzlabIvTVqUuK5yLrAedRPRDA0IpPFMUV1IXt6OqljIxX/kumN6EjUYp41Hqelh6p/Dw==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.62.1.tgz",
|
||||
"integrity": "sha512-4EQM77WgVNxj7OkL/5b/D/xZsw00G577+UriYTC7JF5opcF3T2AuoeY7ueLaZgSVjSgCS6yOAJB5bRGLPSJUzA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/regexpp": "^4.12.2",
|
||||
"@typescript-eslint/scope-manager": "8.62.0",
|
||||
"@typescript-eslint/type-utils": "8.62.0",
|
||||
"@typescript-eslint/utils": "8.62.0",
|
||||
"@typescript-eslint/visitor-keys": "8.62.0",
|
||||
"@typescript-eslint/scope-manager": "8.62.1",
|
||||
"@typescript-eslint/type-utils": "8.62.1",
|
||||
"@typescript-eslint/utils": "8.62.1",
|
||||
"@typescript-eslint/visitor-keys": "8.62.1",
|
||||
"ignore": "^7.0.5",
|
||||
"natural-compare": "^1.4.0",
|
||||
"ts-api-utils": "^2.5.0"
|
||||
@@ -3131,7 +3122,7 @@
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@typescript-eslint/parser": "^8.62.0",
|
||||
"@typescript-eslint/parser": "^8.62.1",
|
||||
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
|
||||
"typescript": ">=4.8.4 <6.1.0"
|
||||
}
|
||||
@@ -3147,16 +3138,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/parser": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.62.0.tgz",
|
||||
"integrity": "sha512-dzHeT2gySzZtLDsuqxU9AkYgIsQoHAHtRBpOqM+Ofzx1Bwrd2RcCjQJ+6iQbsHOIR6NS33bF2W1k3blN1zLDrA==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.62.1.tgz",
|
||||
"integrity": "sha512-sPhE4iHuJDSvoAiec+Ro8JyXw8f0ql13HFR82P99nCm9GwTEKG0KYLvDe6REk8BCXuit6vJAv/Yxg5ABaNS2rA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.62.0",
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/typescript-estree": "8.62.0",
|
||||
"@typescript-eslint/visitor-keys": "8.62.0",
|
||||
"@typescript-eslint/scope-manager": "8.62.1",
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"@typescript-eslint/typescript-estree": "8.62.1",
|
||||
"@typescript-eslint/visitor-keys": "8.62.1",
|
||||
"debug": "^4.4.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -3172,14 +3163,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/project-service": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.62.0.tgz",
|
||||
"integrity": "sha512-wexnCqiTg7BOGtbLDftYpRWlmLq4xfoMd7BKFR6Y75sZS3QmRKLdN3yWLhmIYgqMmP/OXWpj3H8odkb5nGURCQ==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.62.1.tgz",
|
||||
"integrity": "sha512-yQ3RgY5RkSBpsNS1Bx/JQEcA24FOSdfGktoyprAr5u18390UQdtVcfnEv4nIrIshNnavlVyZBKxQwT1fIAE6cg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/tsconfig-utils": "^8.62.0",
|
||||
"@typescript-eslint/types": "^8.62.0",
|
||||
"@typescript-eslint/tsconfig-utils": "^8.62.1",
|
||||
"@typescript-eslint/types": "^8.62.1",
|
||||
"debug": "^4.4.3"
|
||||
},
|
||||
"engines": {
|
||||
@@ -3194,14 +3185,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/scope-manager": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.62.0.tgz",
|
||||
"integrity": "sha512-1lX38kNxXIRb8mEc3lbq5mdHq1Pf2+U0nFU65KfT18mtPxxl0fvjuEE92mHuXPuCtElJhOrddOpyMlM3Z0umEA==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.62.1.tgz",
|
||||
"integrity": "sha512-r4d249KbQ1SFdpeStvob8Ih6aPPIzfqllPVOtvhve6ZcpuVcYo5/7zUWckKpHE7StASX4kTKZTLf0WQm/wPkcg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/visitor-keys": "8.62.0"
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"@typescript-eslint/visitor-keys": "8.62.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -3212,9 +3203,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/tsconfig-utils": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.62.0.tgz",
|
||||
"integrity": "sha512-y2GAdB6ykaXUvuspbYnizQc4oDDz0Tz/Yc7iWrXf9mx8vm/L/0vLHCe0tS2boG96Zy+DivnVDQ9ZUEWoHqqx1g==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.62.1.tgz",
|
||||
"integrity": "sha512-xadytJqX9vJVQ2fdQjkcIVigwaOJNWkpjdLt6cEQ+xPnrI1fkp+/jZE/I97k9KUjqtpd25i0HeyZf3T6dutv2g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -3229,15 +3220,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/type-utils": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.62.0.tgz",
|
||||
"integrity": "sha512-+g5O3j0w2ldzC86Pv6fvbO/xhAonbJFIdf/MKQ1d30gndlsVzUOE83ldfSE15Qrl9fhFjK6AovHs5Wpp6vx86w==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.62.1.tgz",
|
||||
"integrity": "sha512-aXM5xlqXiTxPibXB93cLAURfT3rlizf7uMXISCXy66Isr/9hISJx3yDsKl0L7lKa51b8JpFuNKby0/O0pEm9jg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/typescript-estree": "8.62.0",
|
||||
"@typescript-eslint/utils": "8.62.0",
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"@typescript-eslint/typescript-estree": "8.62.1",
|
||||
"@typescript-eslint/utils": "8.62.1",
|
||||
"debug": "^4.4.3",
|
||||
"ts-api-utils": "^2.5.0"
|
||||
},
|
||||
@@ -3254,9 +3245,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/types": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.62.0.tgz",
|
||||
"integrity": "sha512-KvAclkktORPvM54TgLgA4z9HIV1M8zOgw9ZVNXl9f/8dLYfXYX1wkMXP7qmabpijQRV5bHJLOmoyGQbLMaUYeg==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.62.1.tgz",
|
||||
"integrity": "sha512-ooCzJFaf+Hg+uG6fA3NRFGuFjlfNlDhBthbv4ZPU/0elCAFUfnyXUvf/WOpHz/jYwSmvU2GkR2LtyUfy1AxZ1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -3268,16 +3259,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.62.0.tgz",
|
||||
"integrity": "sha512-+hVbNxtW64pIcZWDPGbyaKF7vp2IBTVY5ma1blwwksrjdsbdqqEKvJWMGbBofei4F6Dovx1M0RJgoFeNu2279A==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.62.1.tgz",
|
||||
"integrity": "sha512-xMcW9oP9u7fAMXYs9A65CVmtLQe2r//oXINHfi8HV+oiqhih17sbLdhXr4540YWlgpDKQdY854OL5ZrdCiQsAA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/project-service": "8.62.0",
|
||||
"@typescript-eslint/tsconfig-utils": "8.62.0",
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/visitor-keys": "8.62.0",
|
||||
"@typescript-eslint/project-service": "8.62.1",
|
||||
"@typescript-eslint/tsconfig-utils": "8.62.1",
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"@typescript-eslint/visitor-keys": "8.62.1",
|
||||
"debug": "^4.4.3",
|
||||
"minimatch": "^10.2.2",
|
||||
"semver": "^7.7.3",
|
||||
@@ -3309,16 +3300,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/utils": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.62.0.tgz",
|
||||
"integrity": "sha512-82r66fi9zYwZ+mTq3vKgwjbZ1PVk/DJzrXFLpG6RnBbdvH8TEGVHIs9H4d2drhkOzf0syZuD/OZvvlu6GDbP4g==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.62.1.tgz",
|
||||
"integrity": "sha512-sHtbPfuKNZCG+ih8SyjjucqRntSVmp8XgL5u6o9mAhiSn8ds5o/M/XdM0abweme2Tln3szOstOrZ9OXitvPh0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.9.1",
|
||||
"@typescript-eslint/scope-manager": "8.62.0",
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/typescript-estree": "8.62.0"
|
||||
"@typescript-eslint/scope-manager": "8.62.1",
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"@typescript-eslint/typescript-estree": "8.62.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -3333,13 +3324,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/visitor-keys": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.62.0.tgz",
|
||||
"integrity": "sha512-CY3uyFSRbcQv3nnSv8S0+lDftMVz6P963PoRlxrV7ew/Md564g9ut60PYzdLM5qW4jFn93GBF+Soi90ISAN+GQ==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.62.1.tgz",
|
||||
"integrity": "sha512-4g3BLxfdTMy8iZG0MaBkadnlRrCJ74cQiFbyEVMrkwIoqdyaXXQM22cotDvrl4x28wgIZ9rEJRoM+mmhSJpJ1g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.62.0",
|
||||
"@typescript-eslint/types": "8.62.1",
|
||||
"eslint-visitor-keys": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
@@ -3918,9 +3909,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.10.40",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.40.tgz",
|
||||
"integrity": "sha512-BSSLZ9/Cjjv7Gtj5B68ZzXcXUg8iOf3fme+FCuh8rC/Go+Kmh8cox7M3A8dolou16s64QjLPOSdngh7GxXvkSw==",
|
||||
"version": "2.10.41",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.41.tgz",
|
||||
"integrity": "sha512-WwS7MHhqGHHlaVsqRZnhvCEMS0owDX+SxRlve7JkuH7My1Ara3ZriTmCQupPfYjxMZ8I/tgxtJYr2t7taHaH4A==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
@@ -4058,9 +4049,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001799",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001799.tgz",
|
||||
"integrity": "sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==",
|
||||
"version": "1.0.30001800",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001800.tgz",
|
||||
"integrity": "sha512-MMHtuAz9Ys840zAY5F4k6fV5GaivZ9sPk+nz0mY+GYVzRBnYkN0mpqkSR92oWRQ19yQWo4HvBV/FnC16AJX8MA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -4644,9 +4635,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.381",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.381.tgz",
|
||||
"integrity": "sha512-n9Wa6yB+vDsGuA8AKbl/0z7HbvWqt5jxIdvr1IUicd0ryPrk7/xzwqLv8D9AbbvZ6avVNtXYLTfmgFHkwkyelg==",
|
||||
"version": "1.5.384",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.384.tgz",
|
||||
"integrity": "sha512-g6KAKY1vkYsADvSPWvdJsuYT0ixdcu6lUtD9P/wJKGBEDlZVXh2AX42j1mPqqaQPDluWjara9ziQ7xqAeXCt5A==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
@@ -4777,9 +4768,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-lexer": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.2.0.tgz",
|
||||
"integrity": "sha512-3lGxdTXCLfe1MYfTz1y2ksAAUM4NAOP6rPEjxGJVKO7TZ5+tvHCaQWGpC4Y3IXvW3ece0Cz1cIP4FWBxOnGCTQ==",
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",
|
||||
"integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
@@ -5700,9 +5691,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/i18next": {
|
||||
"version": "26.3.3",
|
||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.3.tgz",
|
||||
"integrity": "sha512-aYVegyBdXSO93CMMihvr47jI7GHSOcIahMpJX+qzUXDzW4xDJf2uenIA+45vDU+YhiVdcfsql70AC9RVdMNrHg==",
|
||||
"version": "26.3.4",
|
||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.4.tgz",
|
||||
"integrity": "sha512-pa7m0d7pBDqGHZxljT+WPFeyFgQ7P7SciPPo1tTqYuO0z4sqADYhwnBESmmGp/wEof1inwdls/k8ZgTg8rxFHA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
@@ -5758,9 +5749,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/immer": {
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",
|
||||
"integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",
|
||||
"version": "11.1.9",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.9.tgz",
|
||||
"integrity": "sha512-sc/z0Cyti70bZa0ZU4sWfAElfovFb9Ni8tArJZLuklYWxegPiK3pDOql1Rq5H0FIRAW9LSQRG6OX4KqBldbhBA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
@@ -7690,9 +7681,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.0.tgz",
|
||||
"integrity": "sha512-pTTGt8J+ji1NOmYnjzT+bAJy/1zD+Jp4ziO6cL7T3ZLvXKtusO7BpFqlRXitqpcPVqllsIXFHRMt+2/k3Xn6HQ==",
|
||||
"version": "7.18.1",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
|
||||
"integrity": "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
@@ -7712,12 +7703,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.0.tgz",
|
||||
"integrity": "sha512-Fi0yY6kgtKae/Th2xibdWK0KSdYZ4B53Gyf6wRtomOKWgpNm7H7+DyfDhncdz9FKbpS+1jmDhg3F4WoGJ+yFOA==",
|
||||
"version": "7.18.1",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.1.tgz",
|
||||
"integrity": "sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.18.0"
|
||||
"react-router": "7.18.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
@@ -7748,9 +7739,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/recharts": {
|
||||
"version": "3.9.0",
|
||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.9.0.tgz",
|
||||
"integrity": "sha512-dCEcE9y20c8H2tkVeByrAXhhnBJk6/QLbxKmn+dJUptOfc5NMjwRh1jo0vZPRLD+5dMrHrP+hPEsfbGBMfnf5Q==",
|
||||
"version": "3.9.1",
|
||||
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.9.1.tgz",
|
||||
"integrity": "sha512-WMcwlXcB7l+BbxiEdyClkG+1sxrMHNZpzT577LEvU4+rXPd8oTAy1wXk72hnk2KOOmxuLvw3z5DtXT7HEAydtg==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"www"
|
||||
@@ -7761,7 +7752,7 @@
|
||||
"decimal.js-light": "^2.5.1",
|
||||
"es-toolkit": "^1.39.3",
|
||||
"eventemitter3": "^5.0.1",
|
||||
"immer": "^10.1.1",
|
||||
"immer": "^11.1.8",
|
||||
"react-redux": "8.x.x || 9.x.x",
|
||||
"reselect": "5.2.0",
|
||||
"tiny-invariant": "^1.3.3",
|
||||
@@ -7927,13 +7918,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.3.tgz",
|
||||
"integrity": "sha512-1F1eEtUBtFvcGm1HQ9TiUIUHPQG7mSAODrhIzjxoUEFuo8OcbrGLiVLkevNgj84TE4lnHvnumwFjhJO5Eu135g==",
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.4.tgz",
|
||||
"integrity": "sha512-IjZYiLxZwpnhwhdBH2ugdTGVSdhCQUmLxLoqyjiL0JxYjyRst+5a0P3xfrTxJ5F638j4Mvvw5FAX5XE6eHpXbA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@oxc-project/types": "=0.137.0",
|
||||
"@oxc-project/types": "=0.138.0",
|
||||
"@rolldown/pluginutils": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
@@ -7943,21 +7934,21 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@rolldown/binding-android-arm64": "1.1.3",
|
||||
"@rolldown/binding-darwin-arm64": "1.1.3",
|
||||
"@rolldown/binding-darwin-x64": "1.1.3",
|
||||
"@rolldown/binding-freebsd-x64": "1.1.3",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.1.3",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.1.3",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.1.3",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.1.3",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.1.3",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.1.3",
|
||||
"@rolldown/binding-linux-x64-musl": "1.1.3",
|
||||
"@rolldown/binding-openharmony-arm64": "1.1.3",
|
||||
"@rolldown/binding-wasm32-wasi": "1.1.3",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.1.3",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.1.3"
|
||||
"@rolldown/binding-android-arm64": "1.1.4",
|
||||
"@rolldown/binding-darwin-arm64": "1.1.4",
|
||||
"@rolldown/binding-darwin-x64": "1.1.4",
|
||||
"@rolldown/binding-freebsd-x64": "1.1.4",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.1.4",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.1.4",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.1.4",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.1.4",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.1.4",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.1.4",
|
||||
"@rolldown/binding-linux-x64-musl": "1.1.4",
|
||||
"@rolldown/binding-openharmony-arm64": "1.1.4",
|
||||
"@rolldown/binding-wasm32-wasi": "1.1.4",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.1.4",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-array-concat": {
|
||||
@@ -8830,16 +8821,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/typescript-eslint": {
|
||||
"version": "8.62.0",
|
||||
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.62.0.tgz",
|
||||
"integrity": "sha512-8QxXi+ZACKX0kaqO4gY8kn0RSD9gFfaHDWwjqtEN48aWCBkX4MJaufWN+c3BzlrXLOxfywDL8CaoqUwcRq4j4Q==",
|
||||
"version": "8.62.1",
|
||||
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.62.1.tgz",
|
||||
"integrity": "sha512-vymnnM5g0AKQDSAyfP12nMIBvgwgA42syg74kkuZ4x1VuTzwQKwc5h9rGxeShCjny5o+zWAb6OEoz7XLgrIkIw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "8.62.0",
|
||||
"@typescript-eslint/parser": "8.62.0",
|
||||
"@typescript-eslint/typescript-estree": "8.62.0",
|
||||
"@typescript-eslint/utils": "8.62.0"
|
||||
"@typescript-eslint/eslint-plugin": "8.62.1",
|
||||
"@typescript-eslint/parser": "8.62.1",
|
||||
"@typescript-eslint/typescript-estree": "8.62.1",
|
||||
"@typescript-eslint/utils": "8.62.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
@@ -8971,16 +8962,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "8.1.0",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.0.tgz",
|
||||
"integrity": "sha512-BuJcQK/56NQTWDGn4ABea3q4SSBdNPWwNZKTkkUpcMPnLoquSYH8llRtSUIgoL1KSCpHt5eghLShn50mH36y7Q==",
|
||||
"version": "8.1.3",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.3.tgz",
|
||||
"integrity": "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lightningcss": "^1.32.0",
|
||||
"picomatch": "^4.0.4",
|
||||
"postcss": "^8.5.15",
|
||||
"rolldown": "~1.1.2",
|
||||
"postcss": "^8.5.16",
|
||||
"rolldown": "~1.1.3",
|
||||
"tinyglobby": "^0.2.17"
|
||||
},
|
||||
"bin": {
|
||||
|
||||
@@ -24,21 +24,22 @@
|
||||
"@ant-design/icons": "^6.3.2",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@noble/hashes": "^2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@tanstack/react-query-devtools": "^5.101.2",
|
||||
"antd": "^6.5.0",
|
||||
"axios": "^1.18.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"dayjs": "^1.11.21",
|
||||
"i18next": "^26.3.3",
|
||||
"i18next": "^26.3.4",
|
||||
"otpauth": "^9.5.1",
|
||||
"persian-calendar-suite": "^1.5.5",
|
||||
"qs": "^6.15.3",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-i18next": "^17.0.8",
|
||||
"react-router-dom": "^7.18.0",
|
||||
"recharts": "^3.9.0",
|
||||
"react-router-dom": "^7.18.1",
|
||||
"recharts": "^3.9.1",
|
||||
"swagger-ui-react": "^5.32.8",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
@@ -57,8 +58,8 @@
|
||||
"globals": "^17.7.0",
|
||||
"jsdom": "^29.1.1",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.62.0",
|
||||
"vite": "8.1.0",
|
||||
"typescript-eslint": "^8.62.1",
|
||||
"vite": "8.1.3",
|
||||
"vitest": "^4.1.9"
|
||||
},
|
||||
"overrides": {
|
||||
|
||||
@@ -1824,10 +1824,21 @@
|
||||
},
|
||||
"InboundOption": {
|
||||
"properties": {
|
||||
"enable": {
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"listen": {
|
||||
"type": "string"
|
||||
},
|
||||
"nodeAddress": {
|
||||
"description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
|
||||
"type": "string"
|
||||
},
|
||||
"nodeId": {
|
||||
"description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).",
|
||||
"nullable": true,
|
||||
@@ -1845,6 +1856,12 @@
|
||||
"example": "VLESS-443",
|
||||
"type": "string"
|
||||
},
|
||||
"shareAddr": {
|
||||
"type": "string"
|
||||
},
|
||||
"shareAddrStrategy": {
|
||||
"type": "string"
|
||||
},
|
||||
"ssMethod": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1867,6 +1884,7 @@
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enable",
|
||||
"id",
|
||||
"port",
|
||||
"protocol",
|
||||
@@ -2147,6 +2165,34 @@
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"PanelUpdateStatus": {
|
||||
"description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.",
|
||||
"properties": {
|
||||
"exitCode": {
|
||||
"example": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"finishedAt": {
|
||||
"example": 1735689612,
|
||||
"type": "integer"
|
||||
},
|
||||
"runId": {
|
||||
"example": "1735689600123456789",
|
||||
"type": "string"
|
||||
},
|
||||
"state": {
|
||||
"example": "success",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"exitCode",
|
||||
"finishedAt",
|
||||
"runId",
|
||||
"state"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ProbeResultUI": {
|
||||
"properties": {
|
||||
"cpuPct": {
|
||||
@@ -2754,11 +2800,16 @@
|
||||
"success": true,
|
||||
"obj": [
|
||||
{
|
||||
"enable": true,
|
||||
"id": 1,
|
||||
"listen": "",
|
||||
"nodeAddress": "",
|
||||
"nodeId": null,
|
||||
"port": 443,
|
||||
"protocol": "vless",
|
||||
"remark": "VLESS-443",
|
||||
"shareAddr": "",
|
||||
"shareAddrStrategy": "",
|
||||
"ssMethod": "",
|
||||
"tag": "in-443-tcp",
|
||||
"tlsFlowCapable": true,
|
||||
@@ -3901,6 +3952,47 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/panel/api/server/getUpdateStatus": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Server"
|
||||
],
|
||||
"summary": "Report the outcome of the most recently launched panel self-update (see POST updatePanel). Compare the returned runId against the one updatePanel returned to tell this run apart from a stale result.",
|
||||
"operationId": "get_panel_api_server_getUpdateStatus",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Successful response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"success": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"msg": {
|
||||
"type": "string"
|
||||
},
|
||||
"obj": {
|
||||
"$ref": "#/components/schemas/PanelUpdateStatus"
|
||||
}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"success": true,
|
||||
"obj": {
|
||||
"exitCode": 0,
|
||||
"finishedAt": 1735689612,
|
||||
"runId": "1735689600123456789",
|
||||
"state": "success"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/panel/api/server/getConfigJson": {
|
||||
"get": {
|
||||
"tags": [
|
||||
@@ -4427,6 +4519,12 @@
|
||||
},
|
||||
"obj": {}
|
||||
}
|
||||
},
|
||||
"example": {
|
||||
"success": true,
|
||||
"obj": {
|
||||
"runId": "1735689600123456789"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,10 @@ export interface RemoteInboundOption {
|
||||
|
||||
export function useNodeMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.nodes.root() });
|
||||
const invalidate = () => {
|
||||
queryClient.invalidateQueries({ queryKey: keys.nodes.root() });
|
||||
queryClient.invalidateQueries({ queryKey: keys.inbounds.options() });
|
||||
};
|
||||
|
||||
const createMut = useMutation({
|
||||
mutationFn: (payload: Partial<NodeRecord>) =>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Tag } from 'antd';
|
||||
|
||||
import { SizeFormatter } from '@/utils';
|
||||
import type { ClientSpeedEntry } from '@/hooks/useClients';
|
||||
|
||||
export type { ClientSpeedEntry };
|
||||
|
||||
export function isActiveSpeed(speed?: ClientSpeedEntry): speed is ClientSpeedEntry {
|
||||
return !!speed && (speed.up > 0 || speed.down > 0);
|
||||
}
|
||||
|
||||
interface ClientSpeedTagProps {
|
||||
speed: ClientSpeedEntry;
|
||||
}
|
||||
|
||||
export function ClientSpeedTag({ speed }: ClientSpeedTagProps) {
|
||||
return (
|
||||
<Tag color="blue">
|
||||
↑ {SizeFormatter.speedFormat(speed.up)}
|
||||
{' / '}
|
||||
↓ {SizeFormatter.speedFormat(speed.down)}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
export default ClientSpeedTag;
|
||||
Vendored
+1
@@ -18,6 +18,7 @@ interface SubPageData {
|
||||
links?: string[];
|
||||
emails?: string[];
|
||||
datepicker?: 'gregorian' | 'jalalian';
|
||||
announce?: string;
|
||||
downloadByte?: string | number;
|
||||
uploadByte?: string | number;
|
||||
usedByte?: string | number;
|
||||
|
||||
@@ -399,11 +399,16 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"xver": 0
|
||||
},
|
||||
"InboundOption": {
|
||||
"enable": true,
|
||||
"id": 1,
|
||||
"listen": "",
|
||||
"nodeAddress": "",
|
||||
"nodeId": null,
|
||||
"port": 443,
|
||||
"protocol": "vless",
|
||||
"remark": "VLESS-443",
|
||||
"shareAddr": "",
|
||||
"shareAddrStrategy": "",
|
||||
"ssMethod": "",
|
||||
"tag": "in-443-tcp",
|
||||
"tlsFlowCapable": true,
|
||||
@@ -468,6 +473,12 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"total": 0,
|
||||
"up": 0
|
||||
},
|
||||
"PanelUpdateStatus": {
|
||||
"exitCode": 0,
|
||||
"finishedAt": 1735689612,
|
||||
"runId": "1735689600123456789",
|
||||
"state": "success"
|
||||
},
|
||||
"ProbeResultUI": {
|
||||
"cpuPct": 12.5,
|
||||
"error": "",
|
||||
|
||||
@@ -1798,10 +1798,21 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
},
|
||||
"InboundOption": {
|
||||
"properties": {
|
||||
"enable": {
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"listen": {
|
||||
"type": "string"
|
||||
},
|
||||
"nodeAddress": {
|
||||
"description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
|
||||
"type": "string"
|
||||
},
|
||||
"nodeId": {
|
||||
"description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).",
|
||||
"nullable": true,
|
||||
@@ -1819,6 +1830,12 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"example": "VLESS-443",
|
||||
"type": "string"
|
||||
},
|
||||
"shareAddr": {
|
||||
"type": "string"
|
||||
},
|
||||
"shareAddrStrategy": {
|
||||
"type": "string"
|
||||
},
|
||||
"ssMethod": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1841,6 +1858,7 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enable",
|
||||
"id",
|
||||
"port",
|
||||
"protocol",
|
||||
@@ -2121,6 +2139,34 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"PanelUpdateStatus": {
|
||||
"description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.",
|
||||
"properties": {
|
||||
"exitCode": {
|
||||
"example": 0,
|
||||
"type": "integer"
|
||||
},
|
||||
"finishedAt": {
|
||||
"example": 1735689612,
|
||||
"type": "integer"
|
||||
},
|
||||
"runId": {
|
||||
"example": "1735689600123456789",
|
||||
"type": "string"
|
||||
},
|
||||
"state": {
|
||||
"example": "success",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"exitCode",
|
||||
"finishedAt",
|
||||
"runId",
|
||||
"state"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ProbeResultUI": {
|
||||
"properties": {
|
||||
"cpuPct": {
|
||||
|
||||
@@ -393,11 +393,16 @@ export interface InboundFallback {
|
||||
}
|
||||
|
||||
export interface InboundOption {
|
||||
enable: boolean;
|
||||
id: number;
|
||||
listen?: string;
|
||||
nodeAddress?: string;
|
||||
nodeId?: number | null;
|
||||
port: number;
|
||||
protocol: string;
|
||||
remark: string;
|
||||
shareAddr?: string;
|
||||
shareAddrStrategy?: string;
|
||||
ssMethod: string;
|
||||
tag: string;
|
||||
tlsFlowCapable: boolean;
|
||||
@@ -464,6 +469,13 @@ export interface OutboundTraffics {
|
||||
up: number;
|
||||
}
|
||||
|
||||
export interface PanelUpdateStatus {
|
||||
exitCode: number;
|
||||
finishedAt: number;
|
||||
runId: string;
|
||||
state: string;
|
||||
}
|
||||
|
||||
export interface ProbeResultUI {
|
||||
cpuPct: number;
|
||||
error: string;
|
||||
|
||||
@@ -420,11 +420,16 @@ export const InboundFallbackSchema = z.object({
|
||||
export type InboundFallback = z.infer<typeof InboundFallbackSchema>;
|
||||
|
||||
export const InboundOptionSchema = z.object({
|
||||
enable: z.boolean(),
|
||||
id: z.number().int(),
|
||||
listen: z.string().optional(),
|
||||
nodeAddress: z.string().optional(),
|
||||
nodeId: z.number().int().nullable().optional(),
|
||||
port: z.number().int(),
|
||||
protocol: z.string(),
|
||||
remark: z.string(),
|
||||
shareAddr: z.string().optional(),
|
||||
shareAddrStrategy: z.string().optional(),
|
||||
ssMethod: z.string(),
|
||||
tag: z.string(),
|
||||
tlsFlowCapable: z.boolean(),
|
||||
@@ -495,6 +500,14 @@ export const OutboundTrafficsSchema = z.object({
|
||||
});
|
||||
export type OutboundTraffics = z.infer<typeof OutboundTrafficsSchema>;
|
||||
|
||||
export const PanelUpdateStatusSchema = z.object({
|
||||
exitCode: z.number().int(),
|
||||
finishedAt: z.number().int(),
|
||||
runId: z.string(),
|
||||
state: z.string(),
|
||||
});
|
||||
export type PanelUpdateStatus = z.infer<typeof PanelUpdateStatusSchema>;
|
||||
|
||||
export const ProbeResultUISchema = z.object({
|
||||
cpuPct: z.number(),
|
||||
error: z.string(),
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
type BulkDetachResult,
|
||||
} from '@/schemas/client';
|
||||
import { DefaultsPayloadSchema } from '@/schemas/defaults';
|
||||
import { TRAFFIC_POLL_INTERVAL_S } from '@/lib/traffic/poll-interval';
|
||||
|
||||
// One row sent to POST /clients/:email/externalLinks.
|
||||
export type ExternalLinkInput = { kind: 'link' | 'subscription'; value: string; remark: string };
|
||||
@@ -75,6 +76,11 @@ const DEFAULT_SUMMARY: ClientsSummary = {
|
||||
total: 0, active: 0, online: [], depleted: [], expiring: [], deactive: [],
|
||||
};
|
||||
|
||||
export interface ClientSpeedEntry {
|
||||
up: number;
|
||||
down: number;
|
||||
}
|
||||
|
||||
type ClientStatRow = ClientTraffic & { email?: string };
|
||||
|
||||
// Mirror of the server's buildClientsSummary (web/service/client.go). The
|
||||
@@ -264,6 +270,7 @@ export function useClients() {
|
||||
// back to the server-computed summary until the first event lands, and keeps
|
||||
// the server's authoritative total for the headline count.
|
||||
const [allClientStats, setAllClientStats] = useState<ClientStatRow[]>([]);
|
||||
const [clientSpeed, setClientSpeed] = useState<Record<string, ClientSpeedEntry>>({});
|
||||
const summary = useMemo<ClientsSummary>(() => {
|
||||
const serverSummary = listQuery.data?.summary ?? DEFAULT_SUMMARY;
|
||||
if (allClientStats.length === 0) return serverSummary;
|
||||
@@ -543,17 +550,31 @@ export function useClients() {
|
||||
|
||||
const applyTrafficEvent = useCallback((payload: unknown) => {
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
const p = payload as { onlineClients?: string[] };
|
||||
const p = payload as {
|
||||
onlineClients?: string[];
|
||||
clientTraffics?: { email: string; up: number; down: number }[];
|
||||
};
|
||||
if (Array.isArray(p.onlineClients)) {
|
||||
queryClient.setQueryData(keys.clients.onlines(), p.onlineClients);
|
||||
}
|
||||
if (Array.isArray(p.clientTraffics)) {
|
||||
const next: Record<string, ClientSpeedEntry> = {};
|
||||
for (const ct of p.clientTraffics) {
|
||||
if (!ct || !ct.email) continue;
|
||||
next[ct.email] = {
|
||||
up: (ct.up || 0) / TRAFFIC_POLL_INTERVAL_S,
|
||||
down: (ct.down || 0) / TRAFFIC_POLL_INTERVAL_S,
|
||||
};
|
||||
}
|
||||
setClientSpeed(next);
|
||||
}
|
||||
}, [queryClient]);
|
||||
|
||||
const applyClientStatsEvent = useCallback((payload: unknown) => {
|
||||
if (!payload || typeof payload !== 'object') return;
|
||||
const p = payload as { clients?: ClientStatRow[] };
|
||||
const p = payload as { clients?: ClientStatRow[]; snapshot?: boolean };
|
||||
if (!Array.isArray(p.clients) || p.clients.length === 0) return;
|
||||
setAllClientStats(p.clients);
|
||||
if (p.snapshot !== false) setAllClientStats(p.clients);
|
||||
const byEmail = new Map<string, ClientTraffic>();
|
||||
for (const row of p.clients) {
|
||||
if (row && row.email) byEmail.set(row.email, row);
|
||||
@@ -629,6 +650,7 @@ export function useClients() {
|
||||
exportClients,
|
||||
importClients,
|
||||
setEnable,
|
||||
clientSpeed,
|
||||
applyTrafficEvent,
|
||||
applyClientStatsEvent,
|
||||
};
|
||||
|
||||
@@ -17,8 +17,9 @@ import {
|
||||
const DIRTY_POLL_MS = 1000;
|
||||
const DEFAULT_TEST_URL = 'https://www.google.com/generate_204';
|
||||
// One HTTP-mode batch request tests this many outbounds through a single
|
||||
// shared temp xray instance; chunking keeps responses bounded (~15s worst
|
||||
// case) and lands Test All results progressively.
|
||||
// shared temp xray instance; chunking keeps responses bounded (~30s worst
|
||||
// case — each probe is a cold plus a warm request) and lands Test All
|
||||
// results progressively.
|
||||
const HTTP_BATCH_CHUNK = 16;
|
||||
|
||||
export function isUdpOutbound(outbound: unknown): boolean {
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const TRAFFIC_POLL_INTERVAL_S = 5;
|
||||
@@ -13,7 +13,7 @@ import type { Sniffing } from '@/schemas/primitives';
|
||||
import type { z } from 'zod';
|
||||
import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize';
|
||||
import { canEnableSniffing } from '@/lib/xray/protocol-capabilities';
|
||||
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
|
||||
import { XHttpStreamSettingsSchema, XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
|
||||
|
||||
const XMUX_DEFAULTS = XHttpXmuxSchema.parse({});
|
||||
|
||||
@@ -164,7 +164,9 @@ export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues {
|
||||
const streamRecord = streamSettings as unknown as Record<string, unknown>;
|
||||
const xh = streamRecord.xhttpSettings;
|
||||
if (xh && typeof xh === 'object' && !Array.isArray(xh)) {
|
||||
const xhttp = xh as Record<string, unknown>;
|
||||
const parsed = XHttpStreamSettingsSchema.safeParse(xh);
|
||||
const xhttp = (parsed.success ? parsed.data : xh) as Record<string, unknown>;
|
||||
streamRecord.xhttpSettings = xhttp;
|
||||
const xmux = xhttp.xmux;
|
||||
if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) {
|
||||
xhttp.enableXmux = true;
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { XHttpStreamSettings } from '@/schemas/protocols/stream/xhttp';
|
||||
|
||||
import { getHeaderValue } from './headers';
|
||||
import { canEnableTlsFlow } from './protocol-capabilities';
|
||||
import { deriveSpiderX } from './spider-x';
|
||||
|
||||
// Share-link generators. Each per-protocol fn takes a typed inbound plus
|
||||
// client overrides and returns a URL (or '' when the protocol doesn't
|
||||
@@ -322,6 +323,7 @@ export interface GenVlessLinkInput {
|
||||
forceTls?: ForceTls;
|
||||
remark?: string;
|
||||
clientId: string;
|
||||
clientKey?: string;
|
||||
flow?: VlessClient['flow'];
|
||||
externalProxy?: ExternalProxyEntry | null;
|
||||
}
|
||||
@@ -350,6 +352,7 @@ export function genVlessLink(input: GenVlessLinkInput): string {
|
||||
forceTls = 'same',
|
||||
remark = '',
|
||||
clientId,
|
||||
clientKey = '',
|
||||
flow = '',
|
||||
externalProxy = null,
|
||||
} = input;
|
||||
@@ -430,7 +433,8 @@ export function genVlessLink(input: GenVlessLinkInput): string {
|
||||
if (sni && sni.length > 0) params.set('sni', sni);
|
||||
|
||||
if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
|
||||
if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX);
|
||||
const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
|
||||
if (spx.length > 0) params.set('spx', spx);
|
||||
if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
|
||||
}
|
||||
} else {
|
||||
@@ -512,7 +516,7 @@ function writeTlsParams(stream: NonNullable<Inbound['streamSettings']>, params:
|
||||
|
||||
// Reality query-string writer shared by VLESS and Trojan. Preserves the
|
||||
// legacy SNI-omission quirk (see genVlessLink for the full story).
|
||||
function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void {
|
||||
function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams, clientKey: string): void {
|
||||
if (stream.security !== 'reality') return;
|
||||
const reality = stream.realitySettings;
|
||||
params.set('pbk', reality.settings.publicKey);
|
||||
@@ -526,7 +530,8 @@ function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, para
|
||||
if (sni && sni.length > 0) params.set('sni', sni);
|
||||
|
||||
if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
|
||||
if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX);
|
||||
const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
|
||||
if (spx.length > 0) params.set('spx', spx);
|
||||
if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
|
||||
}
|
||||
|
||||
@@ -537,6 +542,7 @@ export interface GenTrojanLinkInput {
|
||||
forceTls?: ForceTls;
|
||||
remark?: string;
|
||||
clientPassword: string;
|
||||
clientKey?: string;
|
||||
externalProxy?: ExternalProxyEntry | null;
|
||||
}
|
||||
|
||||
@@ -551,6 +557,7 @@ export function genTrojanLink(input: GenTrojanLinkInput): string {
|
||||
forceTls = 'same',
|
||||
remark = '',
|
||||
clientPassword,
|
||||
clientKey = '',
|
||||
externalProxy = null,
|
||||
} = input;
|
||||
|
||||
@@ -571,7 +578,7 @@ export function genTrojanLink(input: GenTrojanLinkInput): string {
|
||||
applyExternalProxyTLSParams(externalProxy, params, security);
|
||||
} else if (security === 'reality') {
|
||||
params.set('security', 'reality');
|
||||
writeRealityParams(stream, params);
|
||||
writeRealityParams(stream, params, clientKey);
|
||||
} else {
|
||||
params.set('security', 'none');
|
||||
}
|
||||
@@ -960,20 +967,51 @@ function isShareableHost(host: string): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
function shareableListen(inbound: Inbound): string {
|
||||
const listen = inbound.listen.trim();
|
||||
return listen.length > 0 && !isUnixSocketListen(listen) && isShareableHost(listen)
|
||||
? normalizeShareHost(listen)
|
||||
function shareableListenFrom(listen: string): string {
|
||||
const trimmed = listen.trim();
|
||||
return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
|
||||
? normalizeShareHost(trimmed)
|
||||
: '';
|
||||
}
|
||||
|
||||
type ShareAddrStrategy = 'node' | 'listen' | 'custom';
|
||||
|
||||
function shareAddrStrategy(inbound: Inbound): ShareAddrStrategy {
|
||||
const strategy = inbound.shareAddrStrategy;
|
||||
return strategy === 'listen' || strategy === 'custom'
|
||||
? strategy
|
||||
: 'node';
|
||||
function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
|
||||
return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
|
||||
}
|
||||
|
||||
// ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
|
||||
// holding only a lightweight projection (e.g. the clients page InboundOption)
|
||||
// can pick the same host as the full-inbound share/QR path.
|
||||
export interface ShareHostFields {
|
||||
listen?: string;
|
||||
shareAddr?: string;
|
||||
shareAddrStrategy?: string;
|
||||
}
|
||||
|
||||
// resolveShareHost picks the host that goes into share/QR links, the browser-side
|
||||
// analog of the backend resolveInboundAddress. hostOverride is the hosting node's
|
||||
// address (empty for this panel's own inbounds); fallbackHostname is the
|
||||
// already-resolved panel/public host used as the last resort — kept verbatim when
|
||||
// it fails normalization (e.g. an underscore intranet hostname) so the last
|
||||
// resort never degrades to an empty host.
|
||||
export function resolveShareHost(
|
||||
fields: ShareHostFields,
|
||||
hostOverride: string,
|
||||
fallbackHostname: string,
|
||||
): string {
|
||||
const nodeAddr = normalizeShareHost(hostOverride);
|
||||
const listenAddr = shareableListenFrom(fields.listen ?? '');
|
||||
const customAddr = normalizeShareHost(fields.shareAddr ?? '');
|
||||
const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
|
||||
switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
|
||||
case 'listen':
|
||||
return listenAddr || nodeAddr || fallbackAddr;
|
||||
case 'custom':
|
||||
return customAddr || nodeAddr || listenAddr || fallbackAddr;
|
||||
default:
|
||||
return nodeAddr || listenAddr || fallbackAddr;
|
||||
}
|
||||
}
|
||||
|
||||
// Orchestrators.
|
||||
@@ -982,18 +1020,7 @@ function shareAddrStrategy(inbound: Inbound): ShareAddrStrategy {
|
||||
// node-managed inbounds; other strategies let a row prefer its listen address
|
||||
// or a custom endpoint.
|
||||
export function resolveAddr(inbound: Inbound, hostOverride: string, fallbackHostname: string): string {
|
||||
const nodeAddr = normalizeShareHost(hostOverride);
|
||||
const listenAddr = shareableListen(inbound);
|
||||
const customAddr = normalizeShareHost(inbound.shareAddr ?? '');
|
||||
const fallbackAddr = normalizeShareHost(fallbackHostname);
|
||||
switch (shareAddrStrategy(inbound)) {
|
||||
case 'listen':
|
||||
return listenAddr || nodeAddr || fallbackAddr;
|
||||
case 'custom':
|
||||
return customAddr || nodeAddr || listenAddr || fallbackAddr;
|
||||
default:
|
||||
return nodeAddr || listenAddr || fallbackAddr;
|
||||
}
|
||||
return resolveShareHost(inbound, hostOverride, fallbackHostname);
|
||||
}
|
||||
|
||||
// A loopback browser host means the panel was reached through a tunnel (e.g.
|
||||
@@ -1017,7 +1044,13 @@ export function preferPublicHost(browserHost: string, publicHost: string): strin
|
||||
// `this.clients` getter, which used isSSMultiUser to gate). Returns null
|
||||
// for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
|
||||
// clients, and any protocol without a clients array.
|
||||
type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string };
|
||||
type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string; subId?: string };
|
||||
|
||||
// Mirror of the Go subKey: the stable per-client identity spx derivation
|
||||
// keys on — subscription id first, unique email as the fallback.
|
||||
function clientSubKey(client: ClientShape): string {
|
||||
return client.subId || client.email || '';
|
||||
}
|
||||
|
||||
export function getInboundClients(inbound: Inbound): ClientShape[] | null {
|
||||
switch (inbound.protocol) {
|
||||
@@ -1066,6 +1099,7 @@ export function genLink(input: GenLinkInput): string {
|
||||
return genVlessLink({
|
||||
inbound, address, port, forceTls, remark,
|
||||
clientId: client.id ?? '',
|
||||
clientKey: clientSubKey(client),
|
||||
flow: client.flow,
|
||||
externalProxy,
|
||||
});
|
||||
@@ -1081,6 +1115,7 @@ export function genLink(input: GenLinkInput): string {
|
||||
return genTrojanLink({
|
||||
inbound, address, port, forceTls, remark,
|
||||
clientPassword: client.password ?? '',
|
||||
clientKey: clientSubKey(client),
|
||||
externalProxy,
|
||||
});
|
||||
case 'hysteria':
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
|
||||
import { OutboundDomainStrategySchema } from '@/schemas/protocols/outbound';
|
||||
import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize';
|
||||
import { Wireguard } from '@/utils';
|
||||
import type { Sniffing, SniffingDest } from '@/schemas/primitives';
|
||||
import type { OutboundDomainStrategy } from '@/schemas/protocols/outbound';
|
||||
|
||||
import type {
|
||||
DnsOutboundFormSettings,
|
||||
@@ -56,6 +58,16 @@ function asPort(value: unknown, fallback: number): number {
|
||||
return n;
|
||||
}
|
||||
|
||||
// xray-core matches targetStrategy/domainStrategy case-insensitively;
|
||||
// normalize the wire value to the canonical spelling or '' (= AsIs).
|
||||
function targetStrategyFromWire(value: unknown): OutboundDomainStrategy | '' {
|
||||
const s = asString(value);
|
||||
if (!s) return '';
|
||||
return OutboundDomainStrategySchema.options.find(
|
||||
(v) => v.toLowerCase() === s.toLowerCase(),
|
||||
) ?? '';
|
||||
}
|
||||
|
||||
const SNIFFING_DEST_VALUES: readonly SniffingDest[] = ['http', 'tls', 'quic', 'fakedns'];
|
||||
|
||||
const SNIFFING_DEFAULT: Sniffing = {
|
||||
@@ -285,14 +297,9 @@ function freedomFromWire(raw: Raw): FreedomOutboundFormSettings {
|
||||
&& typeof raw.fragment === 'object'
|
||||
&& Object.keys(fragment).length > 0;
|
||||
return {
|
||||
domainStrategy: ((): FreedomOutboundFormSettings['domainStrategy'] => {
|
||||
const allowed = [
|
||||
'AsIs', 'UseIP', 'UseIPv4', 'UseIPv6', 'UseIPv6v4', 'UseIPv4v6',
|
||||
'ForceIP', 'ForceIPv6v4', 'ForceIPv6', 'ForceIPv4v6', 'ForceIPv4',
|
||||
];
|
||||
const s = asString(raw.domainStrategy);
|
||||
return (allowed.includes(s) ? s : '') as FreedomOutboundFormSettings['domainStrategy'];
|
||||
})(),
|
||||
domainStrategy: targetStrategyFromWire(
|
||||
asString(raw.targetStrategy) || asString(raw.domainStrategy),
|
||||
),
|
||||
redirect: asString(raw.redirect),
|
||||
userLevel: asNumber(raw.userLevel, 0),
|
||||
proxyProtocol: ((): FreedomOutboundFormSettings['proxyProtocol'] => {
|
||||
@@ -374,6 +381,7 @@ export interface RawOutboundRow {
|
||||
tag?: string;
|
||||
protocol?: string;
|
||||
sendThrough?: string;
|
||||
targetStrategy?: string;
|
||||
settings?: unknown;
|
||||
streamSettings?: unknown;
|
||||
mux?: unknown;
|
||||
@@ -401,6 +409,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
|
||||
const settings = asObject(raw.settings);
|
||||
const tag = asString(raw.tag);
|
||||
const sendThrough = asString(raw.sendThrough);
|
||||
const targetStrategy = targetStrategyFromWire(raw.targetStrategy);
|
||||
const mux = muxFromWire(raw.mux);
|
||||
const hasStream = raw.streamSettings
|
||||
&& typeof raw.streamSettings === 'object'
|
||||
@@ -430,6 +439,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
|
||||
...typed,
|
||||
tag,
|
||||
sendThrough,
|
||||
targetStrategy,
|
||||
mux,
|
||||
streamSettings,
|
||||
};
|
||||
@@ -543,6 +553,8 @@ function hysteriaToWire(s: HysteriaOutboundFormSettings) {
|
||||
}
|
||||
|
||||
function freedomToWire(s: FreedomOutboundFormSettings) {
|
||||
// The strategy is emitted under the legacy domainStrategy key: new cores
|
||||
// fall back to it when targetStrategy is absent, old cores only know it.
|
||||
// Legacy semantics: emit fragment only when the user actually populated
|
||||
// at least one of the four sub-fields. Defaults like packets='1-3' alone
|
||||
// are not enough — the modal's Fragment Switch sets all four together.
|
||||
@@ -672,6 +684,7 @@ export function formValuesToWirePayload(values: OutboundFormValues): WireOutboun
|
||||
settings,
|
||||
};
|
||||
if (values.tag) result.tag = values.tag;
|
||||
if (values.targetStrategy) result.targetStrategy = values.targetStrategy;
|
||||
|
||||
// streamSettings emission gates on canEnableStream — non-stream protocols
|
||||
// still emit just `sockopt` if that key is present (legacy behavior).
|
||||
|
||||
@@ -218,6 +218,7 @@ function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
|
||||
try {
|
||||
const parsed = JSON.parse(fm) as Record<string, unknown>;
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
sanitizeFinalMaskQuicParams(parsed);
|
||||
stream.finalmask = parsed;
|
||||
}
|
||||
} catch {
|
||||
@@ -225,6 +226,68 @@ function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
|
||||
}
|
||||
}
|
||||
|
||||
const QUIC_PARAMS_NUMERIC_KEYS = [
|
||||
'initStreamReceiveWindow',
|
||||
'maxStreamReceiveWindow',
|
||||
'initConnectionReceiveWindow',
|
||||
'maxConnectionReceiveWindow',
|
||||
'maxIdleTimeout',
|
||||
'keepAlivePeriod',
|
||||
'maxIncomingStreams',
|
||||
] as const;
|
||||
|
||||
const DURATION_SECONDS: Record<string, number> = { ms: 0.001, s: 1, m: 60, h: 3600 };
|
||||
|
||||
const QUIC_NUMERIC_MAX = 1e15;
|
||||
|
||||
function coerceQuicNumeric(value: unknown): number | null {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return Math.trunc(value);
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const asNumber = Number(value);
|
||||
if (value.trim() !== '' && Number.isFinite(asNumber)) {
|
||||
return Math.trunc(asNumber);
|
||||
}
|
||||
const duration = /^(-?\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value.trim());
|
||||
if (duration) {
|
||||
return Math.trunc(Number(duration[1]) * DURATION_SECONDS[duration[2]]);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function clampQuicNumeric(key: string, n: number): number | null {
|
||||
if (n < 0 || n > QUIC_NUMERIC_MAX) return null;
|
||||
if (n === 0) return 0;
|
||||
if (key === 'keepAlivePeriod') return Math.min(Math.max(n, 2), 60);
|
||||
if (key === 'maxIdleTimeout') return Math.min(Math.max(n, 4), 120);
|
||||
if (key === 'maxIncomingStreams') return Math.max(n, 8);
|
||||
return n;
|
||||
}
|
||||
|
||||
// xray-core rejects the whole config when these quicParams fields are not
|
||||
// plain integers within its accepted ranges (keepAlivePeriod 0 or 2-60,
|
||||
// maxIdleTimeout 0 or 4-120, maxIncomingStreams 0 or >= 8), so coerce
|
||||
// numeric/duration strings, clamp the ranged fields, and drop anything
|
||||
// unparseable, negative, or absurdly large (#5783). Mirrors the Go parser in
|
||||
// internal/util/link/outbound.go.
|
||||
function sanitizeFinalMaskQuicParams(parsed: Record<string, unknown>): void {
|
||||
const raw = parsed.quicParams;
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
|
||||
const quic = raw as Record<string, unknown>;
|
||||
for (const key of QUIC_PARAMS_NUMERIC_KEYS) {
|
||||
if (!(key in quic)) continue;
|
||||
const coerced = coerceQuicNumeric(quic[key]);
|
||||
const clamped = coerced === null ? null : clampQuicNumeric(key, coerced);
|
||||
if (clamped === null) {
|
||||
delete quic[key];
|
||||
continue;
|
||||
}
|
||||
quic[key] = clamped;
|
||||
}
|
||||
}
|
||||
|
||||
function applySecurityParams(stream: Raw, params: URLSearchParams): void {
|
||||
if (stream.security === 'tls') {
|
||||
const tls = stream.tlsSettings as Raw;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
|
||||
|
||||
// Mirrors deriveSpiderX in internal/sub/service.go byte-for-byte so panel
|
||||
// links and subscription links agree; returns '' when there is no seed and
|
||||
// no client key (the caller then omits spx, as the legacy builder did).
|
||||
export function deriveSpiderX(seed: string, clientKey: string): string {
|
||||
if (!seed && !clientKey) return '';
|
||||
return `/${bytesToHex(sha256(utf8ToBytes(`${seed}|${clientKey}`))).slice(0, 15)}`;
|
||||
}
|
||||
@@ -108,6 +108,18 @@ export function validateRealityTarget(target: string): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function liftLegacyXhttpSessionKeys(obj: Record<string, unknown>): void {
|
||||
const lift = (legacy: string, renamed: string) => {
|
||||
const v = obj[legacy];
|
||||
if ((obj[renamed] === undefined || obj[renamed] === '') && typeof v === 'string' && v !== '') {
|
||||
obj[renamed] = v;
|
||||
}
|
||||
delete obj[legacy];
|
||||
};
|
||||
lift('sessionPlacement', 'sessionIDPlacement');
|
||||
lift('sessionKey', 'sessionIDKey');
|
||||
}
|
||||
|
||||
function dropEmptyStrings(obj: Record<string, unknown>, keys: readonly string[]): void {
|
||||
for (const key of keys) {
|
||||
const v = obj[key];
|
||||
@@ -160,6 +172,7 @@ export function normalizeXhttpForWire(
|
||||
side: StreamWireSide,
|
||||
): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = { ...raw };
|
||||
liftLegacyXhttpSessionKeys(out);
|
||||
const mode = typeof out.mode === 'string' && out.mode !== '' ? out.mode : 'auto';
|
||||
const enableXmux = out.enableXmux === true;
|
||||
delete out.enableXmux;
|
||||
@@ -254,7 +267,6 @@ export function normalizeSockoptForWire(
|
||||
const he = out.happyEyeballs;
|
||||
if (isRecord(he)) {
|
||||
const heOut: Record<string, unknown> = { ...he };
|
||||
if (heOut.tryDelayMs === 0) delete heOut.tryDelayMs;
|
||||
if (heOut.prioritizeIPv6 === false) delete heOut.prioritizeIPv6;
|
||||
if (heOut.interleave === 1) delete heOut.interleave;
|
||||
if (heOut.maxConcurrentTry === 4) delete heOut.maxConcurrentTry;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
export type VlessAuthKind =
|
||||
| 'x25519'
|
||||
| 'x25519_xorpub'
|
||||
| 'x25519_random'
|
||||
| 'mlkem768'
|
||||
| 'mlkem768_xorpub'
|
||||
| 'mlkem768_random';
|
||||
|
||||
export const VLESS_AUTH_LABEL_KEYS: Record<VlessAuthKind, string> = {
|
||||
x25519: 'pages.inbounds.vlessAuthX25519',
|
||||
x25519_xorpub: 'pages.inbounds.vlessAuthX25519Xorpub',
|
||||
x25519_random: 'pages.inbounds.vlessAuthX25519Random',
|
||||
mlkem768: 'pages.inbounds.vlessAuthMlkem768',
|
||||
mlkem768_xorpub: 'pages.inbounds.vlessAuthMlkem768Xorpub',
|
||||
mlkem768_random: 'pages.inbounds.vlessAuthMlkem768Random',
|
||||
};
|
||||
|
||||
const MLKEM768_MIN_KEY_LENGTH = 300;
|
||||
|
||||
export function vlessEncryptionAuthKind(encryption: string): VlessAuthKind | null {
|
||||
if (!encryption || encryption === 'none') return null;
|
||||
const parts = encryption.split('.').filter(Boolean);
|
||||
const authKey = parts[parts.length - 1] || '';
|
||||
if (!authKey) return null;
|
||||
const mode = parts[1] || 'native';
|
||||
const keyType = authKey.length > MLKEM768_MIN_KEY_LENGTH ? 'mlkem768' : 'x25519';
|
||||
if (mode === 'xorpub' || mode === 'random') return `${keyType}_${mode}`;
|
||||
return keyType;
|
||||
}
|
||||
@@ -103,6 +103,9 @@ export class AllSetting {
|
||||
hasWarpSecret = false;
|
||||
hasNordSecret = false;
|
||||
hasSmtpPassword = false;
|
||||
clearTgBotToken = false;
|
||||
clearLdapPassword = false;
|
||||
clearSmtpPassword = false;
|
||||
|
||||
constructor(data?: unknown) {
|
||||
if (data != null) {
|
||||
|
||||
@@ -323,6 +323,12 @@ export const sections: readonly Section[] = [
|
||||
path: '/panel/api/server/getPanelUpdateInfo',
|
||||
summary: 'Check whether a newer 3x-ui release is available on GitHub.',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/server/getUpdateStatus',
|
||||
summary: 'Report the outcome of the most recently launched panel self-update (see POST updatePanel). Compare the returned runId against the one updatePanel returned to tell this run apart from a stale result.',
|
||||
responseSchema: 'PanelUpdateStatus',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/server/getConfigJson',
|
||||
@@ -407,6 +413,7 @@ export const sections: readonly Section[] = [
|
||||
method: 'POST',
|
||||
path: '/panel/api/server/updatePanel',
|
||||
summary: 'Self-update the panel to the latest version. The server restarts on success.',
|
||||
response: '{\n "success": true,\n "obj": {\n "runId": "1735689600123456789"\n }\n}',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
|
||||
@@ -376,12 +376,13 @@ export default function ClientFormModal({
|
||||
const inboundOptions = useMemo(
|
||||
() => (inbounds || [])
|
||||
.filter((ib) => MULTI_CLIENT_PROTOCOLS.has(ib.protocol || ''))
|
||||
.filter((ib) => ib.enable || (form.inboundIds || []).includes(ib.id))
|
||||
.map((ib) => ({
|
||||
label: formatInboundLabel(ib.tag, ib.remark),
|
||||
value: ib.id,
|
||||
title: formatInboundLabel(ib.tag, ib.remark),
|
||||
})),
|
||||
[inbounds],
|
||||
[inbounds, form.inboundIds],
|
||||
);
|
||||
|
||||
const linkRows = useMemo(() => form.externalLinks.filter((r) => r.kind === 'link'), [form.externalLinks]);
|
||||
@@ -492,6 +493,13 @@ export default function ClientFormModal({
|
||||
if (form.wgPreSharedKey) {
|
||||
clientPayload.preSharedKey = form.wgPreSharedKey;
|
||||
}
|
||||
const allowedIPs = form.wgAllowedIPs
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s !== '');
|
||||
if (allowedIPs.length > 0) {
|
||||
clientPayload.allowedIPs = allowedIPs;
|
||||
}
|
||||
}
|
||||
|
||||
const externalLinks: ExternalLinkInput[] = form.externalLinks
|
||||
@@ -802,11 +810,16 @@ export default function ClientFormModal({
|
||||
onChange={(e) => update('wgPreSharedKey', e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
{isEdit && form.wgAllowedIPs && (
|
||||
<Form.Item label={t('pages.clients.wireguardAllowedIPs')}>
|
||||
<Input value={form.wgAllowedIPs} disabled />
|
||||
</Form.Item>
|
||||
)}
|
||||
<Form.Item
|
||||
label={t('pages.clients.wireguardAllowedIPs')}
|
||||
extra={t('pages.clients.wireguardAllowedIPsHint')}
|
||||
>
|
||||
<Input
|
||||
value={form.wgAllowedIPs}
|
||||
placeholder="10.0.0.2/32"
|
||||
onChange={(e) => update('wgAllowedIPs', e.target.value)}
|
||||
/>
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -308,6 +308,12 @@ export default function ClientInfoModal({
|
||||
<td>{t('pages.inbounds.updatedAt')}</td>
|
||||
<td><Tag>{dateLabel(client.updatedAt)}</Tag></td>
|
||||
</tr>
|
||||
{client.group && (
|
||||
<tr>
|
||||
<td>{t('pages.clients.group')}</td>
|
||||
<td><Tag color="geekblue">{client.group}</Tag></td>
|
||||
</tr>
|
||||
)}
|
||||
{client.comment && (
|
||||
<tr>
|
||||
<td>{t('pages.clients.comment')}</td>
|
||||
|
||||
@@ -162,6 +162,12 @@
|
||||
background: color-mix(in srgb, var(--ant-color-primary) 6%, transparent);
|
||||
}
|
||||
|
||||
.client-card-speed {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--ant-color-text-secondary);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -61,6 +61,7 @@ import { useNodesQuery } from '@/api/queries/useNodesQuery';
|
||||
import { useDatepicker } from '@/hooks/useDatepicker';
|
||||
import type { ClientRecord, InboundOption, ExternalLink, ExternalLinkInput } from '@/hooks/useClients';
|
||||
import ClientTrafficCell from '@/components/clients/ClientTrafficCell';
|
||||
import ClientSpeedTag, { isActiveSpeed } from '@/components/clients/ClientSpeedTag';
|
||||
import AppSidebar from '@/layouts/AppSidebar';
|
||||
import { IntlUtil, SizeFormatter } from '@/utils';
|
||||
import { setMessageInstance } from '@/utils/messageBus';
|
||||
@@ -209,6 +210,7 @@ export default function ClientsPage() {
|
||||
tgBotEnable, expireDiff, trafficDiff, pageSize,
|
||||
create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
|
||||
resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable,
|
||||
clientSpeed,
|
||||
applyTrafficEvent, applyClientStatsEvent,
|
||||
refresh,
|
||||
hydrate,
|
||||
@@ -902,6 +904,17 @@ export default function ClientsPage() {
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('pages.clients.speed'),
|
||||
key: 'speed',
|
||||
width: 110,
|
||||
align: 'center',
|
||||
render: (_v, record) => {
|
||||
const speed = clientSpeed[record.email];
|
||||
if (!isActiveSpeed(speed)) return <Tag color="default">—</Tag>;
|
||||
return <ClientSpeedTag speed={speed} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('pages.clients.remaining'),
|
||||
key: 'remaining',
|
||||
@@ -919,7 +932,7 @@ export default function ClientsPage() {
|
||||
),
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters, allGroups, datepicker, trafficDiff]);
|
||||
], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters, allGroups, datepicker, trafficDiff, clientSpeed]);
|
||||
|
||||
const tablePagination = {
|
||||
current: currentPage,
|
||||
@@ -1428,6 +1441,15 @@ export default function ClientsPage() {
|
||||
enabled={row.enable}
|
||||
trafficDiff={trafficDiff}
|
||||
/>
|
||||
{(() => {
|
||||
const speed = clientSpeed[row.email];
|
||||
if (!isActiveSpeed(speed)) return null;
|
||||
return (
|
||||
<div className="client-card-speed">
|
||||
<ClientSpeedTag speed={speed} />
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { formatInboundLabel } from '@/lib/inbounds/label';
|
||||
import { preferPublicHost } from '@/lib/xray/inbound-link';
|
||||
import { preferPublicHost, resolveShareHost } from '@/lib/xray/inbound-link';
|
||||
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
|
||||
|
||||
export function isWireguardClient(client: ClientRecord | null | undefined): boolean {
|
||||
@@ -22,7 +22,7 @@ export function buildWireguardClientConfig(
|
||||
host = window.location.hostname,
|
||||
publicHost = '',
|
||||
): string {
|
||||
const endpointHost = preferPublicHost(host, publicHost);
|
||||
const endpointHost = resolveShareHost(inbound ?? {}, inbound?.nodeAddress ?? '', preferPublicHost(host, publicHost));
|
||||
const address = client.allowedIPs || '10.0.0.2/32';
|
||||
const endpoint = `${endpointHost}:${inbound?.port || ''}`;
|
||||
const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : '';
|
||||
|
||||
@@ -50,7 +50,7 @@ export default function GroupAddClientsModal({
|
||||
if (!open) return;
|
||||
setSelectedEmails([]);
|
||||
setSearch('');
|
||||
}, [open, rows]);
|
||||
}, [open]);
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
|
||||
@@ -48,7 +48,7 @@ export default function GroupRemoveClientsModal({
|
||||
if (!open) return;
|
||||
setSelectedEmails([]);
|
||||
setSearch('');
|
||||
}, [open, rows]);
|
||||
}, [open]);
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
|
||||
@@ -41,6 +41,7 @@ import { Protocols } from '@/schemas/primitives';
|
||||
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
|
||||
import { HysteriaStreamSettingsSchema } from '@/schemas/protocols/stream/hysteria';
|
||||
import { createHysteriaTlsSettingsWithDefaultCert } from '@/lib/xray/inbound-tls-defaults';
|
||||
import { VLESS_AUTH_LABEL_KEYS, vlessEncryptionAuthKind } from '@/lib/xray/vless-encryption';
|
||||
import { SniffingSchema } from '@/schemas/primitives/sniffing';
|
||||
import { TcpStreamSettingsSchema } from '@/schemas/protocols/stream/tcp';
|
||||
import { KcpStreamSettingsSchema } from '@/schemas/protocols/stream/kcp';
|
||||
@@ -248,6 +249,7 @@ export default function InboundFormModal({
|
||||
scanRealityCandidates,
|
||||
applyRealityScanResult,
|
||||
randomizeShortIds,
|
||||
randomizeSpiderX,
|
||||
getNewEchCert,
|
||||
clearEchCert,
|
||||
pinFromCert,
|
||||
@@ -316,27 +318,14 @@ export default function InboundFormModal({
|
||||
form.setFieldValue(['settings', 'encryption'], 'none');
|
||||
};
|
||||
|
||||
const vlessAuthKind = vlessEncryptionAuthKind(
|
||||
typeof vlessEncryption === 'string' ? vlessEncryption : '',
|
||||
);
|
||||
const selectedVlessAuth = (() => {
|
||||
const enc = typeof vlessEncryption === 'string' ? vlessEncryption : '';
|
||||
if (!enc || enc === 'none') return 'None';
|
||||
const parts = enc.split('.').filter(Boolean);
|
||||
const authKey = parts[parts.length - 1] || '';
|
||||
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
|
||||
const mode = parts[1] || 'native';
|
||||
const keyType = authKey.length > 300 ? 'mlkem768' : 'x25519';
|
||||
if (mode === 'xorpub') {
|
||||
return keyType === 'mlkem768'
|
||||
? t('pages.inbounds.vlessAuthMlkem768Xorpub')
|
||||
: t('pages.inbounds.vlessAuthX25519Xorpub');
|
||||
}
|
||||
if (mode === 'random') {
|
||||
return keyType === 'mlkem768'
|
||||
? t('pages.inbounds.vlessAuthMlkem768Random')
|
||||
: t('pages.inbounds.vlessAuthX25519Random');
|
||||
}
|
||||
return keyType === 'mlkem768'
|
||||
? t('pages.inbounds.vlessAuthMlkem768')
|
||||
: t('pages.inbounds.vlessAuthX25519');
|
||||
if (!vlessAuthKind) return t('pages.inbounds.vlessAuthCustom');
|
||||
return t(VLESS_AUTH_LABEL_KEYS[vlessAuthKind]);
|
||||
})();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -539,6 +528,7 @@ export default function InboundFormModal({
|
||||
{selectableNodes.length > 0 && isNodeEligible && (
|
||||
<Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
|
||||
<Select
|
||||
showSearch
|
||||
disabled={mode === 'edit'}
|
||||
placeholder={t('pages.inbounds.localPanel')}
|
||||
allowClear
|
||||
@@ -702,7 +692,7 @@ export default function InboundFormModal({
|
||||
|
||||
{protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />}
|
||||
|
||||
{protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
|
||||
{protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} vlessAuthKind={vlessAuthKind} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
|
||||
|
||||
{isFallbackHost && fallbacksCard}
|
||||
{(protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
|
||||
@@ -896,6 +886,7 @@ export default function InboundFormModal({
|
||||
scanRealityCandidates={scanRealityCandidates}
|
||||
applyRealityScanResult={applyRealityScanResult}
|
||||
randomizeShortIds={randomizeShortIds}
|
||||
randomizeSpiderX={randomizeSpiderX}
|
||||
genRealityKeypair={genRealityKeypair}
|
||||
clearRealityKeypair={clearRealityKeypair}
|
||||
genMldsa65={genMldsa65}
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Form, Input, InputNumber, Select, Space, Typography } from 'antd';
|
||||
|
||||
type VlessAuthKind =
|
||||
| 'x25519'
|
||||
| 'x25519_xorpub'
|
||||
| 'x25519_random'
|
||||
| 'mlkem768'
|
||||
| 'mlkem768_xorpub'
|
||||
| 'mlkem768_random';
|
||||
import { VLESS_AUTH_LABEL_KEYS, type VlessAuthKind } from '@/lib/xray/vless-encryption';
|
||||
|
||||
interface VlessFieldsProps {
|
||||
saving: boolean;
|
||||
selectedVlessAuth: string;
|
||||
vlessAuthKind: VlessAuthKind | null;
|
||||
network: string;
|
||||
security: string;
|
||||
getNewVlessEnc: (kind: VlessAuthKind) => void;
|
||||
@@ -22,22 +17,22 @@ interface VlessFieldsProps {
|
||||
export default function VlessFields({
|
||||
saving,
|
||||
selectedVlessAuth,
|
||||
vlessAuthKind,
|
||||
network,
|
||||
security,
|
||||
getNewVlessEnc,
|
||||
clearVlessEnc,
|
||||
}: VlessFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const [authKind, setAuthKind] = useState<VlessAuthKind>('x25519');
|
||||
const [authKind, setAuthKind] = useState<VlessAuthKind>(vlessAuthKind ?? 'x25519');
|
||||
|
||||
const authOptions = [
|
||||
{ value: 'x25519', label: t('pages.inbounds.vlessAuthX25519') },
|
||||
{ value: 'x25519_xorpub', label: t('pages.inbounds.vlessAuthX25519Xorpub') },
|
||||
{ value: 'x25519_random', label: t('pages.inbounds.vlessAuthX25519Random') },
|
||||
{ value: 'mlkem768', label: t('pages.inbounds.vlessAuthMlkem768') },
|
||||
{ value: 'mlkem768_xorpub', label: t('pages.inbounds.vlessAuthMlkem768Xorpub') },
|
||||
{ value: 'mlkem768_random', label: t('pages.inbounds.vlessAuthMlkem768Random') },
|
||||
];
|
||||
useEffect(() => {
|
||||
setAuthKind(vlessAuthKind ?? 'x25519');
|
||||
}, [vlessAuthKind]);
|
||||
|
||||
const authOptions = (Object.entries(VLESS_AUTH_LABEL_KEYS) as [VlessAuthKind, string][]).map(
|
||||
([value, labelKey]) => ({ value, label: t(labelKey) }),
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -16,6 +16,7 @@ interface RealityFormProps {
|
||||
scanRealityCandidates: (targets?: string) => Promise<RealityScanResult[]>;
|
||||
applyRealityScanResult: (result: RealityScanResult) => void;
|
||||
randomizeShortIds: () => void;
|
||||
randomizeSpiderX: () => void;
|
||||
genRealityKeypair: () => void;
|
||||
clearRealityKeypair: () => void;
|
||||
genMldsa65: () => void;
|
||||
@@ -30,6 +31,7 @@ export default function RealityForm({
|
||||
scanRealityCandidates,
|
||||
applyRealityScanResult,
|
||||
randomizeShortIds,
|
||||
randomizeSpiderX,
|
||||
genRealityKeypair,
|
||||
clearRealityKeypair,
|
||||
genMldsa65,
|
||||
@@ -147,10 +149,18 @@ export default function RealityForm({
|
||||
</Space.Compact>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={['streamSettings', 'realitySettings', 'settings', 'spiderX']}
|
||||
label={t('pages.inbounds.form.spiderX')}
|
||||
tooltip={t('pages.inbounds.form.spiderXHint')}
|
||||
>
|
||||
<Input />
|
||||
<Space.Compact block style={{ display: 'flex' }}>
|
||||
<Form.Item
|
||||
name={['streamSettings', 'realitySettings', 'settings', 'spiderX']}
|
||||
noStyle
|
||||
>
|
||||
<Input style={{ flex: 1 }} />
|
||||
</Form.Item>
|
||||
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={randomizeSpiderX} />
|
||||
</Space.Compact>
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={['streamSettings', 'realitySettings', 'settings', 'publicKey']}
|
||||
|
||||
@@ -124,6 +124,13 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
|
||||
);
|
||||
};
|
||||
|
||||
const randomizeSpiderX = () => {
|
||||
form.setFieldValue(
|
||||
['streamSettings', 'realitySettings', 'settings', 'spiderX'],
|
||||
`/${RandomUtil.randomSeq(15)}`,
|
||||
);
|
||||
};
|
||||
|
||||
const getNewEchCert = async () => {
|
||||
const sni = form.getFieldValue(['streamSettings', 'tlsSettings', 'serverName']);
|
||||
setSaving(true);
|
||||
@@ -270,6 +277,7 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
|
||||
}
|
||||
form.setFieldValue('streamSettings', cleaned);
|
||||
if (next === 'reality') {
|
||||
randomizeSpiderX();
|
||||
try {
|
||||
const msg = await HttpUtil.get('/panel/api/server/getNewX25519Cert');
|
||||
if (msg?.success) {
|
||||
@@ -292,6 +300,7 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
|
||||
scanRealityCandidates,
|
||||
applyRealityScanResult,
|
||||
randomizeShortIds,
|
||||
randomizeSpiderX,
|
||||
getNewEchCert,
|
||||
clearEchCert,
|
||||
pinFromCert,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Card,
|
||||
Checkbox,
|
||||
Dropdown,
|
||||
Input,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
ReloadOutlined,
|
||||
InfoCircleOutlined,
|
||||
DeleteOutlined,
|
||||
SearchOutlined,
|
||||
} from '@ant-design/icons';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
@@ -56,6 +58,7 @@ export default function InboundList({
|
||||
// Node filter (#4997): 'all' shows everything, 0 is the local-panel
|
||||
// sentinel (inbounds without a nodeId), otherwise a node id. Session-only.
|
||||
const [nodeFilter, setNodeFilter] = useState<number | 'all'>('all');
|
||||
const [searchKey, setSearchKey] = useState('');
|
||||
|
||||
const showNodeFilter = useMemo(
|
||||
() => nodesById.size > 0 || dbInbounds.some((ib) => ib.nodeId != null),
|
||||
@@ -72,10 +75,17 @@ export default function InboundList({
|
||||
);
|
||||
|
||||
const visibleInbounds = useMemo(() => {
|
||||
if (nodeFilter === 'all') return dbInbounds;
|
||||
if (nodeFilter === 0) return dbInbounds.filter((ib) => ib.nodeId == null);
|
||||
return dbInbounds.filter((ib) => ib.nodeId === nodeFilter);
|
||||
}, [dbInbounds, nodeFilter]);
|
||||
let list = dbInbounds;
|
||||
if (nodeFilter === 0) list = list.filter((ib) => ib.nodeId == null);
|
||||
else if (nodeFilter !== 'all') list = list.filter((ib) => ib.nodeId === nodeFilter);
|
||||
const q = searchKey.trim().toLowerCase();
|
||||
if (!q) return list;
|
||||
return list.filter((ib) => (
|
||||
(ib.remark || '').toLowerCase().includes(q)
|
||||
|| String(ib.port).includes(q)
|
||||
|| (ib.protocol || '').toLowerCase().includes(q)
|
||||
));
|
||||
}, [dbInbounds, nodeFilter, searchKey]);
|
||||
|
||||
const onSwitchEnable = useCallback(async (dbInbound: DBInboundRecord, next: boolean) => {
|
||||
const previous = dbInbound.enable;
|
||||
@@ -174,11 +184,21 @@ export default function InboundList({
|
||||
value={nodeFilter}
|
||||
onChange={(v) => setNodeFilter(v)}
|
||||
options={nodeFilterOptions}
|
||||
showSearch
|
||||
popupMatchSelectWidth={false}
|
||||
style={{ minWidth: isMobile ? 90 : 140 }}
|
||||
aria-label={t('pages.clients.filters.nodes')}
|
||||
/>
|
||||
)}
|
||||
<Input
|
||||
value={searchKey}
|
||||
onChange={(e) => setSearchKey(e.target.value)}
|
||||
placeholder={t('search')}
|
||||
allowClear
|
||||
prefix={<SearchOutlined />}
|
||||
style={{ maxWidth: isMobile ? 110 : 200 }}
|
||||
aria-label={t('search')}
|
||||
/>
|
||||
{selectedRowKeys.length > 0 && (
|
||||
<>
|
||||
<Tag color="blue" closable onClose={() => setSelectedRowKeys([])} style={{ marginInlineEnd: 0 }}>
|
||||
|
||||
@@ -13,6 +13,7 @@ import { OnlinesSchema, OnlineByNodeSchema, ActiveInboundsByNodeSchema } from '@
|
||||
import { DefaultsPayloadSchema, type DefaultsPayload } from '@/schemas/defaults';
|
||||
|
||||
import type { InboundSpeedEntry } from './list/types';
|
||||
import { TRAFFIC_POLL_INTERVAL_S } from '@/lib/traffic/poll-interval';
|
||||
|
||||
export interface SubSettings {
|
||||
enable: boolean;
|
||||
@@ -28,10 +29,6 @@ export interface SubSettings {
|
||||
|
||||
type DBInboundInstance = InstanceType<typeof DBInbound>;
|
||||
|
||||
// Server-side traffic polling interval in seconds. XrayTrafficJob broadcasts
|
||||
// deltas accumulated over this window, so dividing by it yields bytes/sec.
|
||||
const TRAFFIC_POLL_INTERVAL_S = 5;
|
||||
|
||||
// Speed is delta-derived, so it can't be recomputed until the first poll after
|
||||
// mount; navigating away and back would otherwise blank the column for up to one
|
||||
// poll. Cache the last speed map across mounts (module scope) and reseed from it
|
||||
|
||||
@@ -6,8 +6,11 @@ import axios from 'axios';
|
||||
|
||||
import { HttpUtil, PromiseUtil } from '@/utils';
|
||||
import { formatPanelVersion } from '@/lib/panel-version';
|
||||
import type { PanelUpdateStatus } from '@/generated/types';
|
||||
import './PanelUpdateModal.css';
|
||||
|
||||
type UpdateOutcome = 'success' | 'failed' | 'timeout';
|
||||
|
||||
export interface PanelUpdateInfo {
|
||||
channel?: string;
|
||||
currentVersion: string;
|
||||
@@ -45,19 +48,23 @@ export default function PanelUpdateModal({
|
||||
|
||||
const isDev = info.channel === 'dev';
|
||||
|
||||
async function pollUntilBack(): Promise<boolean> {
|
||||
async function pollUpdateStatus(expectedRunId: string): Promise<UpdateOutcome> {
|
||||
await PromiseUtil.sleep(5000);
|
||||
const deadline = Date.now() + 90_000;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const r = await axios.get('/panel/api/server/status', { timeout: 2000 });
|
||||
if (r?.data?.success) return true;
|
||||
const r = await axios.get('/panel/api/server/getUpdateStatus', { timeout: 2000 });
|
||||
const status = r?.data?.obj as PanelUpdateStatus | undefined;
|
||||
if (status?.runId === expectedRunId) {
|
||||
if (status.state === 'success') return 'success';
|
||||
if (status.state === 'failed') return 'failed';
|
||||
}
|
||||
} catch {
|
||||
/* still restarting */
|
||||
}
|
||||
await PromiseUtil.sleep(2000);
|
||||
}
|
||||
return false;
|
||||
return 'timeout';
|
||||
}
|
||||
|
||||
async function handleChannel(checked: boolean) {
|
||||
@@ -81,14 +88,24 @@ export default function PanelUpdateModal({
|
||||
const tip = info.latestVersion ? `${baseTip} (${info.latestVersion})` : baseTip;
|
||||
onClose();
|
||||
onBusy({ busy: true, tip });
|
||||
const result = await HttpUtil.post('/panel/api/server/updatePanel');
|
||||
const result = await HttpUtil.post<{ runId: string }>('/panel/api/server/updatePanel');
|
||||
if (!result?.success) {
|
||||
onBusy({ busy: false });
|
||||
return;
|
||||
}
|
||||
const back = await pollUntilBack();
|
||||
if (back) await PromiseUtil.sleep(800);
|
||||
window.location.reload();
|
||||
const outcome = await pollUpdateStatus(result.obj?.runId ?? '');
|
||||
onBusy({ busy: false });
|
||||
if (outcome === 'success') {
|
||||
await PromiseUtil.sleep(800);
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
modal[outcome === 'failed' ? 'error' : 'warning']({
|
||||
title: t(outcome === 'failed' ? 'pages.index.panelUpdateFailedTitle' : 'pages.index.panelUpdateUnknownTitle'),
|
||||
content: t(outcome === 'failed' ? 'pages.index.panelUpdateFailedDesc' : 'pages.index.panelUpdateUnknownDesc'),
|
||||
okText: t('refresh'),
|
||||
onOk: () => window.location.reload(),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { SettingListItem } from '@/components/ui';
|
||||
import { EmailNotifications } from '@/components/ui/notifications/EmailNotifications';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { catTabLabel } from './catTabLabel';
|
||||
import SecretInput from './SecretInput';
|
||||
|
||||
interface EmailTabProps {
|
||||
allSetting: AllSetting;
|
||||
@@ -72,10 +73,13 @@ export default function EmailTab({ allSetting, updateSetting }: EmailTabProps) {
|
||||
</SettingListItem>
|
||||
|
||||
<SettingListItem paddings="small" title={t('pages.settings.smtpPassword')}
|
||||
description={allSetting.hasSmtpPassword ? t('pages.settings.smtpPasswordConfigured') : t('pages.settings.smtpPasswordDesc')}>
|
||||
<Input.Password value={allSetting.smtpPassword}
|
||||
placeholder={allSetting.hasSmtpPassword ? t('pages.settings.smtpPasswordPlaceholder') : ''}
|
||||
onChange={(e) => updateSetting({ smtpPassword: e.target.value })} />
|
||||
description={allSetting.hasSmtpPassword && !allSetting.clearSmtpPassword ? t('pages.settings.smtpPasswordConfigured') : t('pages.settings.smtpPasswordDesc')}>
|
||||
<SecretInput value={allSetting.smtpPassword}
|
||||
configured={allSetting.hasSmtpPassword}
|
||||
clearArmed={allSetting.clearSmtpPassword}
|
||||
placeholder={t('pages.settings.smtpPasswordPlaceholder')}
|
||||
onChange={(v) => updateSetting({ smtpPassword: v })}
|
||||
onClearArmedChange={(armed) => updateSetting({ clearSmtpPassword: armed })} />
|
||||
</SettingListItem>
|
||||
|
||||
<SettingListItem paddings="small" title={t('pages.settings.smtpTo')} description={t('pages.settings.smtpToDesc')}>
|
||||
|
||||
@@ -21,6 +21,7 @@ import { SettingListItem } from '@/components/ui';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { catTabLabel } from './catTabLabel';
|
||||
import { sanitizePath } from './uriPath';
|
||||
import SecretInput from './SecretInput';
|
||||
|
||||
interface ApiMsg<T = unknown> {
|
||||
success?: boolean;
|
||||
@@ -329,12 +330,15 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
|
||||
<SettingListItem
|
||||
paddings="small"
|
||||
title={t('password')}
|
||||
description={allSetting.hasLdapPassword ? t('pages.settings.ldap.passwordConfigured') : t('pages.settings.ldap.passwordUnconfigured')}
|
||||
description={allSetting.hasLdapPassword && !allSetting.clearLdapPassword ? t('pages.settings.ldap.passwordConfigured') : t('pages.settings.ldap.passwordUnconfigured')}
|
||||
>
|
||||
<Input.Password
|
||||
<SecretInput
|
||||
value={allSetting.ldapPassword}
|
||||
placeholder={allSetting.hasLdapPassword ? t('pages.settings.ldap.passwordPlaceholder') : ''}
|
||||
onChange={(e) => updateSetting({ ldapPassword: e.target.value })}
|
||||
configured={allSetting.hasLdapPassword}
|
||||
clearArmed={allSetting.clearLdapPassword}
|
||||
placeholder={t('pages.settings.ldap.passwordPlaceholder')}
|
||||
onChange={(v) => updateSetting({ ldapPassword: v })}
|
||||
onClearArmedChange={(armed) => updateSetting({ clearLdapPassword: armed })}
|
||||
/>
|
||||
</SettingListItem>
|
||||
<SettingListItem paddings="small" title={t('pages.settings.ldap.baseDn')}>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Button, Input, Space } from 'antd';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface SecretInputProps {
|
||||
value: string;
|
||||
configured: boolean;
|
||||
clearArmed: boolean;
|
||||
placeholder: string;
|
||||
onChange: (value: string) => void;
|
||||
onClearArmedChange: (armed: boolean) => void;
|
||||
}
|
||||
|
||||
export default function SecretInput({
|
||||
value,
|
||||
configured,
|
||||
clearArmed,
|
||||
placeholder,
|
||||
onChange,
|
||||
onClearArmedChange,
|
||||
}: SecretInputProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Space.Compact style={{ width: '100%' }}>
|
||||
<Input.Password
|
||||
value={value}
|
||||
placeholder={configured && !clearArmed ? placeholder : ''}
|
||||
onChange={(e) => {
|
||||
onChange(e.target.value);
|
||||
if (clearArmed) onClearArmedChange(false);
|
||||
}}
|
||||
/>
|
||||
{configured && (
|
||||
<Button
|
||||
danger={clearArmed}
|
||||
onClick={() => {
|
||||
onChange('');
|
||||
onClearArmedChange(!clearArmed);
|
||||
}}
|
||||
>
|
||||
{clearArmed ? t('pages.settings.secretClearUndo') : t('pages.settings.secretClear')}
|
||||
</Button>
|
||||
)}
|
||||
</Space.Compact>
|
||||
);
|
||||
}
|
||||
@@ -204,7 +204,7 @@ export default function SettingsPage() {
|
||||
case 'subscription-formats': return <SubscriptionFormatsTab allSetting={allSetting} updateSetting={updateSetting} />;
|
||||
default: return <GeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
|
||||
}
|
||||
}, [activeSlug, allSetting, updateSetting]);
|
||||
}, [activeSlug, allSetting, updateSetting, savePayload]);
|
||||
|
||||
return (
|
||||
<ConfigProvider theme={antdThemeConfig}>
|
||||
|
||||
@@ -79,7 +79,7 @@ export default function SubscriptionGeneralTab({ allSetting, updateSetting }: Su
|
||||
</SettingListItem>
|
||||
|
||||
<SettingListItem paddings="small" title={t('pages.settings.subUpdates')} description={t('pages.settings.subUpdatesDesc')}>
|
||||
<InputNumber value={allSetting.subUpdates} min={1} style={{ width: '100%' }}
|
||||
<InputNumber value={allSetting.subUpdates} min={0} max={525600} style={{ width: '100%' }}
|
||||
onChange={(v) => updateSetting({ subUpdates: Number(v) || 0 })} />
|
||||
</SettingListItem>
|
||||
</>
|
||||
|
||||
@@ -9,6 +9,7 @@ import { SettingListItem } from '@/components/ui';
|
||||
import { TelegramNotifications } from '@/components/ui/notifications/TelegramNotifications';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { catTabLabel } from './catTabLabel';
|
||||
import SecretInput from './SecretInput';
|
||||
|
||||
interface TelegramTabProps {
|
||||
allSetting: AllSetting;
|
||||
@@ -193,12 +194,15 @@ export default function TelegramTab({ allSetting, updateSetting }: TelegramTabPr
|
||||
<SettingListItem
|
||||
paddings="small"
|
||||
title={t('pages.settings.telegramToken')}
|
||||
description={allSetting.hasTgBotToken ? t('pages.settings.telegramTokenConfigured') : t('pages.settings.telegramTokenDesc')}
|
||||
description={allSetting.hasTgBotToken && !allSetting.clearTgBotToken ? t('pages.settings.telegramTokenConfigured') : t('pages.settings.telegramTokenDesc')}
|
||||
>
|
||||
<Input.Password
|
||||
<SecretInput
|
||||
value={allSetting.tgBotToken}
|
||||
placeholder={allSetting.hasTgBotToken ? t('pages.settings.telegramTokenPlaceholder') : ''}
|
||||
onChange={(e) => updateSetting({ tgBotToken: e.target.value })}
|
||||
configured={allSetting.hasTgBotToken}
|
||||
clearArmed={allSetting.clearTgBotToken}
|
||||
placeholder={t('pages.settings.telegramTokenPlaceholder')}
|
||||
onChange={(v) => updateSetting({ tgBotToken: v })}
|
||||
onClearArmedChange={(armed) => updateSetting({ clearTgBotToken: armed })}
|
||||
/>
|
||||
</SettingListItem>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
@@ -61,6 +62,7 @@ const links: string[] = Array.isArray(subData.links) ? subData.links : [];
|
||||
const linkEmails: string[] = Array.isArray(subData.emails) ? subData.emails : [];
|
||||
const subEmail = [...new Set(linkEmails.filter(Boolean))].join(', ');
|
||||
const datepicker = subData.datepicker || 'gregorian';
|
||||
const announce = subData.announce || '';
|
||||
|
||||
const isUnlimited = totalByte <= 0 && expireMs === 0;
|
||||
const isActive = (() => {
|
||||
@@ -283,6 +285,9 @@ export default function SubPage() {
|
||||
<Row justify="center">
|
||||
<Col xs={24} sm={22} md={18} lg={14} xl={12}>
|
||||
<Card hoverable className="subscription-card" title={cardTitle} extra={cardExtra}>
|
||||
{announce && (
|
||||
<Alert type="info" showIcon message={announce} style={{ marginBottom: 16 }} />
|
||||
)}
|
||||
<Descriptions
|
||||
bordered
|
||||
column={1}
|
||||
|
||||
@@ -367,7 +367,6 @@ export default function BalancersTab({
|
||||
<ObservatorySettingsTab
|
||||
templateSettings={templateSettings}
|
||||
mutate={mutate}
|
||||
isMobile={isMobile}
|
||||
/>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Empty, Input, InputNumber, Segmented, Select, Space, Switch, Tag } from 'antd';
|
||||
import { Alert, Empty, Input, InputNumber, Select, Space, Switch, Tag } from 'antd';
|
||||
|
||||
import { SettingListItem } from '@/components/ui';
|
||||
import {
|
||||
@@ -13,11 +13,11 @@ import {
|
||||
type PingConfigObject,
|
||||
} from '@/schemas/observatory';
|
||||
import type { XraySettingsValue } from '@/hooks/useXraySetting';
|
||||
import { settingsRequireBurstObservatory } from './balancer-helpers';
|
||||
|
||||
interface ObservatorySettingsTabProps {
|
||||
templateSettings: XraySettingsValue | null;
|
||||
mutate: (mutator: (next: XraySettingsValue) => void) => void;
|
||||
isMobile: boolean;
|
||||
}
|
||||
|
||||
const OBSERVATORY_DEFAULTS = ObservatorySchema.parse({});
|
||||
@@ -43,7 +43,6 @@ function SelectorTags({ tags }: { tags: string[] }) {
|
||||
export default function ObservatorySettingsTab({
|
||||
templateSettings,
|
||||
mutate,
|
||||
isMobile,
|
||||
}: ObservatorySettingsTabProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -63,13 +62,10 @@ export default function ObservatorySettingsTab({
|
||||
|
||||
const hasObservatory = observatory != null;
|
||||
const hasBurst = burst != null;
|
||||
|
||||
const [view, setView] = useState<'observatory' | 'burstObservatory'>('observatory');
|
||||
const effectiveView = !hasObservatory && hasBurst
|
||||
const hasMixedObservers = hasObservatory && hasBurst;
|
||||
const activeView = hasBurst && (!hasObservatory || settingsRequireBurstObservatory(templateSettings))
|
||||
? 'burstObservatory'
|
||||
: !hasBurst && hasObservatory
|
||||
? 'observatory'
|
||||
: view;
|
||||
: 'observatory';
|
||||
|
||||
function patchObservatory(patch: Partial<ObservatoryObject>) {
|
||||
mutate((tt) => {
|
||||
@@ -220,19 +216,15 @@ export default function ObservatorySettingsTab({
|
||||
|
||||
return (
|
||||
<Space orientation="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Alert type="info" showIcon message={t('pages.xray.observatory.autoManaged')} />
|
||||
{hasObservatory && hasBurst && (
|
||||
<Segmented
|
||||
block={isMobile}
|
||||
value={effectiveView}
|
||||
onChange={(v) => setView(v as 'observatory' | 'burstObservatory')}
|
||||
options={[
|
||||
{ label: t('pages.xray.observatory.title'), value: 'observatory' },
|
||||
{ label: t('pages.xray.observatory.burstTitle'), value: 'burstObservatory' },
|
||||
]}
|
||||
<Alert type="info" showIcon title={t('pages.xray.observatory.autoManaged')} />
|
||||
{hasMixedObservers && (
|
||||
<Alert
|
||||
type="warning"
|
||||
showIcon
|
||||
title={t('pages.xray.observatory.mixedLegacy')}
|
||||
/>
|
||||
)}
|
||||
<div>{effectiveView === 'observatory' ? observatorySection : burstSection}</div>
|
||||
<div>{activeView === 'observatory' ? observatorySection : burstSection}</div>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,16 @@ export function collectSelectors(list: BalancerObject[]): string[] {
|
||||
return [...out];
|
||||
}
|
||||
|
||||
export function balancerRequiresBurstObservatory(b: BalancerObject): boolean {
|
||||
const type = b.strategy?.type || 'random';
|
||||
return type === 'leastLoad' || ((type === 'random' || type === 'roundRobin') && (b.fallbackTag ?? '').length > 0);
|
||||
}
|
||||
|
||||
export function settingsRequireBurstObservatory(t: XraySettingsValue | null): boolean {
|
||||
const balancers = (t?.routing?.balancers || []) as BalancerObject[];
|
||||
return balancers.some(balancerRequiresBurstObservatory);
|
||||
}
|
||||
|
||||
// syncObservatories keeps the (burst)observatory sections aligned with the
|
||||
// balancer strategies that actually require them. Observatories have no runtime
|
||||
// reload API in xray-core, so creating OR removing one forces a full process
|
||||
@@ -36,39 +46,35 @@ export function collectSelectors(list: BalancerObject[]): string[] {
|
||||
// when its fallbackTag is set (issue #5605): with a fallbackTag the strategy
|
||||
// calls RequireFeatures(Observatory) and the core aborts startup with "not all
|
||||
// dependencies are resolved" if none exists; without a fallbackTag it never even
|
||||
// consults an observatory. leastLoad always needs the burst observer, leastPing
|
||||
// the regular one.
|
||||
// consults an observatory. leastLoad needs the burst observer, while leastPing
|
||||
// can use any extension.Observatory result with Alive/Delay. When a burst
|
||||
// observer is required, keep all observer-backed balancers on burstObservatory
|
||||
// to avoid xray-core resolving the earlier regular observatory feature instead.
|
||||
//
|
||||
// So each observer lives exactly as long as something requires it, and is
|
||||
// dropped the moment nothing does — clearing the last fallbackTag (or deleting
|
||||
// the last leastLoad) removes the burst observer again. A no-fallback balancer's
|
||||
// selector is still probed while the observer exists for another reason, but
|
||||
// never keeps it alive on its own.
|
||||
// the last leastLoad) removes the burst observer again. A no-fallback
|
||||
// Random/RoundRobin balancer never expands the observer either, because those
|
||||
// strategies do not consume observer data.
|
||||
export function syncObservatories(t: XraySettingsValue) {
|
||||
const balancers = (t.routing?.balancers || []) as BalancerObject[];
|
||||
|
||||
const leastPings = balancers.filter((b) => b.strategy?.type === 'leastPing');
|
||||
if (leastPings.length > 0) {
|
||||
if (!t.observatory) t.observatory = JSON.parse(JSON.stringify(DEFAULT_OBSERVATORY));
|
||||
(t.observatory as { subjectSelector: string[] }).subjectSelector = collectSelectors(leastPings);
|
||||
} else {
|
||||
delete t.observatory;
|
||||
}
|
||||
|
||||
const hasFallback = (b: BalancerObject) => (b.fallbackTag ?? '').length > 0;
|
||||
const required = balancers.filter((b) => {
|
||||
const type = b.strategy?.type || 'random';
|
||||
if (type === 'leastLoad') return true;
|
||||
return (type === 'random' || type === 'roundRobin') && hasFallback(b);
|
||||
});
|
||||
const optional = balancers.filter((b) => {
|
||||
const type = b.strategy?.type || 'random';
|
||||
return (type === 'random' || type === 'roundRobin') && !hasFallback(b);
|
||||
});
|
||||
const required = balancers.filter(balancerRequiresBurstObservatory);
|
||||
if (required.length > 0) {
|
||||
delete t.observatory;
|
||||
if (!t.burstObservatory) t.burstObservatory = JSON.parse(JSON.stringify(DEFAULT_BURST_OBSERVATORY));
|
||||
(t.burstObservatory as { subjectSelector: string[] }).subjectSelector = collectSelectors([...required, ...optional]);
|
||||
(t.burstObservatory as { subjectSelector: string[] }).subjectSelector = collectSelectors([
|
||||
...required,
|
||||
...leastPings,
|
||||
]);
|
||||
} else {
|
||||
delete t.burstObservatory;
|
||||
if (leastPings.length > 0) {
|
||||
if (!t.observatory) t.observatory = JSON.parse(JSON.stringify(DEFAULT_OBSERVATORY));
|
||||
(t.observatory as { subjectSelector: string[] }).subjectSelector = collectSelectors(leastPings);
|
||||
} else {
|
||||
delete t.observatory;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
NETWORK_OPTIONS,
|
||||
PROTOCOL_OPTIONS,
|
||||
SERVER_PROTOCOLS,
|
||||
TARGET_STRATEGY_OPTIONS,
|
||||
} from './outbound-form-constants';
|
||||
import {
|
||||
applyNetworkChange,
|
||||
@@ -394,6 +395,14 @@ export default function OutboundFormModal({
|
||||
<Input placeholder={t('pages.xray.outboundForm.localIpPlaceholder')} />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={t('pages.xray.outbound.targetStrategy')}
|
||||
name="targetStrategy"
|
||||
tooltip={t('pages.xray.outboundForm.targetStrategyHint')}
|
||||
>
|
||||
<Select allowClear placeholder="AsIs" options={TARGET_STRATEGY_OPTIONS} />
|
||||
</Form.Item>
|
||||
|
||||
{SERVER_PROTOCOLS.has(protocol) && <ServerTarget />}
|
||||
{protocol === 'vmess' && <VmessFields />}
|
||||
{protocol === 'vless' && <VlessFields />}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
USERS_SECURITY,
|
||||
UTLS_FINGERPRINT,
|
||||
} from '@/schemas/primitives';
|
||||
import { OutboundDomainStrategySchema } from '@/schemas/protocols/outbound';
|
||||
import { SSMethodSchema } from '@/schemas/protocols/shared/shadowsocks';
|
||||
|
||||
export const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
|
||||
@@ -20,6 +21,10 @@ export const ADDRESS_PORT_STRATEGY_OPTIONS = Object.values(Address_Port_Strategy
|
||||
value: v,
|
||||
label: v,
|
||||
}));
|
||||
export const TARGET_STRATEGY_OPTIONS = OutboundDomainStrategySchema.options.map((v) => ({
|
||||
value: v,
|
||||
label: v,
|
||||
}));
|
||||
|
||||
// canEnableMux mirrors the adapter's helper but lives here so the modal
|
||||
// can show/hide the Mux section without going through the adapter.
|
||||
|
||||
@@ -54,6 +54,13 @@ export const InboundOptionSchema = z.object({
|
||||
wgDns: z.string().optional(),
|
||||
// Hosting node id; absent/null for this panel's own inbounds (#4997).
|
||||
nodeId: z.number().nullable().optional(),
|
||||
// Share-host resolution inputs, mirroring the backend resolveInboundAddress so
|
||||
// the clients page picks the same WireGuard endpoint host as the subscription:
|
||||
// the hosting node address, the inbound listen, and its share-address strategy.
|
||||
nodeAddress: z.string().optional(),
|
||||
listen: z.string().optional(),
|
||||
shareAddr: z.string().optional(),
|
||||
shareAddrStrategy: z.string().optional(),
|
||||
}).loose();
|
||||
|
||||
export const InboundOptionsSchema = z.array(InboundOptionSchema);
|
||||
|
||||
@@ -219,11 +219,13 @@ export const OutboundStreamFormSchema = NetworkSettingsSchema
|
||||
.and(StreamExtrasSchema);
|
||||
export type OutboundStreamFormValues = z.infer<typeof OutboundStreamFormSchema>;
|
||||
|
||||
// Top-level form base: identity (tag, sendThrough), then the per-protocol
|
||||
// settings DU, then the stream sub-form, then mux.
|
||||
// Top-level form base: identity (tag, sendThrough, targetStrategy), then
|
||||
// the per-protocol settings DU, then the stream sub-form, then mux.
|
||||
// targetStrategy '' means AsIs (omitted from wire).
|
||||
export const OutboundFormBaseSchema = z.object({
|
||||
tag: z.string().default(''),
|
||||
sendThrough: z.string().default(''),
|
||||
targetStrategy: z.union([OutboundDomainStrategySchema, z.literal('')]).default(''),
|
||||
streamSettings: OutboundStreamFormSchema.optional(),
|
||||
mux: MuxFormSchema.default({
|
||||
enabled: false,
|
||||
|
||||
@@ -33,7 +33,7 @@ export const AddressPortStrategySchema = z.enum([
|
||||
export type AddressPortStrategy = z.infer<typeof AddressPortStrategySchema>;
|
||||
|
||||
export const HappyEyeballsSchema = z.object({
|
||||
tryDelayMs: z.number().int().min(0).default(0),
|
||||
tryDelayMs: z.number().int().min(0).default(250),
|
||||
prioritizeIPv6: z.boolean().default(false),
|
||||
interleave: z.number().int().min(1).default(1),
|
||||
maxConcurrentTry: z.number().int().min(0).default(4),
|
||||
|
||||
@@ -53,7 +53,7 @@ export const AllSettingSchema = z.object({
|
||||
restartXrayOnClientDisable: z.boolean().optional(),
|
||||
subCertFile: z.string().optional(),
|
||||
subKeyFile: z.string().optional(),
|
||||
subUpdates: z.number().int().min(1).max(168).optional(),
|
||||
subUpdates: z.number().int().min(0).max(525600).optional(),
|
||||
subEncrypt: z.boolean().optional(),
|
||||
subURI: z.string().optional(),
|
||||
subJsonURI: z.string().optional(),
|
||||
|
||||
@@ -8,7 +8,7 @@ exports[`genInboundLinks orchestrator > shadowsocks-tcp-2022: byte-stable 1`] =
|
||||
|
||||
exports[`genInboundLinks orchestrator > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@override.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`;
|
||||
|
||||
exports[`genInboundLinks orchestrator > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@override.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2F&flow=xtls-rprx-vision#parity-test"`;
|
||||
exports[`genInboundLinks orchestrator > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@override.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2Fdafd018f50a389b&flow=xtls-rprx-vision#parity-test"`;
|
||||
|
||||
exports[`genInboundLinks orchestrator > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@override.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`;
|
||||
|
||||
@@ -36,7 +36,7 @@ exports[`genShadowsocksLink > shadowsocks-tcp-2022: byte-stable 1`] = `"ss://202
|
||||
|
||||
exports[`genTrojanLink > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@example.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`;
|
||||
|
||||
exports[`genVlessLink > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@example.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2F&flow=xtls-rprx-vision#parity-test"`;
|
||||
exports[`genVlessLink > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@example.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2Fd08ed99bd9afc60&flow=xtls-rprx-vision#parity-test"`;
|
||||
|
||||
exports[`genVlessLink > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@example.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`;
|
||||
|
||||
|
||||
@@ -7,12 +7,208 @@ function tpl(routing: Record<string, unknown>, extra: Record<string, unknown> =
|
||||
return { routing, ...extra } as unknown as XraySettingsValue;
|
||||
}
|
||||
|
||||
type ExpectedObserver = 'none' | 'observatory' | 'burstObservatory';
|
||||
|
||||
function expectObserver(t: XraySettingsValue, expected: ExpectedObserver, selectors: string[] = []) {
|
||||
if (expected === 'none') {
|
||||
expect(t.observatory).toBeUndefined();
|
||||
expect(t.burstObservatory).toBeUndefined();
|
||||
return;
|
||||
}
|
||||
|
||||
if (expected === 'observatory') {
|
||||
expect(t.observatory).toBeDefined();
|
||||
expect(t.burstObservatory).toBeUndefined();
|
||||
expect(new Set((t.observatory as { subjectSelector: string[] }).subjectSelector)).toEqual(new Set(selectors));
|
||||
return;
|
||||
}
|
||||
|
||||
expect(t.observatory).toBeUndefined();
|
||||
expect(t.burstObservatory).toBeDefined();
|
||||
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(new Set(selectors));
|
||||
}
|
||||
|
||||
// Observatory sections have no reload API in xray-core, so creating one turns
|
||||
// a balancer save from a live (hot-applied) routing change into a full
|
||||
// restart. These tests pin the rule: only strategies that genuinely need an
|
||||
// observer may create one — which, for random/roundRobin, means a fallbackTag
|
||||
// is set (xray-core then requires the Observatory feature; see #5605).
|
||||
describe('syncObservatories', () => {
|
||||
it.each([
|
||||
{
|
||||
name: 'random without fallback',
|
||||
balancers: [{ tag: 'random', selector: ['random-out'] }],
|
||||
expected: 'none' as const,
|
||||
selectors: [],
|
||||
},
|
||||
{
|
||||
name: 'random with fallback',
|
||||
balancers: [{ tag: 'random', selector: ['random-out'], fallbackTag: 'direct' }],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['random-out'],
|
||||
},
|
||||
{
|
||||
name: 'roundRobin without fallback',
|
||||
balancers: [{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } }],
|
||||
expected: 'none' as const,
|
||||
selectors: [],
|
||||
},
|
||||
{
|
||||
name: 'roundRobin with fallback',
|
||||
balancers: [{ tag: 'rr', selector: ['rr-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } }],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['rr-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing without fallback',
|
||||
balancers: [{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }],
|
||||
expected: 'observatory' as const,
|
||||
selectors: ['lp-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing with fallback',
|
||||
balancers: [{ tag: 'lp', selector: ['lp-out'], fallbackTag: 'direct', strategy: { type: 'leastPing' } }],
|
||||
expected: 'observatory' as const,
|
||||
selectors: ['lp-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastLoad without fallback',
|
||||
balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['ll-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastLoad with fallback',
|
||||
balancers: [{ tag: 'll', selector: ['ll-out'], fallbackTag: 'direct', strategy: { type: 'leastLoad' } }],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['ll-out'],
|
||||
},
|
||||
])('covers standalone strategy: $name', ({ balancers, expected, selectors }) => {
|
||||
const t = tpl({ balancers });
|
||||
syncObservatories(t);
|
||||
expectObserver(t, expected, selectors);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'random + roundRobin without fallbacks',
|
||||
balancers: [
|
||||
{ tag: 'random', selector: ['random-out'] },
|
||||
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
expected: 'none' as const,
|
||||
selectors: [],
|
||||
},
|
||||
{
|
||||
name: 'leastPing + random without fallback',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'random', selector: ['random-out'] },
|
||||
],
|
||||
expected: 'observatory' as const,
|
||||
selectors: ['lp-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing + roundRobin without fallback',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
expected: 'observatory' as const,
|
||||
selectors: ['lp-out'],
|
||||
},
|
||||
{
|
||||
name: 'random fallback + random without fallback',
|
||||
balancers: [
|
||||
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
|
||||
{ tag: 'random', selector: ['random-out'] },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['random-fallback-out'],
|
||||
},
|
||||
{
|
||||
name: 'roundRobin fallback + roundRobin without fallback',
|
||||
balancers: [
|
||||
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
|
||||
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['rr-fallback-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastLoad + random without fallback',
|
||||
balancers: [
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
{ tag: 'random', selector: ['random-out'] },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['ll-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastLoad + roundRobin without fallback',
|
||||
balancers: [
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['ll-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing + leastLoad with disjoint selectors',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out', 'direct'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out-1', 'll-out-2'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['lp-out', 'direct', 'll-out-1', 'll-out-2'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing + random fallback',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['lp-out', 'random-fallback-out'],
|
||||
},
|
||||
{
|
||||
name: 'leastPing + roundRobin fallback',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['lp-out', 'rr-fallback-out'],
|
||||
},
|
||||
{
|
||||
name: 'all strategies mixed',
|
||||
balancers: [
|
||||
{ tag: 'random', selector: ['random-out'] },
|
||||
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
|
||||
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
|
||||
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['random-fallback-out', 'rr-fallback-out', 'lp-out', 'll-out'],
|
||||
},
|
||||
{
|
||||
name: 'shared selectors are de-duplicated',
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['shared', 'lp-only'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['shared', 'll-only'], strategy: { type: 'leastLoad' } },
|
||||
{ tag: 'rf', selector: ['shared', 'rf-only'], fallbackTag: 'direct' },
|
||||
],
|
||||
expected: 'burstObservatory' as const,
|
||||
selectors: ['shared', 'lp-only', 'll-only', 'rf-only'],
|
||||
},
|
||||
])('covers mixed strategy matrix: $name', ({ balancers, expected, selectors }) => {
|
||||
const t = tpl({ balancers });
|
||||
syncObservatories(t);
|
||||
expectObserver(t, expected, selectors);
|
||||
});
|
||||
|
||||
it('does not create burstObservatory for a fresh random balancer (stays hot-appliable)', () => {
|
||||
const t = tpl({ balancers: [{ tag: 'b1', selector: ['direct'] }] });
|
||||
syncObservatories(t);
|
||||
@@ -64,7 +260,7 @@ describe('syncObservatories', () => {
|
||||
expect(t.burstObservatory).toBeUndefined();
|
||||
});
|
||||
|
||||
it('keeps burstObservatory while another fallback balancer still needs it', () => {
|
||||
it('keeps burstObservatory while another fallback balancer still needs it without adding no-fallback selectors', () => {
|
||||
const t = tpl(
|
||||
{
|
||||
balancers: [
|
||||
@@ -76,7 +272,7 @@ describe('syncObservatories', () => {
|
||||
);
|
||||
syncObservatories(t);
|
||||
expect(t.burstObservatory).toBeDefined();
|
||||
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b', 'a']);
|
||||
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('creates burstObservatory for leastLoad (required by the strategy)', () => {
|
||||
@@ -86,20 +282,55 @@ describe('syncObservatories', () => {
|
||||
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('creates observatory for leastPing (required by the strategy)', () => {
|
||||
it('creates observatory for leastPing when no burst observer is required', () => {
|
||||
const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastPing' } }] });
|
||||
syncObservatories(t);
|
||||
expect(t.observatory).toBeDefined();
|
||||
expect((t.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']);
|
||||
});
|
||||
|
||||
it('keeps an existing burstObservatory in sync for random balancers (legacy setups)', () => {
|
||||
it('uses only burstObservatory when leastPing is mixed with leastLoad', () => {
|
||||
const t = tpl(
|
||||
{
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['least-ping-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['least-load-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
},
|
||||
{ observatory: { subjectSelector: ['stale-least-ping-out'] } },
|
||||
);
|
||||
syncObservatories(t);
|
||||
expect(t.observatory).toBeUndefined();
|
||||
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(
|
||||
new Set(['least-load-out', 'least-ping-out']),
|
||||
);
|
||||
});
|
||||
|
||||
it('uses only burstObservatory when leastPing is mixed with fallback balancers', () => {
|
||||
const t = tpl(
|
||||
{
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['least-ping-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
|
||||
{ tag: 'rr', selector: ['round-robin-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
|
||||
],
|
||||
},
|
||||
{ observatory: { subjectSelector: ['stale-least-ping-out'] } },
|
||||
);
|
||||
syncObservatories(t);
|
||||
expect(t.observatory).toBeUndefined();
|
||||
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(
|
||||
new Set(['random-fallback-out', 'round-robin-fallback-out', 'least-ping-out']),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not keep no-fallback random selectors in an observer created by another balancer', () => {
|
||||
const t = tpl(
|
||||
{ balancers: [{ tag: 'b1', selector: ['a'] }, { tag: 'b2', selector: ['b'], strategy: { type: 'leastLoad' } }] },
|
||||
{ burstObservatory: { subjectSelector: ['stale'] } },
|
||||
);
|
||||
syncObservatories(t);
|
||||
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b', 'a']);
|
||||
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('removes observatories when no balancer can use them', () => {
|
||||
@@ -112,6 +343,30 @@ describe('syncObservatories', () => {
|
||||
expect(t.burstObservatory).toBeUndefined();
|
||||
});
|
||||
|
||||
it('switches from stale burstObservatory back to regular observatory when only leastPing remains', () => {
|
||||
const t = tpl(
|
||||
{ balancers: [{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }] },
|
||||
{
|
||||
observatory: { subjectSelector: ['stale-observatory-out'] },
|
||||
burstObservatory: { subjectSelector: ['stale-burst-out'] },
|
||||
},
|
||||
);
|
||||
syncObservatories(t);
|
||||
expectObserver(t, 'observatory', ['lp-out']);
|
||||
});
|
||||
|
||||
it('switches from stale observatory to burstObservatory when any burst strategy remains', () => {
|
||||
const t = tpl(
|
||||
{ balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }] },
|
||||
{
|
||||
observatory: { subjectSelector: ['stale-observatory-out'] },
|
||||
burstObservatory: { subjectSelector: ['stale-burst-out'] },
|
||||
},
|
||||
);
|
||||
syncObservatories(t);
|
||||
expectObserver(t, 'burstObservatory', ['ll-out']);
|
||||
});
|
||||
|
||||
it('creates burstObservatory with the HEAD httpMethod default for leastLoad', () => {
|
||||
const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastLoad' } }] });
|
||||
syncObservatories(t);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type RawInboundRow,
|
||||
} from '@/lib/xray/inbound-form-adapter';
|
||||
import { InboundDbFieldsSchema, InboundFormSchema } from '@/schemas/forms/inbound-form';
|
||||
import { normalizeXhttpForWire } from '@/lib/xray/stream-wire-normalize';
|
||||
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
|
||||
|
||||
// Round-trip: raw DB row → InboundFormValues → wire payload, asserting
|
||||
@@ -304,3 +305,51 @@ describe('subSortIndex', () => {
|
||||
expect(InboundDbFieldsSchema.parse({}).subSortIndex).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('legacy xhttp session keys on edit (#5621)', () => {
|
||||
const legacyXhttpRow: RawInboundRow = {
|
||||
...vlessRow,
|
||||
streamSettings: {
|
||||
network: 'xhttp',
|
||||
security: 'none',
|
||||
xhttpSettings: {
|
||||
path: '/xh',
|
||||
mode: 'packet-up',
|
||||
sessionPlacement: 'cookie',
|
||||
sessionKey: 'x_session',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it('rawInboundToFormValues lifts sessionPlacement/sessionKey onto the renamed keys', () => {
|
||||
const values = rawInboundToFormValues(legacyXhttpRow);
|
||||
const xhttp = (values.streamSettings as unknown as Record<string, Record<string, unknown>>).xhttpSettings;
|
||||
expect(xhttp.sessionIDPlacement).toBe('cookie');
|
||||
expect(xhttp.sessionIDKey).toBe('x_session');
|
||||
expect(xhttp.sessionPlacement).toBeUndefined();
|
||||
expect(xhttp.sessionKey).toBeUndefined();
|
||||
expect(xhttp.path).toBe('/xh');
|
||||
expect(xhttp.xPaddingBytes).toBe('100-1000');
|
||||
});
|
||||
|
||||
it('formValuesToWirePayload never emits the legacy key names', () => {
|
||||
const values = rawInboundToFormValues(legacyXhttpRow);
|
||||
const payload = formValuesToWirePayload(values);
|
||||
const stream = JSON.parse(payload.streamSettings) as Record<string, Record<string, unknown>>;
|
||||
expect(stream.xhttpSettings.sessionPlacement).toBeUndefined();
|
||||
expect(stream.xhttpSettings.sessionKey).toBeUndefined();
|
||||
expect(stream.xhttpSettings.sessionIDPlacement).toBe('cookie');
|
||||
expect(stream.xhttpSettings.sessionIDKey).toBe('x_session');
|
||||
});
|
||||
|
||||
it('normalizeXhttpForWire lifts stale legacy keys that bypassed the schema', () => {
|
||||
const out = normalizeXhttpForWire(
|
||||
{ sessionPlacement: 'header', sessionKey: 'x_raw' },
|
||||
'inbound',
|
||||
);
|
||||
expect(out.sessionIDPlacement).toBe('header');
|
||||
expect(out.sessionIDKey).toBe('x_raw');
|
||||
expect(out.sessionPlacement).toBeUndefined();
|
||||
expect(out.sessionKey).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -104,6 +104,7 @@ describe('inbound security forms', () => {
|
||||
scanRealityCandidates={async () => []}
|
||||
applyRealityScanResult={noop}
|
||||
randomizeShortIds={noop}
|
||||
randomizeSpiderX={noop}
|
||||
genRealityKeypair={noop}
|
||||
clearRealityKeypair={noop}
|
||||
genMldsa65={noop}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
|
||||
import ObservatorySettingsTab from '@/pages/xray/balancers/ObservatorySettingsTab';
|
||||
import type { XraySettingsValue } from '@/hooks/useXraySetting';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
function renderTab(templateSettings: XraySettingsValue) {
|
||||
renderWithProviders(
|
||||
<ObservatorySettingsTab
|
||||
templateSettings={templateSettings}
|
||||
mutate={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ObservatorySettingsTab', () => {
|
||||
it('shows one burst settings panel and warns for legacy mixed observers', () => {
|
||||
renderTab({
|
||||
routing: {
|
||||
balancers: [{ tag: 'll', selector: ['proxy-a'], strategy: { type: 'leastLoad' } }],
|
||||
},
|
||||
observatory: { subjectSelector: ['stale-regular'] },
|
||||
burstObservatory: { subjectSelector: ['proxy-a'] },
|
||||
} as unknown as XraySettingsValue);
|
||||
|
||||
expect(screen.getByText(/This config contains both Observatory and Burst Observatory/)).toBeTruthy();
|
||||
expect(document.querySelector('.ant-segmented')).toBeFalsy();
|
||||
expect(screen.getByText('Probe Destination')).toBeTruthy();
|
||||
expect(screen.queryByText('Probe URL')).toBeFalsy();
|
||||
});
|
||||
|
||||
it('shows regular observatory settings for mixed legacy configs that normalize back to leastPing only', () => {
|
||||
renderTab({
|
||||
routing: {
|
||||
balancers: [{ tag: 'lp', selector: ['proxy-b'], strategy: { type: 'leastPing' } }],
|
||||
},
|
||||
observatory: { subjectSelector: ['proxy-b'] },
|
||||
burstObservatory: { subjectSelector: ['stale-burst'] },
|
||||
} as unknown as XraySettingsValue);
|
||||
|
||||
expect(screen.getByText(/This config contains both Observatory and Burst Observatory/)).toBeTruthy();
|
||||
expect(document.querySelector('.ant-segmented')).toBeFalsy();
|
||||
expect(screen.getByText('Probe URL')).toBeTruthy();
|
||||
expect(screen.queryByText('Probe Destination')).toBeFalsy();
|
||||
});
|
||||
});
|
||||
@@ -420,6 +420,54 @@ describe('outbound-form-adapter: round-trip', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('outbound-form-adapter: targetStrategy', () => {
|
||||
it('round-trips a top-level targetStrategy', () => {
|
||||
const back = formValuesToWirePayload(rawOutboundToFormValues({
|
||||
protocol: 'vless',
|
||||
settings: { address: 's', port: 443, id: '11111111-2222-4333-8444-555555555555', flow: '', encryption: 'none' },
|
||||
targetStrategy: 'ForceIPv6v4',
|
||||
}));
|
||||
expect(back.targetStrategy).toBe('ForceIPv6v4');
|
||||
});
|
||||
|
||||
it('normalizes wire case to the canonical spelling (core matches case-insensitively)', () => {
|
||||
const form = rawOutboundToFormValues({
|
||||
protocol: 'freedom',
|
||||
settings: {},
|
||||
targetStrategy: 'useipv4v6',
|
||||
});
|
||||
expect(form.targetStrategy).toBe('UseIPv4v6');
|
||||
});
|
||||
|
||||
it('omits targetStrategy when unset and drops unknown values', () => {
|
||||
const unset = formValuesToWirePayload(rawOutboundToFormValues({
|
||||
protocol: 'freedom',
|
||||
settings: {},
|
||||
}));
|
||||
expect(unset).not.toHaveProperty('targetStrategy');
|
||||
|
||||
const invalid = formValuesToWirePayload(rawOutboundToFormValues({
|
||||
protocol: 'freedom',
|
||||
settings: {},
|
||||
targetStrategy: 'UseIPv5',
|
||||
}));
|
||||
expect(invalid).not.toHaveProperty('targetStrategy');
|
||||
});
|
||||
|
||||
it('freedom prefers settings.targetStrategy over domainStrategy and emits the legacy key', () => {
|
||||
const form = rawOutboundToFormValues({
|
||||
protocol: 'freedom',
|
||||
settings: { targetStrategy: 'UseIPv6', domainStrategy: 'UseIPv4' },
|
||||
});
|
||||
if (form.protocol === 'freedom') {
|
||||
expect(form.settings.domainStrategy).toBe('UseIPv6');
|
||||
}
|
||||
const back = formValuesToWirePayload(form);
|
||||
expect(back.settings).toMatchObject({ domainStrategy: 'UseIPv6' });
|
||||
expect(back.settings).not.toHaveProperty('targetStrategy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('outbound-form-adapter: xhttp xmux toggle', () => {
|
||||
const xmuxWire = {
|
||||
protocol: 'vless',
|
||||
|
||||
@@ -308,6 +308,52 @@ describe('parseHysteria2Link', () => {
|
||||
expect(settings.packetSize).toBe('100-200');
|
||||
});
|
||||
|
||||
it('coerces string quicParams numerics under fm to integers — #5783', () => {
|
||||
const fm = encodeURIComponent(JSON.stringify({
|
||||
quicParams: {
|
||||
keepAlivePeriod: '10s',
|
||||
maxIdleTimeout: '30',
|
||||
initStreamReceiveWindow: 524288,
|
||||
maxIncomingStreams: true,
|
||||
brutalUp: '100 mbps',
|
||||
},
|
||||
}));
|
||||
const link = `hysteria2://78e7795a209c4c099f896a816fc8448f@news.domain.org:8443?security=tls&sni=news.domain.org&fm=${fm}#hy2-quic`;
|
||||
const out = parseHysteria2Link(link);
|
||||
expect(out).not.toBeNull();
|
||||
const finalmask = (out!.streamSettings as Record<string, unknown>).finalmask as Record<string, unknown>;
|
||||
const quic = finalmask.quicParams as Record<string, unknown>;
|
||||
expect(quic.keepAlivePeriod).toBe(10);
|
||||
expect(quic.maxIdleTimeout).toBe(30);
|
||||
expect(quic.initStreamReceiveWindow).toBe(524288);
|
||||
expect('maxIncomingStreams' in quic).toBe(false);
|
||||
expect(quic.brutalUp).toBe('100 mbps');
|
||||
});
|
||||
|
||||
it('clamps quicParams to the ranges xray accepts and drops junk — #5783', () => {
|
||||
const fm = encodeURIComponent(JSON.stringify({
|
||||
quicParams: {
|
||||
keepAlivePeriod: '1s',
|
||||
maxIdleTimeout: '10m',
|
||||
maxIncomingStreams: 4,
|
||||
initStreamReceiveWindow: 'inf',
|
||||
maxStreamReceiveWindow: -5,
|
||||
initConnectionReceiveWindow: 1e30,
|
||||
},
|
||||
}));
|
||||
const link = `hysteria2://78e7795a209c4c099f896a816fc8448f@news.domain.org:8443?security=tls&sni=news.domain.org&fm=${fm}#hy2-clamp`;
|
||||
const out = parseHysteria2Link(link);
|
||||
expect(out).not.toBeNull();
|
||||
const finalmask = (out!.streamSettings as Record<string, unknown>).finalmask as Record<string, unknown>;
|
||||
const quic = finalmask.quicParams as Record<string, unknown>;
|
||||
expect(quic.keepAlivePeriod).toBe(2);
|
||||
expect(quic.maxIdleTimeout).toBe(120);
|
||||
expect(quic.maxIncomingStreams).toBe(8);
|
||||
expect('initStreamReceiveWindow' in quic).toBe(false);
|
||||
expect('maxStreamReceiveWindow' in quic).toBe(false);
|
||||
expect('initConnectionReceiveWindow' in quic).toBe(false);
|
||||
});
|
||||
|
||||
it('round-trips the realm tlsConfig under fm', () => {
|
||||
const fm = encodeURIComponent(JSON.stringify({
|
||||
udp: [{
|
||||
|
||||
@@ -83,6 +83,65 @@ describe('outbound deletion', () => {
|
||||
expect(tt.routing!.rules![0].balancerTag).toBeUndefined();
|
||||
});
|
||||
|
||||
it('cascade-removes the burst observer when deleting an outbound removes the last leastLoad balancer', () => {
|
||||
const tt = tpl({
|
||||
outbounds: [{ tag: 'll-out' }],
|
||||
routing: {
|
||||
rules: [],
|
||||
balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }],
|
||||
},
|
||||
burstObservatory: { subjectSelector: ['ll-out'] },
|
||||
});
|
||||
const impact = planOutboundDeletion(tt, 0);
|
||||
expect(impact.balancers).toEqual([{ tag: 'll', reason: 'selectorEmptied' }]);
|
||||
expect(impact.burst).toBe(true);
|
||||
applyOutboundDeletion(tt, 0);
|
||||
expect(tt.burstObservatory).toBeUndefined();
|
||||
expect(tt.routing!.balancers).toEqual([]);
|
||||
});
|
||||
|
||||
it('cascade-switches from burst to regular observer when only leastPing remains', () => {
|
||||
const tt = tpl({
|
||||
outbounds: [{ tag: 'lp-out' }, { tag: 'll-out' }],
|
||||
routing: {
|
||||
rules: [],
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
},
|
||||
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
|
||||
});
|
||||
const impact = planOutboundDeletion(tt, 1);
|
||||
expect(impact.balancers).toEqual([{ tag: 'll', reason: 'selectorEmptied' }]);
|
||||
expect(impact.burst).toBe(true);
|
||||
applyOutboundDeletion(tt, 1);
|
||||
expect(tt.burstObservatory).toBeUndefined();
|
||||
expect((tt.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['lp-out']);
|
||||
expect(tt.routing!.balancers).toEqual([{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }]);
|
||||
});
|
||||
|
||||
it('cascade-keeps burst observer when leastPing is removed but leastLoad remains', () => {
|
||||
const tt = tpl({
|
||||
outbounds: [{ tag: 'lp-out' }, { tag: 'll-out' }],
|
||||
routing: {
|
||||
rules: [],
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
},
|
||||
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
|
||||
});
|
||||
const impact = planOutboundDeletion(tt, 0);
|
||||
expect(impact.balancers).toEqual([{ tag: 'lp', reason: 'selectorEmptied' }]);
|
||||
expect(impact.burst).toBe(false);
|
||||
applyOutboundDeletion(tt, 0);
|
||||
expect(tt.observatory).toBeUndefined();
|
||||
expect((tt.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['ll-out']);
|
||||
expect(tt.routing!.balancers).toEqual([{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }]);
|
||||
});
|
||||
|
||||
it('clears a fallbackTag and a dialerProxy pointing at the deleted outbound', () => {
|
||||
const tt = tpl({
|
||||
outbounds: [
|
||||
@@ -253,6 +312,68 @@ describe('balancer deletion', () => {
|
||||
expect(tt.routing!.balancers).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports and removes the burst observer when deleting the last leastLoad balancer', () => {
|
||||
const tt = tpl({
|
||||
routing: { rules: [], balancers: [{ tag: 'll', selector: ['a'], strategy: { type: 'leastLoad' } }] },
|
||||
burstObservatory: { subjectSelector: ['a'] },
|
||||
});
|
||||
expect(planBalancerDeletion(tt, 0).burst).toBe(true);
|
||||
applyBalancerDeletion(tt, 0);
|
||||
expect(tt.burstObservatory).toBeUndefined();
|
||||
expect(tt.routing!.balancers).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports and removes the burst observer when deleting the last fallback balancer', () => {
|
||||
const tt = tpl({
|
||||
routing: { rules: [], balancers: [{ tag: 'rf', selector: ['a'], fallbackTag: 'direct' }] },
|
||||
burstObservatory: { subjectSelector: ['a'] },
|
||||
});
|
||||
expect(planBalancerDeletion(tt, 0).burst).toBe(true);
|
||||
applyBalancerDeletion(tt, 0);
|
||||
expect(tt.burstObservatory).toBeUndefined();
|
||||
expect(tt.routing!.balancers).toEqual([]);
|
||||
});
|
||||
|
||||
it('switches from burst to regular observer when the deleted balancer was the last burst-required one', () => {
|
||||
const tt = tpl({
|
||||
routing: {
|
||||
rules: [],
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
},
|
||||
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
|
||||
});
|
||||
const impact = planBalancerDeletion(tt, 1);
|
||||
expect(impact.burst).toBe(true);
|
||||
expect(impact.observatory).toBe(false);
|
||||
applyBalancerDeletion(tt, 1);
|
||||
expect(tt.burstObservatory).toBeUndefined();
|
||||
expect((tt.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['lp-out']);
|
||||
expect(tt.routing!.balancers).toEqual([{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }]);
|
||||
});
|
||||
|
||||
it('keeps burst observer when deleting leastPing but a burst-required balancer remains', () => {
|
||||
const tt = tpl({
|
||||
routing: {
|
||||
rules: [],
|
||||
balancers: [
|
||||
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
|
||||
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
|
||||
],
|
||||
},
|
||||
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
|
||||
});
|
||||
const impact = planBalancerDeletion(tt, 0);
|
||||
expect(impact.burst).toBe(false);
|
||||
expect(impact.observatory).toBe(false);
|
||||
applyBalancerDeletion(tt, 0);
|
||||
expect(tt.observatory).toBeUndefined();
|
||||
expect((tt.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['ll-out']);
|
||||
expect(tt.routing!.balancers).toEqual([{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }]);
|
||||
});
|
||||
|
||||
it('does not report rules when the deleted balancer is unreferenced', () => {
|
||||
const tt = tpl({
|
||||
routing: { rules: [{ type: 'field', inboundTag: ['in'], outboundTag: 'direct' }], balancers: [{ tag: 'pool', selector: ['a'] }] },
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AllSettingSchema } from '@/schemas/setting';
|
||||
|
||||
describe('subUpdates range', () => {
|
||||
it('accepts values the backend allows (gte=0, lte=525600)', () => {
|
||||
for (const v of [0, 12, 168, 720, 525600]) {
|
||||
const r = AllSettingSchema.safeParse({ subUpdates: v });
|
||||
expect(r.success, `subUpdates=${v} should be valid`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects values outside the backend range', () => {
|
||||
for (const v of [-1, 525601, 1.5]) {
|
||||
expect(AllSettingSchema.safeParse({ subUpdates: v }).success, `subUpdates=${v} should be invalid`).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { deriveSpiderX } from '@/lib/xray/spider-x';
|
||||
|
||||
// Cross-language vectors shared with TestDeriveSpiderXMatchesFrontendVectors
|
||||
// in internal/sub/service_sharelink_test.go: subscription links come from Go,
|
||||
// panel links from this module, and the two must agree byte-for-byte.
|
||||
describe('deriveSpiderX', () => {
|
||||
it('matches the Go deriveSpiderX vectors', () => {
|
||||
expect(deriveSpiderX('/seed', 'subAlice')).toBe('/c252fbc3ecd3e3c');
|
||||
expect(deriveSpiderX('/', '')).toBe('/d08ed99bd9afc60');
|
||||
});
|
||||
|
||||
it('is stable per client, distinct across clients, and rotates with the seed', () => {
|
||||
expect(deriveSpiderX('/seed', 'subAlice')).toBe(deriveSpiderX('/seed', 'subAlice'));
|
||||
expect(deriveSpiderX('/seed', 'subAlice')).not.toBe(deriveSpiderX('/seed', 'subBob'));
|
||||
expect(deriveSpiderX('/seedA', 'subAlice')).not.toBe(deriveSpiderX('/seedB', 'subAlice'));
|
||||
});
|
||||
|
||||
it('returns empty when there is nothing to derive from', () => {
|
||||
expect(deriveSpiderX('', '')).toBe('');
|
||||
});
|
||||
|
||||
it('emits a /-prefixed 15-hex-char path', () => {
|
||||
expect(deriveSpiderX('/some-seed', 'client@example.com')).toMatch(/^\/[0-9a-f]{15}$/);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
validateRealityTarget,
|
||||
} from '@/lib/xray/stream-wire-normalize';
|
||||
import { InboundFormSchema } from '@/schemas/forms/inbound-form';
|
||||
import { HappyEyeballsSchema } from '@/schemas/protocols/stream/sockopt';
|
||||
import type { InboundFormValues } from '@/schemas/forms/inbound-form';
|
||||
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
|
||||
|
||||
@@ -204,6 +205,22 @@ describe('normalizeSockoptForWire', () => {
|
||||
});
|
||||
expect(out?.domainStrategy).toBe('UseIP');
|
||||
});
|
||||
|
||||
it('keeps a freshly toggled happyEyeballs (schema defaults) across the wire round trip', () => {
|
||||
const out = normalizeSockoptForWire({
|
||||
happyEyeballs: HappyEyeballsSchema.parse({}),
|
||||
});
|
||||
|
||||
expect(out?.happyEyeballs).toEqual({ tryDelayMs: 250 });
|
||||
});
|
||||
|
||||
it('keeps an explicit tryDelayMs of 0 so it cannot rehydrate as the 250 default', () => {
|
||||
const out = normalizeSockoptForWire({
|
||||
happyEyeballs: { tryDelayMs: 0, prioritizeIPv6: true, interleave: 1, maxConcurrentTry: 4 },
|
||||
});
|
||||
|
||||
expect(out?.happyEyeballs).toEqual({ tryDelayMs: 0, prioritizeIPv6: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeStreamSettingsForWire reality', () => {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { vlessEncryptionAuthKind } from '@/lib/xray/vless-encryption';
|
||||
|
||||
const x25519Key = 'kO9pIKKPtoUCzo3ZWfWfp0lQoWCyJC1TqL8oz1hpsFM';
|
||||
const mlkem768Key = 'A'.repeat(1590);
|
||||
|
||||
describe('vlessEncryptionAuthKind', () => {
|
||||
const cases: { name: string; encryption: string; want: ReturnType<typeof vlessEncryptionAuthKind> }[] = [
|
||||
{ name: 'empty string', encryption: '', want: null },
|
||||
{ name: 'none', encryption: 'none', want: null },
|
||||
{ name: 'only dots', encryption: '...', want: null },
|
||||
{ name: 'x25519 native', encryption: `mlkem768x25519plus.native.600s.${x25519Key}`, want: 'x25519' },
|
||||
{ name: 'x25519 xorpub', encryption: `mlkem768x25519plus.xorpub.600s.${x25519Key}`, want: 'x25519_xorpub' },
|
||||
{ name: 'x25519 random', encryption: `mlkem768x25519plus.random.600s.${x25519Key}`, want: 'x25519_random' },
|
||||
{ name: 'mlkem768 native', encryption: `mlkem768x25519plus.native.600s.${mlkem768Key}`, want: 'mlkem768' },
|
||||
{ name: 'mlkem768 xorpub', encryption: `mlkem768x25519plus.xorpub.600s.${mlkem768Key}`, want: 'mlkem768_xorpub' },
|
||||
{ name: 'mlkem768 random', encryption: `mlkem768x25519plus.random.600s.${mlkem768Key}`, want: 'mlkem768_random' },
|
||||
{ name: 'two-segment value treated as native', encryption: `mlkem768x25519plus.${x25519Key}`, want: 'x25519' },
|
||||
];
|
||||
|
||||
for (const c of cases) {
|
||||
it(c.name, () => {
|
||||
expect(vlessEncryptionAuthKind(c.encryption)).toBe(c.want);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -52,4 +52,41 @@ describe('buildWireguardClientConfig', () => {
|
||||
const cfg = buildWireguardClientConfig({ ...client, preSharedKey: undefined }, inbound, 'example.com', '');
|
||||
expect(cfg).not.toContain('PresharedKey');
|
||||
});
|
||||
|
||||
it('uses the hosting node address as the endpoint host for node-managed inbounds', () => {
|
||||
const cfg = buildWireguardClientConfig(client, { ...inbound, nodeAddress: 'node.example.net' }, 'master.example.com', '');
|
||||
expect(cfg).toContain('Endpoint = node.example.net:51820');
|
||||
expect(cfg).not.toContain('master.example.com');
|
||||
});
|
||||
|
||||
it('falls back to the panel host when the node address is blank', () => {
|
||||
const cfg = buildWireguardClientConfig(client, { ...inbound, nodeAddress: ' ' }, 'master.example.com', '');
|
||||
expect(cfg).toContain('Endpoint = master.example.com:51820');
|
||||
});
|
||||
|
||||
it('honors the custom share-address strategy over the node address', () => {
|
||||
const cfg = buildWireguardClientConfig(
|
||||
client,
|
||||
{ ...inbound, nodeAddress: 'node.example.net', shareAddrStrategy: 'custom', shareAddr: 'vpn.example.com' },
|
||||
'master.example.com',
|
||||
'',
|
||||
);
|
||||
expect(cfg).toContain('Endpoint = vpn.example.com:51820');
|
||||
});
|
||||
|
||||
it('honors the listen share-address strategy over the node address', () => {
|
||||
const cfg = buildWireguardClientConfig(
|
||||
client,
|
||||
{ ...inbound, nodeAddress: 'node.example.net', shareAddrStrategy: 'listen', listen: '198.51.100.7' },
|
||||
'master.example.com',
|
||||
'',
|
||||
);
|
||||
expect(cfg).toContain('Endpoint = 198.51.100.7:51820');
|
||||
});
|
||||
|
||||
it('keeps a panel hostname that fails share-host normalization instead of emitting an empty endpoint', () => {
|
||||
const cfg = buildWireguardClientConfig(client, { ...inbound, listen: '0.0.0.0' }, 'wg_gw.corp.lan', '');
|
||||
expect(cfg).toContain('Endpoint = wg_gw.corp.lan:51820');
|
||||
expect(cfg).not.toContain('Endpoint = :51820');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ require (
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1
|
||||
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
github.com/shirou/gopsutil/v4 v4.26.5
|
||||
github.com/shirou/gopsutil/v4 v4.26.6
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||
github.com/valyala/fasthttp v1.72.0
|
||||
github.com/xlzd/gotp v0.1.0
|
||||
@@ -26,7 +26,7 @@ require (
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/sys v0.46.0
|
||||
golang.org/x/text v0.38.0
|
||||
google.golang.org/grpc v1.81.1
|
||||
google.golang.org/grpc v1.82.0
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/postgres v1.6.0
|
||||
gorm.io/driver/sqlite v1.6.0
|
||||
@@ -63,7 +63,7 @@ require (
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/juju/ratelimit v1.0.2 // indirect
|
||||
github.com/klauspost/compress v1.18.6
|
||||
github.com/klauspost/compress v1.19.0
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
|
||||
|
||||
@@ -115,8 +115,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
|
||||
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
|
||||
github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -178,8 +178,8 @@ github.com/sagernet/sing v0.8.10 h1:V5VZffy8rm4dtBVKIpKa8vibRR2SiJprtu/10DFUalU=
|
||||
github.com/sagernet/sing v0.8.10/go.mod h1:olXxWQNqRW/l2Q6JI3b2Qmz8iQnIFlOeeH8bx6JhgUA=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9 h1:Paep5zCszRKsEn8587O0MnhFWKJwDW1Y4zOYYlIxMkM=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.9/go.mod h1:TE/Z6401Pi8tgr0nBZcM/xawAI6u3F6TTbz4nH/qw+8=
|
||||
github.com/shirou/gopsutil/v4 v4.26.5 h1:RPcBXkpz7kOj9PqGFQOlBPZHsyaPvPVQc098y9RmCNM=
|
||||
github.com/shirou/gopsutil/v4 v4.26.5/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
|
||||
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -281,8 +281,8 @@ gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d h1:mpAgMyM9vQHxycBlDq50y1VHpfSfVwzXvrQKtYbXuUY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
|
||||
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
|
||||
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
|
||||
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
+139
-26
@@ -101,17 +101,17 @@ install_base() {
|
||||
apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
|
||||
;;
|
||||
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
|
||||
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
|
||||
dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
|
||||
;;
|
||||
centos)
|
||||
if [[ "${VERSION_ID}" =~ ^7 ]]; then
|
||||
yum -y update && yum install -y cronie curl tar tzdata socat ca-certificates openssl
|
||||
yum makecache -y && yum install -y cronie curl tar tzdata socat ca-certificates openssl
|
||||
else
|
||||
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
|
||||
dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
|
||||
fi
|
||||
;;
|
||||
arch | manjaro | parch)
|
||||
pacman -Syu && pacman -Syu --noconfirm cronie curl tar tzdata socat ca-certificates openssl
|
||||
pacman -Sy --noconfirm cronie curl tar tzdata socat ca-certificates openssl
|
||||
;;
|
||||
opensuse-tumbleweed | opensuse-leap)
|
||||
zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
|
||||
@@ -180,6 +180,36 @@ write_install_result() {
|
||||
echo -e "${green}Install result written to ${result_file} (mode 600).${plain}"
|
||||
}
|
||||
|
||||
# RHEL-family initdb writes pg_hba.conf host rules with ident auth, which
|
||||
# compares the OS username against the Postgres role and always rejects the
|
||||
# randomly generated panel role over TCP (#5806). Prepend password-auth rules
|
||||
# scoped to the panel database; first match wins, and md5 also accepts
|
||||
# scram-sha-256-stored verifiers, so this works on every supported distro.
|
||||
pg_ensure_hba_password_auth() {
|
||||
local pg_db="$1"
|
||||
local hba_file
|
||||
hba_file=$(sudo -u postgres psql -tAc 'SHOW hba_file' 2> /dev/null | tr -d '[:space:]')
|
||||
[[ -n "${hba_file}" && -f "${hba_file}" ]] || return 0
|
||||
grep -Eq "^host[[:space:]]+${pg_db}[[:space:]]" "${hba_file}" && return 0
|
||||
local tmp
|
||||
tmp=$(mktemp) || return 1
|
||||
{
|
||||
echo "# Added by 3x-ui: allow password logins for the panel database."
|
||||
echo "host ${pg_db} all 127.0.0.1/32 md5"
|
||||
echo "host ${pg_db} all ::1/128 md5"
|
||||
cat "${hba_file}"
|
||||
} > "${tmp}" || {
|
||||
rm -f "${tmp}"
|
||||
return 1
|
||||
}
|
||||
cat "${tmp}" > "${hba_file}" || {
|
||||
rm -f "${tmp}"
|
||||
return 1
|
||||
}
|
||||
rm -f "${tmp}"
|
||||
sudo -u postgres psql -tAc 'SELECT pg_reload_conf()' > /dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
install_postgres_local() {
|
||||
local pg_user pg_pass
|
||||
pg_pass=$(gen_random_string 24)
|
||||
@@ -204,7 +234,7 @@ install_postgres_local() {
|
||||
[[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
|
||||
;;
|
||||
arch | manjaro | parch)
|
||||
pacman -Syu --noconfirm postgresql >&2 || return 1
|
||||
pacman -Sy --noconfirm postgresql >&2 || return 1
|
||||
if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
|
||||
sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
|
||||
fi
|
||||
@@ -263,6 +293,9 @@ install_postgres_local() {
|
||||
|
||||
sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
|
||||
|
||||
pg_ensure_hba_password_auth "${pg_db}" \
|
||||
|| echo -e "${yellow}Warning: could not update pg_hba.conf; PostgreSQL may reject the panel's TCP login (ident auth).${plain}" >&2
|
||||
|
||||
local pg_pass_enc
|
||||
pg_pass_enc=$(printf '%s' "${pg_pass}" | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g')
|
||||
|
||||
@@ -373,7 +406,7 @@ setup_ssl_certificate() {
|
||||
fi
|
||||
|
||||
# Install certificate
|
||||
~/.acme.sh/acme.sh --installcert -d ${domain} \
|
||||
~/.acme.sh/acme.sh --installcert --force -d ${domain} \
|
||||
--key-file /root/cert/${domain}/privkey.pem \
|
||||
--fullchain-file /root/cert/${domain}/fullchain.pem \
|
||||
--reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
|
||||
@@ -517,7 +550,7 @@ setup_ip_certificate() {
|
||||
# Install certificate
|
||||
# Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
|
||||
# but the cert files are still installed. We check for files instead of exit code.
|
||||
~/.acme.sh/acme.sh --installcert -d ${ipv4} \
|
||||
~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
|
||||
--key-file "${certDir}/privkey.pem" \
|
||||
--fullchain-file "${certDir}/fullchain.pem" \
|
||||
--reloadcmd "${reloadCmd}" 2>&1 || true
|
||||
@@ -705,7 +738,7 @@ ssl_cert_issue() {
|
||||
|
||||
# install the certificate
|
||||
local installOutput=""
|
||||
installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \
|
||||
installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
|
||||
--key-file /root/cert/${domain}/privkey.pem \
|
||||
--fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
|
||||
local installRc=$?
|
||||
@@ -1326,6 +1359,40 @@ setup_fail2ban() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
|
||||
# atomic mv, so a failed cp/curl or an interrupted mv never leaves a
|
||||
# truncated unit file at the live path -- systemd would then fail to parse
|
||||
# it on the next daemon-reload/start. Same pattern already used for
|
||||
# /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
|
||||
# file already extracted from the release tarball) vs curl (GitHub fallback).
|
||||
_install_xui_service_unit() {
|
||||
local source="$1"
|
||||
local source_is_url="$2"
|
||||
local dest="${xui_service}/x-ui.service"
|
||||
local temp_file="${dest}.tmp.$$"
|
||||
|
||||
rm -f "$temp_file"
|
||||
if [[ "$source_is_url" == "true" ]]; then
|
||||
curl -fLRo "$temp_file" "$source" > /dev/null 2>&1
|
||||
else
|
||||
cp -f "$source" "$temp_file" > /dev/null 2>&1
|
||||
fi
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "$temp_file"
|
||||
return 1
|
||||
fi
|
||||
if [[ ! -s "$temp_file" ]]; then
|
||||
rm -f "$temp_file"
|
||||
return 1
|
||||
fi
|
||||
mv -f "$temp_file" "$dest"
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "$temp_file"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
install_x-ui() {
|
||||
cd ${xui_folder%/x-ui}/
|
||||
|
||||
@@ -1342,6 +1409,11 @@ install_x-ui() {
|
||||
echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
|
||||
rm ${xui_folder}-linux-$(arch).tar.gz -f
|
||||
echo -e "${red}Downloaded x-ui release archive is empty${plain}"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
tag_version=$1
|
||||
# The rolling dev channel ships under a fixed, non-semver tag that is
|
||||
@@ -1367,12 +1439,25 @@ install_x-ui() {
|
||||
echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
|
||||
rm ${xui_folder}-linux-$(arch).tar.gz -f
|
||||
echo -e "${red}Downloaded x-ui release archive is empty${plain}"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
curl -fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
|
||||
local xui_script_temp="/usr/bin/x-ui-temp.$$"
|
||||
rm -f "${xui_script_temp}"
|
||||
curl -fLRo "${xui_script_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "${xui_script_temp}"
|
||||
echo -e "${red}Failed to download x-ui.sh${plain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -s "${xui_script_temp}" ]]; then
|
||||
rm -f "${xui_script_temp}"
|
||||
echo -e "${red}Downloaded x-ui.sh is empty${plain}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Stop x-ui service and remove old resources
|
||||
if [[ -e ${xui_folder}/ ]]; then
|
||||
@@ -1391,16 +1476,29 @@ install_x-ui() {
|
||||
|
||||
# Extract resources and set permissions
|
||||
tar zxvf x-ui-linux-$(arch).tar.gz
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm x-ui-linux-$(arch).tar.gz -f
|
||||
rm -f "${xui_script_temp}"
|
||||
echo -e "${red}Failed to extract the x-ui release archive -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
|
||||
exit 1
|
||||
fi
|
||||
rm x-ui-linux-$(arch).tar.gz -f
|
||||
|
||||
cd x-ui
|
||||
if [[ $? -ne 0 || ! -s x-ui ]]; then
|
||||
rm -f "${xui_script_temp}"
|
||||
echo -e "${red}Extracted x-ui archive is missing the x-ui binary -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
|
||||
exit 1
|
||||
fi
|
||||
chmod +x x-ui
|
||||
chmod +x x-ui.sh
|
||||
|
||||
# Check the system's architecture and rename the file accordingly
|
||||
# Check the system's architecture and rename the file accordingly.
|
||||
# The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
|
||||
# so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
|
||||
if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
|
||||
mv bin/xray-linux-$(arch) bin/xray-linux-arm
|
||||
chmod +x bin/xray-linux-arm
|
||||
mv bin/xray-linux-$(arch) bin/xray-linux-arm32
|
||||
chmod +x bin/xray-linux-arm32
|
||||
if [[ -f bin/mtg-linux-$(arch) ]]; then
|
||||
mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
|
||||
chmod +x bin/mtg-linux-arm
|
||||
@@ -1414,7 +1512,12 @@ install_x-ui() {
|
||||
fi
|
||||
|
||||
# Update x-ui cli and se set permission
|
||||
mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
|
||||
mv -f "${xui_script_temp}" /usr/bin/x-ui
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "${xui_script_temp}"
|
||||
echo -e "${red}Failed to install x-ui.sh${plain}"
|
||||
exit 1
|
||||
fi
|
||||
chmod +x /usr/bin/x-ui
|
||||
mkdir -p /var/log/x-ui
|
||||
config_after_install
|
||||
@@ -1434,11 +1537,25 @@ install_x-ui() {
|
||||
fi
|
||||
|
||||
if [[ $release == "alpine" ]]; then
|
||||
curl -fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
|
||||
xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
|
||||
rm -f "${xui_rc_temp}"
|
||||
curl -fLRo "${xui_rc_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "${xui_rc_temp}"
|
||||
echo -e "${red}Failed to download x-ui.rc${plain}"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -s "${xui_rc_temp}" ]]; then
|
||||
rm -f "${xui_rc_temp}"
|
||||
echo -e "${red}Downloaded x-ui.rc is empty${plain}"
|
||||
exit 1
|
||||
fi
|
||||
mv -f "${xui_rc_temp}" /etc/init.d/x-ui
|
||||
if [[ $? -ne 0 ]]; then
|
||||
rm -f "${xui_rc_temp}"
|
||||
echo -e "${red}Failed to install x-ui.rc${plain}"
|
||||
exit 1
|
||||
fi
|
||||
chmod +x /etc/init.d/x-ui
|
||||
rc-update add x-ui
|
||||
rc-service x-ui start
|
||||
@@ -1448,8 +1565,7 @@ install_x-ui() {
|
||||
|
||||
if [ -f "x-ui.service" ]; then
|
||||
echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
|
||||
cp -f x-ui.service ${xui_service}/ > /dev/null 2>&1
|
||||
if [[ $? -eq 0 ]]; then
|
||||
if _install_xui_service_unit "x-ui.service" "false"; then
|
||||
service_installed=true
|
||||
fi
|
||||
fi
|
||||
@@ -1459,8 +1575,7 @@ install_x-ui() {
|
||||
ubuntu | debian | armbian)
|
||||
if [ -f "x-ui.service.debian" ]; then
|
||||
echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
|
||||
cp -f x-ui.service.debian ${xui_service}/x-ui.service > /dev/null 2>&1
|
||||
if [[ $? -eq 0 ]]; then
|
||||
if _install_xui_service_unit "x-ui.service.debian" "false"; then
|
||||
service_installed=true
|
||||
fi
|
||||
fi
|
||||
@@ -1468,8 +1583,7 @@ install_x-ui() {
|
||||
arch | manjaro | parch)
|
||||
if [ -f "x-ui.service.arch" ]; then
|
||||
echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
|
||||
cp -f x-ui.service.arch ${xui_service}/x-ui.service > /dev/null 2>&1
|
||||
if [[ $? -eq 0 ]]; then
|
||||
if _install_xui_service_unit "x-ui.service.arch" "false"; then
|
||||
service_installed=true
|
||||
fi
|
||||
fi
|
||||
@@ -1477,8 +1591,7 @@ install_x-ui() {
|
||||
*)
|
||||
if [ -f "x-ui.service.rhel" ]; then
|
||||
echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
|
||||
cp -f x-ui.service.rhel ${xui_service}/x-ui.service > /dev/null 2>&1
|
||||
if [[ $? -eq 0 ]]; then
|
||||
if _install_xui_service_unit "x-ui.service.rhel" "false"; then
|
||||
service_installed=true
|
||||
fi
|
||||
fi
|
||||
@@ -1491,17 +1604,17 @@ install_x-ui() {
|
||||
echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
|
||||
case "${release}" in
|
||||
ubuntu | debian | armbian)
|
||||
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian > /dev/null 2>&1
|
||||
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian"
|
||||
;;
|
||||
arch | manjaro | parch)
|
||||
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch > /dev/null 2>&1
|
||||
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch"
|
||||
;;
|
||||
*)
|
||||
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel > /dev/null 2>&1
|
||||
service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel"
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ $? -ne 0 ]]; then
|
||||
if ! _install_xui_service_unit "$service_unit_url" "true"; then
|
||||
echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -169,6 +169,14 @@ func GetDBPath() string {
|
||||
return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName())
|
||||
}
|
||||
|
||||
// GetUpdateStatusFilePath returns the path to the panel self-update status
|
||||
// file update.sh writes on completion. It lives beside the database, outside
|
||||
// XUI_MAIN_FOLDER, so it survives an update regardless of what happens to
|
||||
// that folder.
|
||||
func GetUpdateStatusFilePath() string {
|
||||
return filepath.Join(GetDBFolderPath(), "update-status.json")
|
||||
}
|
||||
|
||||
// GetDBKind returns the configured database backend: "sqlite" (default) or "postgres".
|
||||
func GetDBKind() string {
|
||||
v := strings.ToLower(strings.TrimSpace(os.Getenv("XUI_DB_TYPE")))
|
||||
|
||||
+193
-1
@@ -83,6 +83,9 @@ func initModels() error {
|
||||
&model.OutboundSubscription{},
|
||||
}
|
||||
for _, mdl := range models {
|
||||
if IsPostgres() && postgresModelSettled(mdl) {
|
||||
continue
|
||||
}
|
||||
if err := db.AutoMigrate(mdl); err != nil {
|
||||
if isIgnorableDuplicateColumnErr(err, mdl) {
|
||||
log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
|
||||
@@ -110,6 +113,15 @@ func initModels() error {
|
||||
if err := normalizeInboundSubSortIndex(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repairOverflowedTrafficCounters(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dedupeInboundSettingsClients(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := migrateLegacySocksInboundsToMixed(); err != nil {
|
||||
return err
|
||||
}
|
||||
if IsPostgres() {
|
||||
if err := resyncPostgresSequences(db, models); err != nil {
|
||||
log.Printf("Error resyncing postgres sequences: %v", err)
|
||||
@@ -119,6 +131,30 @@ func initModels() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// postgresModelSettled skips AutoMigrate when table, columns, and indexes all exist:
|
||||
// its catalog-filtered column probe misdetects on some setups and re-ADDs columns forever (#5665).
|
||||
func postgresModelSettled(mdl any) bool {
|
||||
migrator := db.Migrator()
|
||||
if !migrator.HasTable(mdl) {
|
||||
return false
|
||||
}
|
||||
stmt := &gorm.Statement{DB: db}
|
||||
if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
|
||||
return false
|
||||
}
|
||||
for _, dbName := range stmt.Schema.DBNames {
|
||||
if !migrator.HasColumn(mdl, dbName) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, idx := range stmt.Schema.ParseIndexes() {
|
||||
if !migrator.HasIndex(mdl, idx.Name) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func dropLegacyForeignKeys() error {
|
||||
if !IsPostgres() {
|
||||
return nil
|
||||
@@ -456,6 +492,23 @@ func pruneOrphanedClientInbounds() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
|
||||
// The protocol enum dropped socks in favor of mixed (identical settings shape,
|
||||
// same behavior plus HTTP on the shared port), so rows predating the rename
|
||||
// fail model validation — most visibly when pushed to a node, where one legacy
|
||||
// inbound stalled the entire node's config and traffic sync (#5685).
|
||||
func migrateLegacySocksInboundsToMixed() error {
|
||||
res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
|
||||
if res.Error != nil {
|
||||
log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
|
||||
return res.Error
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
|
||||
// minimum (rows written by builds that defaulted the column to 0, or by nodes
|
||||
// predating the field) so they cannot sort ahead of explicitly ranked inbounds.
|
||||
@@ -471,6 +524,111 @@ func normalizeInboundSubSortIndex() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// repairOverflowedTrafficCounters heals traffic counters that historic
|
||||
// compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
|
||||
// silently promoted to REAL, after which the column no longer scans into the
|
||||
// Go int64 field and every reader of the table fails (#5762). REAL cells are
|
||||
// cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
|
||||
// are clamped into [0, TrafficMax] on both backends so the next delta cannot
|
||||
// overflow again.
|
||||
func repairOverflowedTrafficCounters() error {
|
||||
targets := []struct {
|
||||
table string
|
||||
columns []string
|
||||
}{
|
||||
{"client_traffics", []string{"up", "down"}},
|
||||
{"inbounds", []string{"up", "down"}},
|
||||
{"outbound_traffics", []string{"up", "down", "total"}},
|
||||
{"node_client_traffics", []string{"up", "down"}},
|
||||
}
|
||||
for _, target := range targets {
|
||||
for _, col := range target.columns {
|
||||
statements := []string{
|
||||
fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
|
||||
fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
|
||||
}
|
||||
if !IsPostgres() {
|
||||
statements = append([]string{
|
||||
fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
|
||||
}, statements...)
|
||||
}
|
||||
var repaired int64
|
||||
for _, statement := range statements {
|
||||
res := db.Exec(statement)
|
||||
if res.Error != nil {
|
||||
log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
|
||||
return res.Error
|
||||
}
|
||||
repaired += res.RowsAffected
|
||||
}
|
||||
if repaired > 0 {
|
||||
log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// dedupeInboundSettingsClients collapses duplicate same-email entries inside
|
||||
// every inbound's settings.clients array, keeping the first occurrence.
|
||||
// Retried or raced multi-node client adds on older builds appended the same
|
||||
// client several times (#5770), which the client lists then rendered as
|
||||
// phantom duplicates. Runs on every start (idempotent, writes only changed
|
||||
// rows) because a restored backup or a not-yet-upgraded node's snapshot can
|
||||
// reintroduce duplicates.
|
||||
func dedupeInboundSettingsClients() error {
|
||||
var inbounds []model.Inbound
|
||||
if err := db.Find(&inbounds).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
repaired := int64(0)
|
||||
for _, inbound := range inbounds {
|
||||
if strings.TrimSpace(inbound.Settings) == "" {
|
||||
continue
|
||||
}
|
||||
var settings map[string]any
|
||||
if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
|
||||
continue
|
||||
}
|
||||
clients, _ := settings["clients"].([]any)
|
||||
if len(clients) < 2 {
|
||||
continue
|
||||
}
|
||||
seen := make(map[string]struct{}, len(clients))
|
||||
kept := make([]any, 0, len(clients))
|
||||
for _, c := range clients {
|
||||
if cm, ok := c.(map[string]any); ok {
|
||||
if email, _ := cm["email"].(string); email != "" {
|
||||
key := strings.ToLower(email)
|
||||
if _, dup := seen[key]; dup {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
kept = append(kept, c)
|
||||
}
|
||||
if len(kept) == len(clients) {
|
||||
continue
|
||||
}
|
||||
settings["clients"] = kept
|
||||
newSettings, err := json.MarshalIndent(settings, "", " ")
|
||||
if err != nil {
|
||||
log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
|
||||
continue
|
||||
}
|
||||
if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
|
||||
Update("settings", string(newSettings)).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
repaired++
|
||||
}
|
||||
if repaired > 0 {
|
||||
log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
@@ -637,7 +795,10 @@ func runSeeders(isUsersEmpty bool) error {
|
||||
if err := seedWireguardPeersToClients(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
// Idempotent, not seeder-gated: bad values can re-enter via a restored
|
||||
// backup, so re-check on every start.
|
||||
return normalizeSettingPaths()
|
||||
}
|
||||
|
||||
// resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where
|
||||
@@ -742,6 +903,37 @@ func clearLegacyProxySettings() error {
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeSettingPaths repairs URI-path settings persisted before the
|
||||
// leading/trailing-slash rules existed (or restored from an old backup),
|
||||
// mirroring entity.AllSetting.CheckValid. CheckValid self-heals these on save,
|
||||
// but the frontend rejects the whole Settings form on the bad stored value
|
||||
// before a save can ever reach it (#5726), so the stored rows themselves must
|
||||
// be fixed. Idempotent; runs on every start.
|
||||
func normalizeSettingPaths() error {
|
||||
pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
|
||||
var rows []model.Setting
|
||||
if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
fixed := row.Value
|
||||
if !strings.HasPrefix(fixed, "/") {
|
||||
fixed = "/" + fixed
|
||||
}
|
||||
if !strings.HasSuffix(fixed, "/") {
|
||||
fixed += "/"
|
||||
}
|
||||
if fixed == row.Value {
|
||||
continue
|
||||
}
|
||||
if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
|
||||
Update("value", fixed).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeInboundClientTgId() error {
|
||||
var inbounds []model.Inbound
|
||||
if err := db.Find(&inbounds).Error; err != nil {
|
||||
|
||||
@@ -153,3 +153,44 @@ func TestNormalizeInboundClientSubId_FillsMissingAndPreservesExisting(t *testing
|
||||
t.Fatalf("expected one InboundClientSubIdFix history row, got %d", historyCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeSettingPaths_RepairsLegacyValues(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB failed: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
seed := []model.Setting{
|
||||
{Key: "subJsonPath", Value: "YIrCXJOOOL"},
|
||||
{Key: "subPath", Value: "/sub"},
|
||||
{Key: "subClashPath", Value: "clash/"},
|
||||
{Key: "webBasePath", Value: "/panel/"},
|
||||
}
|
||||
for i := range seed {
|
||||
if err := db.Create(&seed[i]).Error; err != nil {
|
||||
t.Fatalf("seed setting %s: %v", seed[i].Key, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := normalizeSettingPaths(); err != nil {
|
||||
t.Fatalf("normalizeSettingPaths: %v", err)
|
||||
}
|
||||
|
||||
want := map[string]string{
|
||||
"subJsonPath": "/YIrCXJOOOL/",
|
||||
"subPath": "/sub/",
|
||||
"subClashPath": "/clash/",
|
||||
"webBasePath": "/panel/",
|
||||
}
|
||||
for key, expected := range want {
|
||||
var row model.Setting
|
||||
if err := db.Where("key = ?", key).First(&row).Error; err != nil {
|
||||
t.Fatalf("read %s: %v", key, err)
|
||||
}
|
||||
if row.Value != expected {
|
||||
t.Errorf("%s = %q, want %q", key, row.Value, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// Locks the #5665 guard: composite-PK client_inbounds has no id column, so the
|
||||
// sequence-reset SQL must never be issued for it.
|
||||
func TestTableWithIdColumn_SkipsCompositeKeyModels(t *testing.T) {
|
||||
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
if table, ok := tableWithIdColumn(db, &model.ClientInbound{}); ok {
|
||||
t.Errorf("ClientInbound (table %q) has no id column but was not skipped", table)
|
||||
}
|
||||
table, ok := tableWithIdColumn(db, &model.Inbound{})
|
||||
if !ok {
|
||||
t.Fatal("Inbound has an id column but was reported as skippable")
|
||||
}
|
||||
if table != "inbounds" {
|
||||
t.Errorf("Inbound table = %q, want inbounds", table)
|
||||
}
|
||||
}
|
||||
|
||||
// Exercises the #5665 AutoMigrate skip on SQLite (the check is dialect-agnostic):
|
||||
// settled after InitDB, not settled with a missing column or table.
|
||||
func TestPostgresModelSettled_TracksSchemaPresence(t *testing.T) {
|
||||
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
for _, mdl := range []any{&model.ClientRecord{}, &model.ClientGroup{}, &model.ClientInbound{}} {
|
||||
if !postgresModelSettled(mdl) {
|
||||
t.Errorf("%T not settled right after InitDB", mdl)
|
||||
}
|
||||
}
|
||||
|
||||
if err := db.Migrator().DropColumn(&model.ClientGroup{}, "reset_up"); err != nil {
|
||||
t.Fatalf("drop column: %v", err)
|
||||
}
|
||||
if postgresModelSettled(&model.ClientGroup{}) {
|
||||
t.Error("ClientGroup settled despite missing reset_up column")
|
||||
}
|
||||
|
||||
if err := db.Migrator().DropTable(&model.ClientGroup{}); err != nil {
|
||||
t.Fatalf("drop table: %v", err)
|
||||
}
|
||||
if postgresModelSettled(&model.ClientGroup{}) {
|
||||
t.Error("ClientGroup settled despite missing table")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,19 @@ package database
|
||||
|
||||
import "fmt"
|
||||
|
||||
// TrafficMax caps every traffic counter safely below math.MaxInt64 (~9.22e18)
|
||||
// so that one more delta can never overflow int64. SQLite silently promotes an
|
||||
// overflowing INTEGER to REAL, after which the column no longer scans into the
|
||||
// Go int64 field and every reader of the table fails (#5762).
|
||||
const TrafficMax = int64(9_000_000_000_000_000_000)
|
||||
|
||||
func ClampedAddExpr(col string) string {
|
||||
if IsPostgres() {
|
||||
return fmt.Sprintf("LEAST(%s + ?, %d)", col, TrafficMax)
|
||||
}
|
||||
return fmt.Sprintf("MIN(%s + ?, %d)", col, TrafficMax)
|
||||
}
|
||||
|
||||
func JSONClientsFromInbound() string {
|
||||
if IsPostgres() {
|
||||
return "FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value)"
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// TestDedupeInboundSettingsClients_CollapsesDuplicateEmails covers the #5770
|
||||
// repair: settings.clients arrays written by older builds can carry the same
|
||||
// email several times; startup must collapse them to the first occurrence and
|
||||
// leave clean inbounds byte-for-byte untouched.
|
||||
func TestDedupeInboundSettingsClients_CollapsesDuplicateEmails(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB failed: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
dupSettings := `{"clients": [` +
|
||||
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true},` +
|
||||
`{"id": "u2", "email": "keep@x", "subId": "s2", "enable": true},` +
|
||||
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true},` +
|
||||
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true}]}`
|
||||
dirty := model.Inbound{UserId: 1, Port: 21001, Protocol: model.VLESS, Tag: "dedupe-dirty", Settings: dupSettings}
|
||||
if err := db.Create(&dirty).Error; err != nil {
|
||||
t.Fatalf("create dirty inbound: %v", err)
|
||||
}
|
||||
|
||||
cleanSettings := `{"clients": [{"id": "u3", "email": "solo@x", "subId": "s3", "enable": true}]}`
|
||||
clean := model.Inbound{UserId: 1, Port: 21002, Protocol: model.VLESS, Tag: "dedupe-clean", Settings: cleanSettings}
|
||||
if err := db.Create(&clean).Error; err != nil {
|
||||
t.Fatalf("create clean inbound: %v", err)
|
||||
}
|
||||
|
||||
if err := dedupeInboundSettingsClients(); err != nil {
|
||||
t.Fatalf("dedupeInboundSettingsClients: %v", err)
|
||||
}
|
||||
|
||||
var gotDirty model.Inbound
|
||||
if err := db.First(&gotDirty, dirty.Id).Error; err != nil {
|
||||
t.Fatalf("reload dirty inbound: %v", err)
|
||||
}
|
||||
var parsed struct {
|
||||
Clients []map[string]any `json:"clients"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(gotDirty.Settings), &parsed); err != nil {
|
||||
t.Fatalf("parse repaired settings: %v", err)
|
||||
}
|
||||
if len(parsed.Clients) != 2 {
|
||||
t.Fatalf("expected 2 clients after dedupe, got %d: %s", len(parsed.Clients), gotDirty.Settings)
|
||||
}
|
||||
if parsed.Clients[0]["email"] != "dup@x" || parsed.Clients[1]["email"] != "keep@x" {
|
||||
t.Fatalf("expected first occurrences [dup@x keep@x], got %v", parsed.Clients)
|
||||
}
|
||||
|
||||
var gotClean model.Inbound
|
||||
if err := db.First(&gotClean, clean.Id).Error; err != nil {
|
||||
t.Fatalf("reload clean inbound: %v", err)
|
||||
}
|
||||
if gotClean.Settings != cleanSettings {
|
||||
t.Fatalf("clean inbound settings were rewritten:\nbefore: %s\nafter: %s", cleanSettings, gotClean.Settings)
|
||||
}
|
||||
|
||||
if err := dedupeInboundSettingsClients(); err != nil {
|
||||
t.Fatalf("second dedupe run: %v", err)
|
||||
}
|
||||
var again model.Inbound
|
||||
if err := db.First(&again, dirty.Id).Error; err != nil {
|
||||
t.Fatalf("reload after second run: %v", err)
|
||||
}
|
||||
if again.Settings != gotDirty.Settings {
|
||||
t.Fatal("dedupe is not idempotent: settings changed on the second run")
|
||||
}
|
||||
}
|
||||
@@ -270,19 +270,14 @@ func resetPostgresSequences(dst *gorm.DB) error {
|
||||
return resyncPostgresSequences(dst, migrationModels())
|
||||
}
|
||||
|
||||
// resyncPostgresSequences sets each model's id sequence to MAX(id) so the next
|
||||
// auto-increment INSERT won't collide with an existing row. Table names are
|
||||
// resolved from the models themselves (not hardcoded), so they always match the
|
||||
// migrated tables. The statement is a no-op for tables without an id sequence
|
||||
// (e.g. composite-PK tables), and idempotent on a healthy DB, so it is safe to
|
||||
// run both after migration and on every Postgres startup.
|
||||
// resyncPostgresSequences sets each model's id sequence to MAX(id); idempotent. Id-less
|
||||
// composite-PK tables are skipped — Postgres rejects MAX(id) at parse time and logs it (#5665).
|
||||
func resyncPostgresSequences(db *gorm.DB, models []any) error {
|
||||
for _, m := range models {
|
||||
stmt := &gorm.Statement{DB: db}
|
||||
if err := stmt.Parse(m); err != nil {
|
||||
t, ok := tableWithIdColumn(db, m)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
t := stmt.Table
|
||||
// t comes from the trusted model set parsed by GORM, not user input, so
|
||||
// interpolating it as an identifier is safe. We ignore errors per-table.
|
||||
_ = db.Exec(
|
||||
@@ -293,3 +288,16 @@ func resyncPostgresSequences(db *gorm.DB, models []any) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// tableWithIdColumn resolves a model's table name and reports whether its GORM
|
||||
// schema maps an "id" database column.
|
||||
func tableWithIdColumn(db *gorm.DB, m any) (string, bool) {
|
||||
stmt := &gorm.Statement{DB: db}
|
||||
if err := stmt.Parse(m); err != nil {
|
||||
return "", false
|
||||
}
|
||||
if stmt.Schema == nil || stmt.Schema.LookUpField("id") == nil {
|
||||
return "", false
|
||||
}
|
||||
return stmt.Table, true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
// TestRepairOverflowedTrafficCounters_HealsSQLiteRealPromotion reproduces
|
||||
// #5762: a counter pushed past int64 makes SQLite silently store the cell as
|
||||
// REAL, after which scanning the row back into the Go int64 field fails and
|
||||
// every reader of client_traffics breaks. The startup repair must convert the
|
||||
// cell back to a scannable integer clamped to TrafficMax.
|
||||
func TestRepairOverflowedTrafficCounters_HealsSQLiteRealPromotion(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB failed: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
rows := []xray.ClientTraffic{
|
||||
{Email: "overflowed@x", Enable: true, Up: 5, Down: 6},
|
||||
{Email: "negative@x", Enable: true, Up: 7, Down: 8},
|
||||
{Email: "healthy@x", Enable: true, Up: 100, Down: 200},
|
||||
}
|
||||
for i := range rows {
|
||||
if err := db.Create(&rows[i]).Error; err != nil {
|
||||
t.Fatalf("create traffic row %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := db.Exec("UPDATE client_traffics SET down = 1.2247589467272907e+19 WHERE email = 'overflowed@x'").Error; err != nil {
|
||||
t.Fatalf("corrupt down: %v", err)
|
||||
}
|
||||
if err := db.Exec("UPDATE client_traffics SET up = -42 WHERE email = 'negative@x'").Error; err != nil {
|
||||
t.Fatalf("corrupt up: %v", err)
|
||||
}
|
||||
|
||||
var broken []xray.ClientTraffic
|
||||
if err := db.Find(&broken).Error; err == nil {
|
||||
t.Fatal("expected the REAL-promoted row to break scanning before the repair")
|
||||
}
|
||||
|
||||
if err := repairOverflowedTrafficCounters(); err != nil {
|
||||
t.Fatalf("repairOverflowedTrafficCounters: %v", err)
|
||||
}
|
||||
|
||||
byEmail := map[string]xray.ClientTraffic{}
|
||||
var repaired []xray.ClientTraffic
|
||||
if err := db.Find(&repaired).Error; err != nil {
|
||||
t.Fatalf("scan after repair: %v", err)
|
||||
}
|
||||
for _, r := range repaired {
|
||||
byEmail[r.Email] = r
|
||||
}
|
||||
if got := byEmail["overflowed@x"].Down; got != TrafficMax {
|
||||
t.Errorf("overflowed down: expected clamp to %d, got %d", TrafficMax, got)
|
||||
}
|
||||
if got := byEmail["overflowed@x"].Up; got != 5 {
|
||||
t.Errorf("overflowed up: expected untouched 5, got %d", got)
|
||||
}
|
||||
if got := byEmail["negative@x"].Up; got != 0 {
|
||||
t.Errorf("negative up: expected clamp to 0, got %d", got)
|
||||
}
|
||||
if got := byEmail["healthy@x"]; got.Up != 100 || got.Down != 200 {
|
||||
t.Errorf("healthy row changed: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClampedAddExpr_CapsAtTrafficMax verifies the write-path clamp: a delta
|
||||
// applied to a counter near the cap must saturate at TrafficMax instead of
|
||||
// overflowing int64 (which SQLite would promote to REAL).
|
||||
func TestClampedAddExpr_CapsAtTrafficMax(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB failed: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = CloseDB() })
|
||||
|
||||
row := xray.ClientTraffic{Email: "near-cap@x", Enable: true, Up: TrafficMax - 10, Down: 1}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatalf("create traffic row: %v", err)
|
||||
}
|
||||
|
||||
query := "UPDATE client_traffics SET up = " + ClampedAddExpr("up") + ", down = " + ClampedAddExpr("down") + " WHERE email = ?"
|
||||
if err := db.Exec(query, int64(1_000_000), int64(5), "near-cap@x").Error; err != nil {
|
||||
t.Fatalf("clamped add: %v", err)
|
||||
}
|
||||
|
||||
var got xray.ClientTraffic
|
||||
if err := db.Where("email = ?", "near-cap@x").First(&got).Error; err != nil {
|
||||
t.Fatalf("scan after clamped add: %v", err)
|
||||
}
|
||||
if got.Up != TrafficMax {
|
||||
t.Errorf("up: expected saturation at %d, got %d", TrafficMax, got.Up)
|
||||
}
|
||||
if got.Down != 6 {
|
||||
t.Errorf("down: expected 6, got %d", got.Down)
|
||||
}
|
||||
}
|
||||
@@ -240,8 +240,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
|
||||
case model.VLESS:
|
||||
proxy["type"] = "vless"
|
||||
proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
|
||||
var inboundSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
|
||||
inboundSettings := subReq.linkSettings(inbound)
|
||||
streamSecurity, _ := stream["security"].(string)
|
||||
if client.Flow != "" && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
|
||||
proxy["flow"] = client.Flow
|
||||
@@ -258,8 +257,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
|
||||
case model.Shadowsocks:
|
||||
proxy["type"] = "ss"
|
||||
proxy["password"] = client.Password
|
||||
var inboundSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
|
||||
inboundSettings := subReq.linkSettings(inbound)
|
||||
method, _ := inboundSettings["method"].(string)
|
||||
if method == "" {
|
||||
return nil
|
||||
@@ -288,8 +286,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
|
||||
// helpers prune fields (like `allowInsecure` / the salamander obfs
|
||||
// block) that the hysteria proxy wants preserved.
|
||||
func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
|
||||
var inboundSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
|
||||
inboundSettings := subReq.linkSettings(inbound)
|
||||
|
||||
proxyType := "hysteria2"
|
||||
authKey := "password"
|
||||
|
||||
+52
-28
@@ -146,18 +146,54 @@ func (a *SUBController) initRouter(g *gin.RouterGroup) {
|
||||
}
|
||||
}
|
||||
|
||||
// subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
|
||||
func (a *SUBController) subs(c *gin.Context) {
|
||||
subId := c.Param("subid")
|
||||
scheme, host, hostWithPort, hostHeader := a.subService.ResolveRequest(c)
|
||||
subReq := a.subService.ForRequest(host)
|
||||
// The remark template's per-client info is for the content a client app
|
||||
// imports — the raw subscription body. A browser viewing the HTML info page
|
||||
// gets clean, name-only remarks (usage is shown in the page summary).
|
||||
// maybeServeSubPage renders the HTML info page when the request comes from a
|
||||
// browser (Accept: text/html) or explicitly asks for it (?html=1 or ?view=html).
|
||||
// It reports whether the request was handled. The remark template's per-client
|
||||
// info is for the content a client app imports — the raw subscription body. A
|
||||
// browser viewing the HTML info page gets clean, name-only remarks (usage is
|
||||
// shown in the page summary).
|
||||
func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
|
||||
accept := c.GetHeader("Accept")
|
||||
wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
|
||||
subReq.subscriptionBody = !wantsHTML
|
||||
if !wantsHTML {
|
||||
return false
|
||||
}
|
||||
subId := c.Param("subid")
|
||||
_, host, _, hostHeader := a.subService.ResolveRequest(c)
|
||||
subReq := a.subService.ForRequest(host)
|
||||
subReq.subscriptionBody = false
|
||||
subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
|
||||
if err != nil || len(subs) == 0 {
|
||||
writeSubError(c, err)
|
||||
return true
|
||||
}
|
||||
subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
|
||||
if !a.jsonEnabled {
|
||||
subJsonURL = ""
|
||||
}
|
||||
if !a.clashEnabled {
|
||||
subClashURL = ""
|
||||
}
|
||||
basePath, exists := c.Get("base_path")
|
||||
if !exists {
|
||||
basePath = "/"
|
||||
}
|
||||
basePathStr := basePath.(string)
|
||||
page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
|
||||
a.serveSubPage(c, basePathStr, page)
|
||||
return true
|
||||
}
|
||||
|
||||
// subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
|
||||
func (a *SUBController) subs(c *gin.Context) {
|
||||
if a.maybeServeSubPage(c) {
|
||||
return
|
||||
}
|
||||
subId := c.Param("subid")
|
||||
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
|
||||
subReq := a.subService.ForRequest(host)
|
||||
subReq.subscriptionBody = true
|
||||
subs, _, _, traffic, err := subReq.getSubs(subId)
|
||||
if err != nil || len(subs) == 0 {
|
||||
writeSubError(c, err)
|
||||
} else {
|
||||
@@ -167,25 +203,6 @@ func (a *SUBController) subs(c *gin.Context) {
|
||||
result.WriteString("\n")
|
||||
}
|
||||
|
||||
// If the request expects HTML (e.g., browser) or explicitly asked (?html=1 or ?view=html), render the info page here
|
||||
if wantsHTML {
|
||||
subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
|
||||
if !a.jsonEnabled {
|
||||
subJsonURL = ""
|
||||
}
|
||||
if !a.clashEnabled {
|
||||
subClashURL = ""
|
||||
}
|
||||
basePath, exists := c.Get("base_path")
|
||||
if !exists {
|
||||
basePath = "/"
|
||||
}
|
||||
basePathStr := basePath.(string)
|
||||
page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
|
||||
a.serveSubPage(c, basePathStr, page)
|
||||
return
|
||||
}
|
||||
|
||||
// Add headers
|
||||
header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
|
||||
profileUrl := a.subProfileUrl
|
||||
@@ -264,6 +281,7 @@ func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageD
|
||||
"links": page.Result,
|
||||
"emails": page.Emails,
|
||||
"datepicker": datepicker,
|
||||
"announce": a.subAnnounce,
|
||||
}
|
||||
|
||||
// When an admin has configured a custom subscription theme, render it
|
||||
@@ -366,6 +384,9 @@ func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, er
|
||||
|
||||
// subJsons handles HTTP requests for JSON subscription configurations.
|
||||
func (a *SUBController) subJsons(c *gin.Context) {
|
||||
if a.maybeServeSubPage(c) {
|
||||
return
|
||||
}
|
||||
subId := c.Param("subid")
|
||||
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
|
||||
jsonSub, header, err := a.subJsonService.GetJson(subId, host)
|
||||
@@ -383,6 +404,9 @@ func (a *SUBController) subJsons(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (a *SUBController) subClashs(c *gin.Context) {
|
||||
if a.maybeServeSubPage(c) {
|
||||
return
|
||||
}
|
||||
subId := c.Param("subid")
|
||||
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
|
||||
clashSub, header, err := a.subClashService.GetClash(subId, host)
|
||||
|
||||
@@ -138,7 +138,7 @@ func (s *SubJsonService) GetJson(subId string, host string) (string, string, err
|
||||
|
||||
func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
|
||||
var newJsonArray []json_util.RawMessage
|
||||
stream := s.streamData(inbound.StreamSettings)
|
||||
stream := s.streamData(inbound.StreamSettings, subKey(client))
|
||||
|
||||
// When externalProxy is empty the JSON config falls back to a
|
||||
// synthetic one whose `dest` is the host the client connects to.
|
||||
@@ -212,9 +212,9 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c
|
||||
case "vless":
|
||||
vc := client
|
||||
vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
|
||||
newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, vc, jsonMux(mux, hostMux)))
|
||||
newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
|
||||
case "trojan", "shadowsocks":
|
||||
newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client, jsonMux(mux, hostMux)))
|
||||
newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
|
||||
case "hysteria":
|
||||
newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
|
||||
}
|
||||
@@ -234,15 +234,25 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c
|
||||
return newJsonArray
|
||||
}
|
||||
|
||||
func (s *SubJsonService) streamData(stream string) map[string]any {
|
||||
func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
|
||||
var streamSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(stream), &streamSettings)
|
||||
if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
|
||||
streamSettings = map[string]any{}
|
||||
}
|
||||
security, _ := streamSettings["security"].(string)
|
||||
switch security {
|
||||
case "tls":
|
||||
streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
|
||||
if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
|
||||
streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
|
||||
} else {
|
||||
delete(streamSettings, "tlsSettings")
|
||||
}
|
||||
case "reality":
|
||||
streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
|
||||
if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
|
||||
streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
|
||||
} else {
|
||||
delete(streamSettings, "realitySettings")
|
||||
}
|
||||
}
|
||||
delete(streamSettings, "sockopt")
|
||||
|
||||
@@ -322,7 +332,7 @@ func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
|
||||
return tlsData
|
||||
}
|
||||
|
||||
func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
|
||||
func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
|
||||
rltyData := make(map[string]any, 1)
|
||||
rltyClientSettings, _ := rData["settings"].(map[string]any)
|
||||
|
||||
@@ -331,8 +341,8 @@ func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
|
||||
rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
|
||||
rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
|
||||
|
||||
// Set random data
|
||||
rltyData["spiderX"] = "/" + random.Seq(15)
|
||||
seed, _ := rltyClientSettings["spiderX"].(string)
|
||||
rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
|
||||
shortIds, ok := rData["shortIds"].([]any)
|
||||
if ok && len(shortIds) > 0 {
|
||||
rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
|
||||
@@ -383,7 +393,7 @@ func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_ut
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
|
||||
func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
|
||||
outbound := Outbound{}
|
||||
outbound.Protocol = string(inbound.Protocol)
|
||||
outbound.Tag = "proxy"
|
||||
@@ -393,8 +403,7 @@ func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_ut
|
||||
outbound.StreamSettings = streamSettings
|
||||
|
||||
// Add encryption for VLESS outbound from inbound settings
|
||||
var inboundSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
|
||||
inboundSettings := subReq.linkSettings(inbound)
|
||||
encryption, _ := inboundSettings["encryption"].(string)
|
||||
|
||||
settings := map[string]any{
|
||||
@@ -412,7 +421,7 @@ func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_ut
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
|
||||
func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
|
||||
outbound := Outbound{}
|
||||
|
||||
serverData := make([]ServerSetting, 1)
|
||||
@@ -424,8 +433,7 @@ func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_u
|
||||
}
|
||||
|
||||
if inbound.Protocol == model.Shadowsocks {
|
||||
var inboundSettings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
|
||||
inboundSettings := subReq.linkSettings(inbound)
|
||||
method, _ := inboundSettings["method"].(string)
|
||||
serverData[0].Method = method
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ func TestSubJsonServiceInjectsGlobalFinalMask(t *testing.T) {
|
||||
t.Fatal("direct_out outbound must never be emitted")
|
||||
}
|
||||
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
|
||||
if _, ok := stream["sockopt"]; ok {
|
||||
t.Fatal("legacy direct_out dialerProxy sockopt must never be set")
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func TestSubJsonServiceMergesWithExistingFinalMask(t *testing.T) {
|
||||
stream := svc.streamData(`{
|
||||
"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}},
|
||||
"finalmask":{"tcp":[{"type":"sudoku"}]}
|
||||
}`)
|
||||
}`, "")
|
||||
|
||||
finalmask, _ := stream["finalmask"].(map[string]any)
|
||||
tcp, _ := finalmask["tcp"].([]any)
|
||||
@@ -93,7 +93,7 @@ func TestSubJsonServiceMergesWithExistingFinalMask(t *testing.T) {
|
||||
|
||||
func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) {
|
||||
svc := NewSubJsonService("", "", "", nil)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
|
||||
if _, ok := stream["finalmask"]; ok {
|
||||
t.Fatal("no finalmask should be emitted when subJsonFinalMask is empty")
|
||||
}
|
||||
@@ -107,7 +107,7 @@ func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) {
|
||||
// to import the config (#5401).
|
||||
func TestSubJsonServicePinnedCertJoinedToString(t *testing.T) {
|
||||
svc := NewSubJsonService("", "", "", nil)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","settings":{"pinnedPeerCertSha256":["aa11","bb22"]}}}`)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","settings":{"pinnedPeerCertSha256":["aa11","bb22"]}}}`, "")
|
||||
|
||||
tls, _ := stream["tlsSettings"].(map[string]any)
|
||||
if tls == nil {
|
||||
@@ -122,7 +122,7 @@ func TestSubJsonServiceVlessFlattened(t *testing.T) {
|
||||
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
|
||||
client := model.Client{ID: "uuid-1", Flow: "xtls-rprx-vision"}
|
||||
|
||||
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(inbound, nil, client, ""))
|
||||
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(&SubService{}, inbound, nil, client, ""))
|
||||
if _, ok := settings["vnext"]; ok {
|
||||
t.Fatal("vless outbound must not use vnext")
|
||||
}
|
||||
@@ -151,7 +151,7 @@ func TestSubJsonServiceServerUsesServersArray(t *testing.T) {
|
||||
trojan := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Trojan, Settings: `{}`}
|
||||
client := model.Client{Password: "p4ss"}
|
||||
|
||||
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(trojan, nil, client, ""))
|
||||
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, trojan, nil, client, ""))
|
||||
server := firstServer(settings)
|
||||
if server == nil {
|
||||
t.Fatalf("trojan outbound must use a servers array, got: %#v", settings)
|
||||
@@ -164,7 +164,7 @@ func TestSubJsonServiceServerUsesServersArray(t *testing.T) {
|
||||
}
|
||||
|
||||
ss := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Shadowsocks, Settings: `{"method":"aes-256-gcm"}`}
|
||||
ssSettings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(ss, nil, client, ""))
|
||||
ssSettings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, ss, nil, client, ""))
|
||||
ssServer := firstServer(ssSettings)
|
||||
if ssServer == nil {
|
||||
t.Fatalf("shadowsocks outbound must use a servers array, got: %#v", ssSettings)
|
||||
@@ -181,7 +181,7 @@ func TestSubJsonServiceXmuxSuppressesGlobalMux(t *testing.T) {
|
||||
// When xmux is present in xhttpSettings, the per-inbound xmux handles
|
||||
// multiplexing and the legacy outbound.Mux must NOT be set.
|
||||
stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up","xmux":{"maxConcurrency":"16-32"}}}`
|
||||
parsed := svc.streamData(stream)
|
||||
parsed := svc.streamData(stream, "")
|
||||
|
||||
mux := globalMux
|
||||
if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
|
||||
@@ -194,7 +194,7 @@ func TestSubJsonServiceXmuxSuppressesGlobalMux(t *testing.T) {
|
||||
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
|
||||
client := model.Client{ID: "uuid-1"}
|
||||
|
||||
raw := svc.genVless(inbound, streamSettings, client, mux)
|
||||
raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
|
||||
var ob map[string]any
|
||||
if err := json.Unmarshal(raw, &ob); err != nil {
|
||||
t.Fatalf("unmarshal outbound: %v", err)
|
||||
@@ -227,7 +227,7 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
|
||||
|
||||
// When no xmux is present, the global subJsonMux should be used.
|
||||
stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up"}}`
|
||||
parsed := svc.streamData(stream)
|
||||
parsed := svc.streamData(stream, "")
|
||||
|
||||
mux := globalMux
|
||||
if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
|
||||
@@ -240,7 +240,7 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
|
||||
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
|
||||
client := model.Client{ID: "uuid-1"}
|
||||
|
||||
raw := svc.genVless(inbound, streamSettings, client, mux)
|
||||
raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
|
||||
var ob map[string]any
|
||||
if err := json.Unmarshal(raw, &ob); err != nil {
|
||||
t.Fatalf("unmarshal outbound: %v", err)
|
||||
@@ -254,3 +254,80 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
|
||||
t.Fatalf("mux payload wrong: %#v", m)
|
||||
}
|
||||
}
|
||||
|
||||
func realitySpiderXFromStream(t *testing.T, svc *SubJsonService, clientKey string) string {
|
||||
t.Helper()
|
||||
stream := svc.streamData(`{
|
||||
"network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
|
||||
"realitySettings":{
|
||||
"serverNames":["reality.example.com"],
|
||||
"shortIds":["ab12cd"],
|
||||
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/seed"}
|
||||
}
|
||||
}`, clientKey)
|
||||
rlty, _ := stream["realitySettings"].(map[string]any)
|
||||
if rlty == nil {
|
||||
t.Fatal("streamData dropped realitySettings")
|
||||
}
|
||||
spx, _ := rlty["spiderX"].(string)
|
||||
if len(spx) != 16 || spx[0] != '/' {
|
||||
t.Fatalf("spiderX = %q, want a 16-char /-prefixed value", spx)
|
||||
}
|
||||
return spx
|
||||
}
|
||||
|
||||
func TestSubJsonServiceRealityDataDerivesPerClientSpiderX(t *testing.T) {
|
||||
svc := NewSubJsonService("", "", "", nil)
|
||||
|
||||
alice := realitySpiderXFromStream(t, svc, "subAlice")
|
||||
if again := realitySpiderXFromStream(t, svc, "subAlice"); again != alice {
|
||||
t.Fatalf("spiderX not stable for the same client: %q vs %q", alice, again)
|
||||
}
|
||||
if bob := realitySpiderXFromStream(t, svc, "subBob"); bob == alice {
|
||||
t.Fatalf("spiderX identical across clients (fingerprintable): %q", alice)
|
||||
}
|
||||
}
|
||||
|
||||
// streamData must tolerate malformed stored inbounds: unparseable stream JSON
|
||||
// (with a finalMask configured, which writes into the map) and tls/reality
|
||||
// security whose settings key is missing or null previously panicked the
|
||||
// subscription request.
|
||||
func TestSubJsonServiceStreamDataMalformedInputs(t *testing.T) {
|
||||
withMask := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil)
|
||||
stream := withMask.streamData("not-json", "clientKey")
|
||||
if _, ok := stream["finalmask"]; !ok {
|
||||
t.Fatal("finalMask must still apply when stream settings fail to parse")
|
||||
}
|
||||
|
||||
svc := NewSubJsonService("", "", "", nil)
|
||||
noReality := svc.streamData(`{"network":"tcp","security":"reality"}`, "clientKey")
|
||||
if v, ok := noReality["realitySettings"]; ok {
|
||||
t.Fatalf("missing realitySettings must stay absent, got %v", v)
|
||||
}
|
||||
nullTls := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":null}`, "")
|
||||
if v, ok := nullTls["tlsSettings"]; ok {
|
||||
t.Fatalf("null tlsSettings must be dropped, got %v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubJsonServiceRealityDataSpiderXFallsBackWhenNoClientKey(t *testing.T) {
|
||||
svc := NewSubJsonService("", "", "", nil)
|
||||
|
||||
stream := svc.streamData(`{
|
||||
"network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
|
||||
"realitySettings":{
|
||||
"serverNames":["reality.example.com"],
|
||||
"shortIds":["ab12cd"],
|
||||
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox"}
|
||||
}
|
||||
}`, "")
|
||||
|
||||
rlty, _ := stream["realitySettings"].(map[string]any)
|
||||
if rlty == nil {
|
||||
t.Fatal("streamData dropped realitySettings")
|
||||
}
|
||||
spx, _ := rlty["spiderX"].(string)
|
||||
if len(spx) != 16 || spx[0] != '/' {
|
||||
t.Fatalf("spiderX fallback = %q, want random 16-char /-prefixed value", spx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,11 +67,11 @@ func TestSubJsonService_MuxAttachedWhenConfigured(t *testing.T) {
|
||||
protocol model.Protocol
|
||||
}{
|
||||
{"vmess mux", NewSubJsonService(mux, "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, mux), true, model.VMESS},
|
||||
{"vless mux", NewSubJsonService(mux, "", "", nil).genVless(&model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, mux), true, model.VLESS},
|
||||
{"server mux", NewSubJsonService(mux, "", "", nil).genServer(&model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, mux), true, model.Trojan},
|
||||
{"vless mux", NewSubJsonService(mux, "", "", nil).genVless(&SubService{}, &model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, mux), true, model.VLESS},
|
||||
{"server mux", NewSubJsonService(mux, "", "", nil).genServer(&SubService{}, &model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, mux), true, model.Trojan},
|
||||
{"vmess no mux", NewSubJsonService("", "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, ""), false, model.VMESS},
|
||||
{"vless no mux", NewSubJsonService("", "", "", nil).genVless(&model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, ""), false, model.VLESS},
|
||||
{"server no mux", NewSubJsonService("", "", "", nil).genServer(&model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, ""), false, model.Trojan},
|
||||
{"vless no mux", NewSubJsonService("", "", "", nil).genVless(&SubService{}, &model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, ""), false, model.VLESS},
|
||||
{"server no mux", NewSubJsonService("", "", "", nil).genServer(&SubService{}, &model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, ""), false, model.Trojan},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -95,15 +95,15 @@ func TestSubJsonService_MuxAttachedWhenConfigured(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- json_service.go:268 — a non-empty finalMask that merges to nothing must
|
||||
// --- applyGlobalFinalMask — a non-empty finalMask that merges to nothing must
|
||||
// not add the finalmask key (the `len(merged) > 0` guard). ---
|
||||
|
||||
func TestSubJsonService_FinalMaskMergingToEmptyNotAdded(t *testing.T) {
|
||||
// finalMask is non-empty (passes the len(fm)==0 early return) but its only
|
||||
// key is an empty tcp slice, which mergeFinalMask drops → merged is empty,
|
||||
// so applyGlobalFinalMask (json_service.go:268) must NOT set finalmask.
|
||||
// so applyGlobalFinalMask must NOT set finalmask.
|
||||
svc := NewSubJsonService("", "", `{"tcp":[]}`, nil)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`)
|
||||
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
|
||||
if _, ok := stream["finalmask"]; ok {
|
||||
t.Fatalf("finalMask merging to empty must not add a finalmask key: %#v", stream["finalmask"])
|
||||
}
|
||||
@@ -111,13 +111,13 @@ func TestSubJsonService_FinalMaskMergingToEmptyNotAdded(t *testing.T) {
|
||||
// Sanity: a finalMask that DOES merge to something still gets set, so the
|
||||
// guard is the only distinguishing factor.
|
||||
svc2 := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil)
|
||||
stream2 := svc2.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`)
|
||||
stream2 := svc2.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
|
||||
if _, ok := stream2["finalmask"]; !ok {
|
||||
t.Fatal("non-empty finalMask must be set")
|
||||
}
|
||||
}
|
||||
|
||||
// --- json_service.go:494 — an empty extra tcp slice must not clobber the base ---
|
||||
// --- mergeFinalMask — an empty extra tcp slice must not clobber the base ---
|
||||
|
||||
func TestMergeFinalMask_EmptyExtraTcpKeepsBase(t *testing.T) {
|
||||
base := map[string]any{"tcp": []any{map[string]any{"type": "keep"}}}
|
||||
|
||||
@@ -459,11 +459,8 @@ func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client)
|
||||
// needed when a global remark template references client-only tokens. Falls back
|
||||
// to an email-only client if not found.
|
||||
func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Client {
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
for _, c := range clients {
|
||||
if c.Email == email {
|
||||
return c
|
||||
}
|
||||
if c, ok := s.clientForLink(inbound, email); ok {
|
||||
return c
|
||||
}
|
||||
return model.Client{Email: email}
|
||||
}
|
||||
|
||||
+196
-67
@@ -54,6 +54,17 @@ type SubService struct {
|
||||
// doesn't own its row (multi-inbound subscriptions). Filled in
|
||||
// getInboundsBySubId; reset per request in PrepareForRequest.
|
||||
statsByEmail map[string]xray.ClientTraffic
|
||||
// clientsByInbound caches clients resolved for this request keyed by
|
||||
// inbound id then email, so the per-protocol link generators look a client
|
||||
// up without re-parsing the inbound's settings JSON per link.
|
||||
// fullyPrimedInbounds marks inbounds whose complete client list is cached
|
||||
// (a miss there is authoritative). Reset per request in PrepareForRequest.
|
||||
clientsByInbound map[int]map[string]model.Client
|
||||
fullyPrimedInbounds map[int]bool
|
||||
// settingsByInbound caches each inbound's settings decoded once per request
|
||||
// with the clients array left out; generators read only inbound-level
|
||||
// fields (encryption, method, version, …) from it.
|
||||
settingsByInbound map[int]map[string]any
|
||||
}
|
||||
|
||||
// NewSubService creates a new subscription service with the given configuration.
|
||||
@@ -86,10 +97,96 @@ func (s *SubService) PrepareForRequest(host string) {
|
||||
s.address = host
|
||||
s.usageShown = map[string]bool{}
|
||||
s.statsByEmail = map[string]xray.ClientTraffic{}
|
||||
s.clientsByInbound = map[int]map[string]model.Client{}
|
||||
s.fullyPrimedInbounds = map[int]bool{}
|
||||
s.settingsByInbound = map[int]map[string]any{}
|
||||
s.loadNodes()
|
||||
s.loadRemarkSettings()
|
||||
}
|
||||
|
||||
// primeLinkClients caches clients (first occurrence per email, matching the
|
||||
// old settings-JSON iteration order) so clientForLink resolves them without a
|
||||
// parse. complete marks the inbound's whole client list as cached.
|
||||
func (s *SubService) primeLinkClients(inboundId int, clients []model.Client, complete bool) {
|
||||
if inboundId <= 0 {
|
||||
return
|
||||
}
|
||||
if s.clientsByInbound == nil {
|
||||
s.clientsByInbound = map[int]map[string]model.Client{}
|
||||
}
|
||||
m := s.clientsByInbound[inboundId]
|
||||
if m == nil {
|
||||
m = make(map[string]model.Client, len(clients))
|
||||
s.clientsByInbound[inboundId] = m
|
||||
}
|
||||
for _, c := range clients {
|
||||
if _, exists := m[c.Email]; !exists {
|
||||
m[c.Email] = c
|
||||
}
|
||||
}
|
||||
if complete {
|
||||
if s.fullyPrimedInbounds == nil {
|
||||
s.fullyPrimedInbounds = map[int]bool{}
|
||||
}
|
||||
s.fullyPrimedInbounds[inboundId] = true
|
||||
}
|
||||
}
|
||||
|
||||
// clientForLink resolves one client of an inbound by email for link
|
||||
// generation: from the per-request cache when primed, otherwise by parsing
|
||||
// the settings JSON once and caching every client from it.
|
||||
func (s *SubService) clientForLink(inbound *model.Inbound, email string) (model.Client, bool) {
|
||||
if m, ok := s.clientsByInbound[inbound.Id]; ok {
|
||||
if c, hit := m[email]; hit {
|
||||
return c, true
|
||||
}
|
||||
if s.fullyPrimedInbounds[inbound.Id] {
|
||||
return model.Client{}, false
|
||||
}
|
||||
}
|
||||
clients, err := s.inboundService.GetClients(inbound)
|
||||
if err != nil {
|
||||
return model.Client{}, false
|
||||
}
|
||||
s.primeLinkClients(inbound.Id, clients, true)
|
||||
for i := range clients {
|
||||
if clients[i].Email == email {
|
||||
return clients[i], true
|
||||
}
|
||||
}
|
||||
return model.Client{}, false
|
||||
}
|
||||
|
||||
// linkSettings returns the inbound's settings decoded once per request with
|
||||
// the clients array left out — the link generators read only inbound-level
|
||||
// fields from it and resolve clients via clientForLink. The shallow
|
||||
// RawMessage pass skips materializing a huge clients array entirely.
|
||||
func (s *SubService) linkSettings(inbound *model.Inbound) map[string]any {
|
||||
if inbound.Id > 0 {
|
||||
if cached, ok := s.settingsByInbound[inbound.Id]; ok {
|
||||
return cached
|
||||
}
|
||||
}
|
||||
shallow := map[string]json.RawMessage{}
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &shallow)
|
||||
out := make(map[string]any, len(shallow))
|
||||
for key, raw := range shallow {
|
||||
if key == "clients" {
|
||||
continue
|
||||
}
|
||||
var value any
|
||||
_ = json.Unmarshal(raw, &value)
|
||||
out[key] = value
|
||||
}
|
||||
if inbound.Id > 0 {
|
||||
if s.settingsByInbound == nil {
|
||||
s.settingsByInbound = map[int]map[string]any{}
|
||||
}
|
||||
s.settingsByInbound[inbound.Id] = out
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// loadRemarkSettings populates the per-request remark formatting state so
|
||||
// every subscription format — raw, JSON, Clash — renders remarks the same way
|
||||
// (the date formatter reads datepicker). Loading it only in getSubs left
|
||||
@@ -144,25 +241,23 @@ func listenIsInternalOnly(listen string) bool {
|
||||
}
|
||||
|
||||
// matchingClients returns the inbound's clients whose SubID equals subId,
|
||||
// deduplicated by email. settings.clients can accumulate duplicate entries
|
||||
// for the same client (multi-node sync/import drift, old DBs): SyncInbound
|
||||
// dedupes the normalized client_inbounds rows on write but never rewrites
|
||||
// the legacy JSON, and the subscription builders iterate that JSON — so
|
||||
// without this guard every duplicate became a duplicate profile in the
|
||||
// output (#5134). Link generation keys purely on (inbound, email), so
|
||||
// same-email entries are pure duplicates and dropping them is lossless.
|
||||
// resolved from the normalized clients/client_inbounds tables (both filter
|
||||
// columns indexed) instead of parsing the settings JSON — at large client
|
||||
// counts that parse made every subscription fetch cost seconds. The
|
||||
// case-insensitive email dedupe stays as cheap insurance even though
|
||||
// clients.email is unique, preserving the #5134 guarantee that duplicate
|
||||
// settings entries never fan out into duplicate profiles. Resolved clients
|
||||
// are primed into the per-request cache so the link generators don't parse
|
||||
// settings either.
|
||||
func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []model.Client {
|
||||
clients, err := s.inboundService.GetClients(inbound)
|
||||
clients, err := s.inboundService.GetClientsBySubId(inbound.Id, subId)
|
||||
if err != nil {
|
||||
logger.Error("SubService - GetClients: Unable to get clients from inbound")
|
||||
logger.Error("SubService - GetClientsBySubId: Unable to get clients from inbound")
|
||||
return nil
|
||||
}
|
||||
var out []model.Client
|
||||
seen := make(map[string]struct{}, len(clients))
|
||||
for _, client := range clients {
|
||||
if client.SubID != subId {
|
||||
continue
|
||||
}
|
||||
key := strings.ToLower(client.Email)
|
||||
if _, dup := seen[key]; dup {
|
||||
continue
|
||||
@@ -170,6 +265,7 @@ func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []mod
|
||||
seen[key] = struct{}{}
|
||||
out = append(out, client)
|
||||
}
|
||||
s.primeLinkClients(inbound.Id, out, false)
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -253,6 +349,7 @@ func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
s.primeLinkClients(inbound.Id, clients, true)
|
||||
s.projectThroughFallbackMaster(inbound)
|
||||
hostEps := s.hostEndpoints(inbound, "raw")
|
||||
var out []string
|
||||
@@ -362,7 +459,7 @@ func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
|
||||
func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
|
||||
db := database.GetDB()
|
||||
var inbounds []*model.Inbound
|
||||
err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in (
|
||||
err := db.Model(model.Inbound{}).Where(`id in (
|
||||
SELECT DISTINCT inbounds.id
|
||||
FROM inbounds
|
||||
JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
|
||||
@@ -374,19 +471,34 @@ func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.indexStatsByEmail(inbounds)
|
||||
s.indexStatsBySubId(subId)
|
||||
return inbounds, nil
|
||||
}
|
||||
|
||||
// indexStatsByEmail records every loaded inbound's client traffic rows keyed by
|
||||
// email so statsForClient can resolve a client's usage even on an inbound that
|
||||
// doesn't own its (globally unique) client_traffics row. See statsByEmail.
|
||||
func (s *SubService) indexStatsByEmail(inbounds []*model.Inbound) {
|
||||
// indexStatsBySubId loads the traffic rows for just this subscriber's clients
|
||||
// into statsByEmail so statsForClient can resolve a client's usage on any of
|
||||
// its inbounds. It replaces preloading every matched inbound's ClientStats,
|
||||
// which read the entire client_traffics table on every subscription fetch of
|
||||
// a large inbound; statsForClient's per-email DB fallback covers any miss.
|
||||
func (s *SubService) indexStatsBySubId(subId string) {
|
||||
if s.statsByEmail == nil {
|
||||
s.statsByEmail = map[string]xray.ClientTraffic{}
|
||||
}
|
||||
for _, inbound := range inbounds {
|
||||
for _, st := range inbound.ClientStats {
|
||||
db := database.GetDB()
|
||||
var emails []string
|
||||
if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", subId).Pluck("email", &emails).Error; err != nil {
|
||||
logger.Error("SubService - indexStatsBySubId: load emails:", err)
|
||||
return
|
||||
}
|
||||
const chunk = 400
|
||||
for lo := 0; lo < len(emails); lo += chunk {
|
||||
hi := min(lo+chunk, len(emails))
|
||||
var rows []xray.ClientTraffic
|
||||
if err := db.Where("email IN ?", emails[lo:hi]).Find(&rows).Error; err != nil {
|
||||
logger.Error("SubService - indexStatsBySubId: load traffics:", err)
|
||||
return
|
||||
}
|
||||
for _, st := range rows {
|
||||
s.statsByEmail[st.Email] = st
|
||||
}
|
||||
}
|
||||
@@ -516,21 +628,14 @@ func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) stri
|
||||
if inbound.Protocol != model.WireGuard {
|
||||
return ""
|
||||
}
|
||||
settings := map[string]any{}
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
|
||||
settings := s.linkSettings(inbound)
|
||||
secretKey, _ := settings["secretKey"].(string)
|
||||
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
var client *model.Client
|
||||
for i := range clients {
|
||||
if clients[i].Email == email {
|
||||
client = &clients[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if client == nil || client.PrivateKey == "" {
|
||||
resolved, ok := s.clientForLink(inbound, email)
|
||||
if !ok || resolved.PrivateKey == "" {
|
||||
return ""
|
||||
}
|
||||
client := &resolved
|
||||
|
||||
link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
|
||||
params := make(map[string]string)
|
||||
@@ -607,10 +712,12 @@ func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
|
||||
applyVmessTLSParams(stream, obj)
|
||||
}
|
||||
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
clientIndex := findClientIndex(clients, email)
|
||||
obj["id"] = clients[clientIndex].ID
|
||||
obj["scy"] = clients[clientIndex].Security
|
||||
client, ok := s.clientForLink(inbound, email)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
obj["id"] = client.ID
|
||||
obj["scy"] = client.Security
|
||||
|
||||
externalProxies, _ := stream["externalProxy"].([]any)
|
||||
|
||||
@@ -659,17 +766,18 @@ func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
|
||||
}
|
||||
address := s.resolveInboundAddress(inbound)
|
||||
stream := unmarshalStreamSettings(inbound.StreamSettings)
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
clientIndex := findClientIndex(clients, email)
|
||||
uuid := clients[clientIndex].ID
|
||||
client, ok := s.clientForLink(inbound, email)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
uuid := client.ID
|
||||
port := inbound.Port
|
||||
streamNetwork := stream["network"].(string)
|
||||
params := make(map[string]string)
|
||||
params["type"] = streamNetwork
|
||||
|
||||
// Add encryption parameter for VLESS from inbound settings
|
||||
var settings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
|
||||
settings := s.linkSettings(inbound)
|
||||
if encryption, ok := settings["encryption"].(string); ok {
|
||||
params["encryption"] = encryption
|
||||
}
|
||||
@@ -683,12 +791,12 @@ func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
|
||||
case "tls":
|
||||
applyShareTLSParams(stream, params)
|
||||
case "reality":
|
||||
applyShareRealityParams(stream, params)
|
||||
applyShareRealityParams(stream, params, subKey(client))
|
||||
default:
|
||||
params["security"] = "none"
|
||||
}
|
||||
if len(clients[clientIndex].Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) {
|
||||
params["flow"] = clients[clientIndex].Flow
|
||||
if len(client.Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) {
|
||||
params["flow"] = client.Flow
|
||||
}
|
||||
|
||||
externalProxies, _ := stream["externalProxy"].([]any)
|
||||
@@ -717,9 +825,11 @@ func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string
|
||||
}
|
||||
address := s.resolveInboundAddress(inbound)
|
||||
stream := unmarshalStreamSettings(inbound.StreamSettings)
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
clientIndex := findClientIndex(clients, email)
|
||||
password := encodeUserinfo(clients[clientIndex].Password)
|
||||
client, ok := s.clientForLink(inbound, email)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
password := encodeUserinfo(client.Password)
|
||||
port := inbound.Port
|
||||
streamNetwork := stream["network"].(string)
|
||||
params := make(map[string]string)
|
||||
@@ -734,9 +844,9 @@ func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string
|
||||
case "tls":
|
||||
applyShareTLSParams(stream, params)
|
||||
case "reality":
|
||||
applyShareRealityParams(stream, params)
|
||||
if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
|
||||
params["flow"] = clients[clientIndex].Flow
|
||||
applyShareRealityParams(stream, params, subKey(client))
|
||||
if streamNetwork == "tcp" && len(client.Flow) > 0 {
|
||||
params["flow"] = client.Flow
|
||||
}
|
||||
default:
|
||||
params["security"] = "none"
|
||||
@@ -788,13 +898,14 @@ func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) st
|
||||
}
|
||||
address := s.resolveInboundAddress(inbound)
|
||||
stream := unmarshalStreamSettings(inbound.StreamSettings)
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
client, ok := s.clientForLink(inbound, email)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
var settings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
|
||||
settings := s.linkSettings(inbound)
|
||||
inboundPassword := settings["password"].(string)
|
||||
method := settings["method"].(string)
|
||||
clientIndex := findClientIndex(clients, email)
|
||||
streamNetwork := stream["network"].(string)
|
||||
params := make(map[string]string)
|
||||
params["type"] = streamNetwork
|
||||
@@ -828,9 +939,9 @@ func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) st
|
||||
userInfo = fmt.Sprintf("%s:%s:%s",
|
||||
url.QueryEscape(method),
|
||||
url.QueryEscape(inboundPassword),
|
||||
url.QueryEscape(clients[clientIndex].Password))
|
||||
url.QueryEscape(client.Password))
|
||||
} else {
|
||||
userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, clients[clientIndex].Password))
|
||||
userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, client.Password))
|
||||
}
|
||||
|
||||
externalProxies, _ := stream["externalProxy"].([]any)
|
||||
@@ -861,15 +972,11 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin
|
||||
}
|
||||
var stream map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
|
||||
clients, _ := s.inboundService.GetClients(inbound)
|
||||
clientIndex := -1
|
||||
for i, client := range clients {
|
||||
if client.Email == email {
|
||||
clientIndex = i
|
||||
break
|
||||
}
|
||||
client, ok := s.clientForLink(inbound, email)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
auth := encodeUserinfo(clients[clientIndex].Auth)
|
||||
auth := encodeUserinfo(client.Auth)
|
||||
params := make(map[string]string)
|
||||
|
||||
params["security"] = "tls"
|
||||
@@ -928,8 +1035,7 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin
|
||||
}
|
||||
}
|
||||
|
||||
var settings map[string]any
|
||||
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
|
||||
settings := s.linkSettings(inbound)
|
||||
version, _ := settings["version"].(float64)
|
||||
protocol := "hysteria2"
|
||||
if int(version) == 1 {
|
||||
@@ -1330,7 +1436,7 @@ func hysteriaPinHex(pin string) string {
|
||||
return pin
|
||||
}
|
||||
|
||||
func applyShareRealityParams(stream map[string]any, params map[string]string) {
|
||||
func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
|
||||
params["security"] = "reality"
|
||||
realitySetting, _ := stream["realitySettings"].(map[string]any)
|
||||
realitySettings, _ := searchKey(realitySetting, "settings")
|
||||
@@ -1356,10 +1462,33 @@ func applyShareRealityParams(stream map[string]any, params map[string]string) {
|
||||
params["pqv"] = pqv
|
||||
}
|
||||
}
|
||||
params["spx"] = "/" + random.Seq(15)
|
||||
seed := ""
|
||||
if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
|
||||
seed, _ = spxValue.(string)
|
||||
}
|
||||
params["spx"] = deriveSpiderX(seed, clientKey)
|
||||
}
|
||||
}
|
||||
|
||||
// subKey returns a stable per-client identity for deterministic derivations,
|
||||
// preferring the subscription id and falling back to the (unique) email.
|
||||
func subKey(c model.Client) string {
|
||||
if c.SubID != "" {
|
||||
return c.SubID
|
||||
}
|
||||
return c.Email
|
||||
}
|
||||
|
||||
// deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
|
||||
// deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
|
||||
func deriveSpiderX(seed, clientKey string) string {
|
||||
if seed == "" && clientKey == "" {
|
||||
return "/" + random.Seq(15)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(seed + "|" + clientKey))
|
||||
return "/" + hex.EncodeToString(sum[:])[:15]
|
||||
}
|
||||
|
||||
func buildVmessLink(obj map[string]any) string {
|
||||
jsonStr, _ := json.MarshalIndent(obj, "", " ")
|
||||
return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
|
||||
|
||||
@@ -69,19 +69,35 @@ func TestGetSubs_DuplicateSettingsClients_Deduped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMatchingClients_DedupsCaseInsensitiveEmail pins the dedup KEY, not just the count:
|
||||
// the two entries differ only by email case, so dropping strings.ToLower (or keying on
|
||||
// another field) yields two clients. The byte-identical dupes above can't catch that.
|
||||
// TestMatchingClients_DedupsCaseInsensitiveEmail pins the dedup KEY, not just the count.
|
||||
// clients.email is unique but case-sensitively so: two rows differing only by email case
|
||||
// can coexist (import drift), and dropping strings.ToLower (or keying on another field)
|
||||
// would emit both. The first row by id must win, matching the old settings-JSON order.
|
||||
func TestMatchingClients_DedupsCaseInsensitiveEmail(t *testing.T) {
|
||||
dbDir := t.TempDir()
|
||||
t.Setenv("XUI_DB_FOLDER", dbDir)
|
||||
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
|
||||
const subId = "s1"
|
||||
const uuid = "11111111-2222-4333-8444-555555555555"
|
||||
ib := &model.Inbound{
|
||||
Protocol: model.VLESS,
|
||||
Settings: `{"clients":[
|
||||
{"id":"` + uuid + `","email":"Dup@Example.com","subId":"` + subId + `","enable":true},
|
||||
{"id":"` + uuid + `","email":"dup@example.com","subId":"` + subId + `","enable":true}
|
||||
]}`,
|
||||
db := database.GetDB()
|
||||
ib := &model.Inbound{Protocol: model.VLESS, Enable: true, Port: 42002, Tag: "dedup-ci", Settings: `{"clients":[]}`}
|
||||
if err := db.Create(ib).Error; err != nil {
|
||||
t.Fatalf("seed inbound: %v", err)
|
||||
}
|
||||
for _, email := range []string{"Dup@Example.com", "dup@example.com"} {
|
||||
c := &model.ClientRecord{Email: email, SubID: subId, UUID: uuid, Enable: true}
|
||||
if err := db.Create(c).Error; err != nil {
|
||||
t.Fatalf("seed client %q: %v", email, err)
|
||||
}
|
||||
if err := db.Create(&model.ClientInbound{ClientId: c.Id, InboundId: ib.Id}).Error; err != nil {
|
||||
t.Fatalf("seed client_inbound %q: %v", email, err)
|
||||
}
|
||||
}
|
||||
|
||||
s := &SubService{}
|
||||
got := s.matchingClients(ib, subId)
|
||||
if len(got) != 1 {
|
||||
@@ -90,7 +106,7 @@ func TestMatchingClients_DedupsCaseInsensitiveEmail(t *testing.T) {
|
||||
if got[0].Email != "Dup@Example.com" {
|
||||
t.Fatalf("first occurrence must be kept, got %q", got[0].Email)
|
||||
}
|
||||
// A wrong subId must still be excluded (guards the subId filter at service.go:127).
|
||||
// A wrong subId must still be excluded (guards the SQL subId filter).
|
||||
if other := s.matchingClients(ib, "nope"); len(other) != 0 {
|
||||
t.Fatalf("non-matching subId must yield 0 clients, got %d", len(other))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package sub
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -52,10 +53,8 @@ func TestGenVlessLink_TLSParamsMapped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenVlessLink_RealityParamsMapped locks the reality field mapping
|
||||
// (applyShareRealityParams, service.go:1147). serverNames/shortIds are single-element
|
||||
// so random.Num is deterministic (index 0); spx is random so it is asserted by prefix.
|
||||
// Distinct pbk/sid values catch a pbk<->sid swap mutant.
|
||||
// Locks the reality field mapping of applyShareRealityParams; distinct pbk/sid
|
||||
// catch a swap mutant. spx is now a per-client derived value (#5718 / follow-up).
|
||||
func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
|
||||
stream := `{
|
||||
"network":"tcp","security":"reality",
|
||||
@@ -63,7 +62,7 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
|
||||
"realitySettings":{
|
||||
"serverNames":["reality.example.com"],
|
||||
"shortIds":["ab12cd"],
|
||||
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox"}
|
||||
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/mypath"}
|
||||
}
|
||||
}`
|
||||
s := &SubService{}
|
||||
@@ -75,7 +74,7 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
|
||||
"pbk=PBKvalue",
|
||||
"sid=ab12cd",
|
||||
"fp=firefox",
|
||||
"spx=%2F", // "/" + random.Seq(15), percent-encoded leading slash
|
||||
"spx=%2F",
|
||||
}
|
||||
for _, w := range wants {
|
||||
if !strings.Contains(link, w) {
|
||||
@@ -87,3 +86,93 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
|
||||
t.Fatalf("reality pbk/sid mapping crossed: %s", link)
|
||||
}
|
||||
}
|
||||
|
||||
// realityTwoClientInbound builds a reality VLESS inbound carrying two clients
|
||||
// with distinct subIds so the per-client spx derivation can be exercised.
|
||||
func realityTwoClientInbound() *model.Inbound {
|
||||
return &model.Inbound{
|
||||
Listen: "203.0.113.1",
|
||||
Port: 443,
|
||||
Protocol: model.VLESS,
|
||||
Remark: "sharelink",
|
||||
Settings: `{"clients":[
|
||||
{"id":"11111111-2222-4333-8444-555555555555","email":"alice","subId":"subAlice"},
|
||||
{"id":"22222222-3333-4444-8555-666666666666","email":"bob","subId":"subBob"}
|
||||
],"decryption":"none","encryption":"none"}`,
|
||||
StreamSettings: `{
|
||||
"network":"tcp","security":"reality",
|
||||
"tcpSettings":{"header":{"type":"none"}},
|
||||
"realitySettings":{
|
||||
"serverNames":["reality.example.com"],
|
||||
"shortIds":["ab12cd"],
|
||||
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/seed"}
|
||||
}
|
||||
}`,
|
||||
}
|
||||
}
|
||||
|
||||
func spxParam(t *testing.T, link string) string {
|
||||
t.Helper()
|
||||
u, err := url.Parse(link)
|
||||
if err != nil {
|
||||
t.Fatalf("parse link %q: %v", link, err)
|
||||
}
|
||||
spx := u.Query().Get("spx")
|
||||
if spx == "" || spx[0] != '/' {
|
||||
t.Fatalf("spx missing or not /-prefixed in %q", link)
|
||||
}
|
||||
return spx
|
||||
}
|
||||
|
||||
// spx must be stable for a given client across repeated exports (the #5718
|
||||
// complaint) yet differ between clients so the value can't be fingerprinted.
|
||||
func TestGenVlessLink_RealitySpiderXPerClientStable(t *testing.T) {
|
||||
s := &SubService{}
|
||||
inbound := realityTwoClientInbound()
|
||||
|
||||
aliceFirst := spxParam(t, s.genVlessLink(inbound, "alice"))
|
||||
aliceSecond := spxParam(t, s.genVlessLink(inbound, "alice"))
|
||||
bob := spxParam(t, s.genVlessLink(inbound, "bob"))
|
||||
|
||||
if aliceFirst != aliceSecond {
|
||||
t.Fatalf("spx not stable for the same client: %q vs %q", aliceFirst, aliceSecond)
|
||||
}
|
||||
if aliceFirst == bob {
|
||||
t.Fatalf("spx identical across clients (fingerprintable): %q", aliceFirst)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveSpiderX(t *testing.T) {
|
||||
if got := deriveSpiderX("seed", "clientA"); got != deriveSpiderX("seed", "clientA") {
|
||||
t.Fatalf("deriveSpiderX not deterministic: %q", got)
|
||||
}
|
||||
if deriveSpiderX("seed", "clientA") == deriveSpiderX("seed", "clientB") {
|
||||
t.Fatal("deriveSpiderX must differ per client")
|
||||
}
|
||||
if deriveSpiderX("seedA", "clientA") == deriveSpiderX("seedB", "clientA") {
|
||||
t.Fatal("rotating the seed must rotate a client's spx")
|
||||
}
|
||||
got := deriveSpiderX("seed", "clientA")
|
||||
if len(got) != 16 || got[0] != '/' {
|
||||
t.Fatalf("deriveSpiderX shape = %q, want /-prefixed 15-char path", got)
|
||||
}
|
||||
if fallback := deriveSpiderX("", ""); len(fallback) != 16 || fallback[0] != '/' {
|
||||
t.Fatalf("empty-input fallback = %q, want /-prefixed path", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
// Cross-language vectors shared with frontend/src/test/spider-x.test.ts: the
|
||||
// panel builds these links in TS, so both derivations must agree byte-for-byte.
|
||||
func TestDeriveSpiderXMatchesFrontendVectors(t *testing.T) {
|
||||
vectors := map[string]struct{ seed, clientKey, want string }{
|
||||
"seed and subId": {"/seed", "subAlice", "/c252fbc3ecd3e3c"},
|
||||
"seed only": {"/", "", "/d08ed99bd9afc60"},
|
||||
}
|
||||
for name, v := range vectors {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if got := deriveSpiderX(v.seed, v.clientKey); got != v.want {
|
||||
t.Fatalf("deriveSpiderX(%q, %q) = %q, want %q (must match frontend/src/lib/xray/spider-x.ts)", v.seed, v.clientKey, got, v.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package sub
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/op/go-logging"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
const scaleTargetSubId = "scale-target-sub"
|
||||
|
||||
// setupScaleSubDB mirrors the service package's scale gating: Postgres via
|
||||
// XUI_DB_TYPE/XUI_DB_DSN, SQLite via XUI_SCALE_TEST=1, skip otherwise.
|
||||
func setupScaleSubDB(t *testing.T) {
|
||||
t.Helper()
|
||||
xuilogger.InitLogger(logging.ERROR)
|
||||
|
||||
if os.Getenv("XUI_DB_TYPE") == "postgres" && strings.TrimSpace(os.Getenv("XUI_DB_DSN")) != "" {
|
||||
if err := database.InitDB(""); err != nil {
|
||||
t.Fatalf("InitDB(postgres): %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
return
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("XUI_SCALE_TEST"))) {
|
||||
case "1", "true", "yes":
|
||||
if err := database.InitDB(filepath.Join(t.TempDir(), "scale.db")); err != nil {
|
||||
t.Fatalf("InitDB(sqlite): %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
return
|
||||
}
|
||||
t.Skip("set XUI_SCALE_TEST=1 (sqlite) or XUI_DB_TYPE=postgres + XUI_DB_DSN (postgres) to run the scale benchmark")
|
||||
}
|
||||
|
||||
func scaleSubSizes(t *testing.T, def ...int) []int {
|
||||
t.Helper()
|
||||
raw := strings.TrimSpace(os.Getenv("XUI_SCALE_SIZES"))
|
||||
if raw == "" {
|
||||
return def
|
||||
}
|
||||
var out []int
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.Atoi(part)
|
||||
if err != nil || n <= 0 {
|
||||
t.Fatalf("XUI_SCALE_SIZES: invalid size %q", part)
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return def
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func resetScaleSubTables(t *testing.T, db *gorm.DB) {
|
||||
t.Helper()
|
||||
if config.GetDBKind() == "postgres" {
|
||||
if err := db.Exec("TRUNCATE TABLE inbounds, clients, client_inbounds, client_traffics RESTART IDENTITY CASCADE").Error; err != nil {
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
} else {
|
||||
for _, tbl := range []string{"inbounds", "clients", "client_inbounds", "client_traffics"} {
|
||||
if err := db.Exec("DELETE FROM " + tbl).Error; err != nil {
|
||||
t.Fatalf("delete %s: %v", tbl, err)
|
||||
}
|
||||
}
|
||||
db.Exec("DELETE FROM sqlite_sequence")
|
||||
}
|
||||
if err := db.Where("1 = 1").Delete(&model.ClientExternalLink{}).Error; err != nil {
|
||||
t.Fatalf("clear client_external_links: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// seedScaleSubDataset seeds one VLESS inbound holding n clients (the sub
|
||||
// server's worst case: matchingClients parses the whole settings blob and
|
||||
// getInboundsBySubId preloads every ClientStats row). Three clients share
|
||||
// scaleTargetSubId; everyone else gets a unique subId.
|
||||
func seedScaleSubDataset(t *testing.T, n int) {
|
||||
t.Helper()
|
||||
db := database.GetDB()
|
||||
resetScaleSubTables(t, db)
|
||||
|
||||
clients := make([]model.Client, n)
|
||||
exp := time.Now().AddDate(1, 0, 0).UnixMilli()
|
||||
targets := map[int]bool{n / 4: true, n / 2: true, 3 * n / 4: true}
|
||||
for i := range n {
|
||||
subId := fmt.Sprintf("sub-%07d", i)
|
||||
if targets[i] {
|
||||
subId = scaleTargetSubId
|
||||
}
|
||||
clients[i] = model.Client{
|
||||
ID: uuid.NewString(),
|
||||
Email: fmt.Sprintf("user-%07d@subscale", i),
|
||||
SubID: subId,
|
||||
Enable: true,
|
||||
ExpiryTime: exp,
|
||||
TotalGB: 100 << 30,
|
||||
}
|
||||
}
|
||||
|
||||
settingsMap := map[string]any{"clients": clients, "decryption": "none"}
|
||||
settings, err := json.Marshal(settingsMap)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal settings: %v", err)
|
||||
}
|
||||
|
||||
tx := db.Begin()
|
||||
if tx.Error != nil {
|
||||
t.Fatalf("begin seed tx: %v", tx.Error)
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if !committed {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
ib := &model.Inbound{
|
||||
UserId: 1,
|
||||
Tag: fmt.Sprintf("subscale-%d", n),
|
||||
Remark: "subscale",
|
||||
Enable: true,
|
||||
Listen: "203.0.113.1",
|
||||
Port: 443,
|
||||
Protocol: model.VLESS,
|
||||
Settings: string(settings),
|
||||
StreamSettings: `{"network":"tcp","security":"none"}`,
|
||||
}
|
||||
if err := tx.Create(ib).Error; err != nil {
|
||||
t.Fatalf("seed inbound: %v", err)
|
||||
}
|
||||
|
||||
records := make([]*model.ClientRecord, n)
|
||||
for i := range clients {
|
||||
records[i] = clients[i].ToRecord()
|
||||
}
|
||||
if err := tx.CreateInBatches(records, 500).Error; err != nil {
|
||||
t.Fatalf("seed clients: %v", err)
|
||||
}
|
||||
links := make([]model.ClientInbound, n)
|
||||
for i := range records {
|
||||
links[i] = model.ClientInbound{ClientId: records[i].Id, InboundId: ib.Id}
|
||||
}
|
||||
if err := tx.CreateInBatches(links, 1000).Error; err != nil {
|
||||
t.Fatalf("seed client_inbounds: %v", err)
|
||||
}
|
||||
traffics := make([]xray.ClientTraffic, n)
|
||||
for i := range clients {
|
||||
traffics[i] = xray.ClientTraffic{
|
||||
InboundId: ib.Id,
|
||||
Email: clients[i].Email,
|
||||
Enable: true,
|
||||
Total: clients[i].TotalGB,
|
||||
ExpiryTime: clients[i].ExpiryTime,
|
||||
}
|
||||
}
|
||||
if err := tx.CreateInBatches(traffics, 1000).Error; err != nil {
|
||||
t.Fatalf("seed client_traffics: %v", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
t.Fatalf("commit seed tx: %v", err)
|
||||
}
|
||||
committed = true
|
||||
db.Exec("ANALYZE")
|
||||
}
|
||||
|
||||
// TestGetSubsScale measures one subscription fetch (raw and JSON format) for a
|
||||
// 3-client subId living inside an n-client inbound, plus a subId miss — the
|
||||
// per-request cost every subscriber pays.
|
||||
func TestGetSubsScale(t *testing.T) {
|
||||
for _, n := range scaleSubSizes(t, 10000, 100000) {
|
||||
t.Run(fmt.Sprintf("N=%d", n), func(t *testing.T) {
|
||||
setupScaleSubDB(t)
|
||||
seedScaleSubDataset(t, n)
|
||||
|
||||
svc := &SubService{}
|
||||
const reps = 5
|
||||
start := time.Now()
|
||||
var links []string
|
||||
for range reps {
|
||||
var err error
|
||||
links, _, _, _, err = svc.GetSubs(scaleTargetSubId, "sub.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("GetSubs: %v", err)
|
||||
}
|
||||
}
|
||||
rawDur := time.Since(start) / reps
|
||||
if len(links) != 3 {
|
||||
t.Fatalf("GetSubs links = %d, want 3", len(links))
|
||||
}
|
||||
|
||||
jsonSvc := NewSubJsonService("", "", "", &SubService{})
|
||||
start = time.Now()
|
||||
for range reps {
|
||||
body, _, err := jsonSvc.GetJson(scaleTargetSubId, "sub.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("GetJson: %v", err)
|
||||
}
|
||||
if body == "" {
|
||||
t.Fatal("GetJson returned empty body")
|
||||
}
|
||||
}
|
||||
jsonDur := time.Since(start) / reps
|
||||
|
||||
start = time.Now()
|
||||
for range reps {
|
||||
missLinks, _, _, _, err := svc.GetSubs("no-such-sub", "sub.example.com")
|
||||
if err != nil {
|
||||
t.Fatalf("GetSubs miss: %v", err)
|
||||
}
|
||||
if len(missLinks) != 0 {
|
||||
t.Fatalf("GetSubs miss links = %d, want 0", len(missLinks))
|
||||
}
|
||||
}
|
||||
missDur := time.Since(start) / reps
|
||||
|
||||
t.Logf("N=%-7d raw=%-10v json=%-10v miss=%v",
|
||||
n, rawDur.Round(time.Millisecond), jsonDur.Round(time.Millisecond), missDur.Round(time.Millisecond))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package common
|
||||
|
||||
import "strings"
|
||||
|
||||
// EnsureURLScheme prepends https:// to a URL that carries no scheme, so
|
||||
// subscription apps and browsers don't resolve it relative to the panel's own
|
||||
// domain (e.g. "t.me/support" turning into "https://panel.example/t.me/support").
|
||||
// Values with an explicit scheme (https://, tg://, mailto:, tel:) and empty
|
||||
// strings pass through untouched.
|
||||
func EnsureURLScheme(raw string) string {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return ""
|
||||
}
|
||||
if strings.Contains(trimmed, "://") ||
|
||||
strings.HasPrefix(trimmed, "mailto:") ||
|
||||
strings.HasPrefix(trimmed, "tel:") {
|
||||
return trimmed
|
||||
}
|
||||
return "https://" + trimmed
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEnsureURLScheme(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"empty", "", ""},
|
||||
{"whitespace only", " ", ""},
|
||||
{"bare telegram handle", "t.me/xui_support", "https://t.me/xui_support"},
|
||||
{"bare domain with path", "example.com/help", "https://example.com/help"},
|
||||
{"already https", "https://t.me/xui_support", "https://t.me/xui_support"},
|
||||
{"already http", "http://example.com", "http://example.com"},
|
||||
{"telegram deep link", "tg://resolve?domain=xui_support", "tg://resolve?domain=xui_support"},
|
||||
{"mailto", "mailto:support@example.com", "mailto:support@example.com"},
|
||||
{"tel", "tel:+1234567890", "tel:+1234567890"},
|
||||
{"trims whitespace", " t.me/xui_support ", "https://t.me/xui_support"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := EnsureURLScheme(tt.in); got != tt.want {
|
||||
t.Errorf("EnsureURLScheme(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Outbound is the minimal shape we emit for each parsed link.
|
||||
@@ -657,11 +659,91 @@ func applyFinalMask(stream map[string]any, p url.Values) {
|
||||
if fm := p.Get("fm"); fm != "" {
|
||||
var parsed any
|
||||
if json.Unmarshal([]byte(fm), &parsed) == nil {
|
||||
sanitizeFinalMaskQuicParams(parsed)
|
||||
stream["finalmask"] = parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sanitizeFinalMaskQuicParams coerces the strictly numeric quicParams fields
|
||||
// of a finalmask blob taken verbatim from a share link's fm= parameter.
|
||||
// Xray-core rejects the whole config at startup when e.g. keepAlivePeriod
|
||||
// arrives as a duration string like "10s" or an out-of-range integer, so
|
||||
// numeric strings are parsed, duration strings are converted to whole
|
||||
// seconds, the ranged fields are clamped to what xray accepts, and anything
|
||||
// non-finite, negative, absurdly large, or unparseable is dropped so a bad
|
||||
// value falls back to xray's default instead of killing the config (#5783).
|
||||
func sanitizeFinalMaskQuicParams(parsed any) {
|
||||
fm, ok := parsed.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
qp, ok := fm["quicParams"].(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
numericKeys := []string{
|
||||
"initStreamReceiveWindow", "maxStreamReceiveWindow",
|
||||
"initConnectionReceiveWindow", "maxConnectionReceiveWindow",
|
||||
"maxIdleTimeout", "keepAlivePeriod", "maxIncomingStreams",
|
||||
}
|
||||
for _, key := range numericKeys {
|
||||
raw, exists := qp[key]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
n, ok := coerceQuicNumeric(raw)
|
||||
if ok {
|
||||
n, ok = clampQuicNumeric(key, n)
|
||||
}
|
||||
if !ok {
|
||||
delete(qp, key)
|
||||
continue
|
||||
}
|
||||
qp[key] = int64(n)
|
||||
}
|
||||
}
|
||||
|
||||
func coerceQuicNumeric(raw any) (float64, bool) {
|
||||
switch v := raw.(type) {
|
||||
case float64:
|
||||
return math.Trunc(v), true
|
||||
case string:
|
||||
if n, err := strconv.ParseFloat(v, 64); err == nil && !math.IsInf(n, 0) && !math.IsNaN(n) {
|
||||
return math.Trunc(n), true
|
||||
}
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
return math.Trunc(d.Seconds()), true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// clampQuicNumeric enforces xray-core's QuicParamsConfig validation so a
|
||||
// coerced value cannot still fail the config load: keepAlivePeriod is 0 or
|
||||
// 2-60, maxIdleTimeout is 0 or 4-120, maxIncomingStreams is 0 or >= 8.
|
||||
// quicNumericMax keeps values in plain-integer JSON territory and far below
|
||||
// the uint64 window fields' range.
|
||||
const quicNumericMax = float64(1e15)
|
||||
|
||||
func clampQuicNumeric(key string, n float64) (float64, bool) {
|
||||
if n < 0 || n > quicNumericMax {
|
||||
return 0, false
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, true
|
||||
}
|
||||
switch key {
|
||||
case "keepAlivePeriod":
|
||||
return math.Min(math.Max(n, 2), 60), true
|
||||
case "maxIdleTimeout":
|
||||
return math.Min(math.Max(n, 4), 120), true
|
||||
case "maxIncomingStreams":
|
||||
return math.Max(n, 8), true
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
func firstNonEmpty(a, b string) string {
|
||||
if a != "" {
|
||||
return a
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package link
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -35,6 +36,83 @@ func TestParseVlessLink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseVlessLink_FinalMaskQuicParamsSanitized(t *testing.T) {
|
||||
fm := url.QueryEscape(`{"mask":"dtls","quicParams":{"keepAlivePeriod":"10s","maxIdleTimeout":"30","initStreamReceiveWindow":524288,"maxIncomingStreams":true,"brutalUp":"100 mbps"}}`)
|
||||
res, err := ParseLink("vless://uuid@1.2.3.4:443?type=tcp&security=none&fm=" + fm + "#node1")
|
||||
if err != nil {
|
||||
t.Fatalf("parse vless with fm: %v", err)
|
||||
}
|
||||
stream, ok := res.Outbound["streamSettings"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing streamSettings: %v", res.Outbound)
|
||||
}
|
||||
finalmask, ok := stream["finalmask"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing finalmask: %v", stream)
|
||||
}
|
||||
if finalmask["mask"] != "dtls" {
|
||||
t.Errorf("mask changed: %v", finalmask["mask"])
|
||||
}
|
||||
qp, ok := finalmask["quicParams"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing quicParams: %v", finalmask)
|
||||
}
|
||||
if got := qp["keepAlivePeriod"]; got != int64(10) {
|
||||
t.Errorf("keepAlivePeriod: expected 10, got %v (%T)", got, got)
|
||||
}
|
||||
if got := qp["maxIdleTimeout"]; got != int64(30) {
|
||||
t.Errorf("maxIdleTimeout: expected 30, got %v (%T)", got, got)
|
||||
}
|
||||
if got := qp["initStreamReceiveWindow"]; got != int64(524288) {
|
||||
t.Errorf("initStreamReceiveWindow: expected 524288, got %v (%T)", got, got)
|
||||
}
|
||||
if _, exists := qp["maxIncomingStreams"]; exists {
|
||||
t.Errorf("maxIncomingStreams should be dropped, got %v", qp["maxIncomingStreams"])
|
||||
}
|
||||
if got := qp["brutalUp"]; got != "100 mbps" {
|
||||
t.Errorf("brutalUp should stay a string, got %v (%T)", got, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeFinalMaskQuicParams_ClampsAndRejects(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
key string
|
||||
in any
|
||||
want any
|
||||
}{
|
||||
{"infinite string dropped", "keepAlivePeriod", "inf", nil},
|
||||
{"nan string dropped", "keepAlivePeriod", "NaN", nil},
|
||||
{"negative dropped", "maxStreamReceiveWindow", float64(-5), nil},
|
||||
{"negative duration dropped", "keepAlivePeriod", "-10s", nil},
|
||||
{"absurd magnitude dropped", "initConnectionReceiveWindow", float64(1e30), nil},
|
||||
{"keepAlive clamped up", "keepAlivePeriod", "1s", int64(2)},
|
||||
{"keepAlive clamped down", "keepAlivePeriod", "90s", int64(60)},
|
||||
{"idle clamped up", "maxIdleTimeout", float64(1), int64(4)},
|
||||
{"idle clamped down", "maxIdleTimeout", "10m", int64(120)},
|
||||
{"streams clamped up", "maxIncomingStreams", float64(4), int64(8)},
|
||||
{"zero means unset and survives", "maxIdleTimeout", float64(0), int64(0)},
|
||||
{"window passes through", "initStreamReceiveWindow", float64(524288), int64(524288)},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
parsed := map[string]any{"quicParams": map[string]any{c.key: c.in}}
|
||||
sanitizeFinalMaskQuicParams(parsed)
|
||||
qp := parsed["quicParams"].(map[string]any)
|
||||
got, exists := qp[c.key]
|
||||
if c.want == nil {
|
||||
if exists {
|
||||
t.Fatalf("%s: expected key dropped, got %v (%T)", c.key, got, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !exists || got != c.want {
|
||||
t.Fatalf("%s: expected %v, got %v (%T)", c.key, c.want, got, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSubscriptionBody_Base64(t *testing.T) {
|
||||
// base64 of the two joined links:
|
||||
// vless://u@h:443?type=tcp#A\nvless://u2@h2:443?type=tcp#B
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// newPanelUpdateTestEngine registers only updatePanel/getUpdateStatus directly
|
||||
// on the controller's zero value, bypassing NewServerController's cron/metrics
|
||||
// setup (unrelated to these two handlers, and unnecessary weight for a unit
|
||||
// test). Callers must set up a DB first (newHostTestDB(t)) since StartUpdate
|
||||
// reads the dev-channel setting before doing anything else.
|
||||
func newPanelUpdateTestEngine() *gin.Engine {
|
||||
a := &ServerController{}
|
||||
engine := gin.New()
|
||||
engine.GET("/panel/api/server/getUpdateStatus", a.getUpdateStatus)
|
||||
engine.POST("/panel/api/server/updatePanel", a.updatePanel)
|
||||
return engine
|
||||
}
|
||||
|
||||
func doPanelUpdateReq(t *testing.T, engine *gin.Engine, method, path string) hostEnvelope {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%s %s: status %d, body=%s", method, path, w.Code, w.Body.String())
|
||||
}
|
||||
var env hostEnvelope
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
|
||||
t.Fatalf("%s %s: decode envelope: %v body=%s", method, path, err, w.Body.String())
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// TestGetUpdateStatus_NoStatusFileYet exercises the read-only status endpoint
|
||||
// with no prior update having run: it must report "pending" (not an error),
|
||||
// since a missing status file is an expected, ordinary state, not a failure.
|
||||
func TestGetUpdateStatus_NoStatusFileYet(t *testing.T) {
|
||||
newHostTestDB(t)
|
||||
engine := newPanelUpdateTestEngine()
|
||||
|
||||
env := doPanelUpdateReq(t, engine, http.MethodGet, "/panel/api/server/getUpdateStatus")
|
||||
if !env.Success {
|
||||
t.Fatalf("getUpdateStatus should always report success=true (it's a best-effort read): msg=%s", env.Msg)
|
||||
}
|
||||
var status struct {
|
||||
RunID string `json:"runId"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Obj, &status); err != nil {
|
||||
t.Fatalf("decode status: %v", err)
|
||||
}
|
||||
if status.State != "pending" {
|
||||
t.Fatalf("State = %q, want %q", status.State, "pending")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetUpdateStatus_RunIdIsAlwaysAString is the regression test for the
|
||||
// precision bug found in review: RunID is a 19-digit UnixNano timestamp, so
|
||||
// it must round-trip over the wire as a JSON string, never a bare number -- a
|
||||
// bare number would silently lose precision in JavaScript past
|
||||
// Number.MAX_SAFE_INTEGER, breaking every future runId comparison on the
|
||||
// frontend. Decoding into a Go string field below only succeeds if the wire
|
||||
// value is actually a JSON string; a bare number there would fail to decode,
|
||||
// so this test doubles as the wire-format check.
|
||||
func TestGetUpdateStatus_RunIdIsAlwaysAString(t *testing.T) {
|
||||
newHostTestDB(t)
|
||||
engine := newPanelUpdateTestEngine()
|
||||
|
||||
statusPath := config.GetUpdateStatusFilePath()
|
||||
body := `{"runId":"1735689600123456789","state":"success","exitCode":0,"finishedAt":1735689612}`
|
||||
if err := os.WriteFile(statusPath, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
env := doPanelUpdateReq(t, engine, http.MethodGet, "/panel/api/server/getUpdateStatus")
|
||||
var status struct {
|
||||
RunID string `json:"runId"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
if err := json.Unmarshal(env.Obj, &status); err != nil {
|
||||
t.Fatalf("decode status (would fail here if runId were a bare JSON number instead of a string): %v, body=%s", err, env.Obj)
|
||||
}
|
||||
if status.RunID != "1735689600123456789" {
|
||||
t.Fatalf("RunID = %q, want %q", status.RunID, "1735689600123456789")
|
||||
}
|
||||
if status.State != "success" {
|
||||
t.Fatalf("State = %q, want %q", status.State, "success")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdatePanel_UnsupportedPlatformReturnsNoRunId covers the one path of
|
||||
// updatePanel that's safe to exercise in an automated test on any OS/CI
|
||||
// runner: the runtime.GOOS != "linux" guard. Actually invoking StartUpdate's
|
||||
// launch logic on Linux would make a real network call and could launch a
|
||||
// real update.sh process, so that path is deliberately not covered here --
|
||||
// see the PR description for why.
|
||||
func TestUpdatePanel_UnsupportedPlatformReturnsNoRunId(t *testing.T) {
|
||||
if runtime.GOOS == "linux" {
|
||||
t.Skip("this test only exercises the non-Linux guard path; on Linux, updatePanel would attempt a real download/exec")
|
||||
}
|
||||
newHostTestDB(t)
|
||||
engine := newPanelUpdateTestEngine()
|
||||
|
||||
env := doPanelUpdateReq(t, engine, http.MethodPost, "/panel/api/server/updatePanel")
|
||||
if env.Success {
|
||||
t.Fatal("updatePanel on an unsupported platform: success = true, want false")
|
||||
}
|
||||
if len(env.Obj) != 0 && string(env.Obj) != "null" {
|
||||
t.Fatalf("updatePanel error response must not carry an obj/runId: got %s", env.Obj)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdatePanel_InvalidDevValueRejectedBeforeLaunch covers the one branch of
|
||||
// updatePanel that's both untested and safe to exercise on any OS/CI runner:
|
||||
// an unparseable "dev" form value is rejected by strconv.ParseBool before
|
||||
// StartUpdateChannel (and therefore any real exec/network call) is ever
|
||||
// reached, on Linux or otherwise.
|
||||
func TestUpdatePanel_InvalidDevValueRejectedBeforeLaunch(t *testing.T) {
|
||||
newHostTestDB(t)
|
||||
engine := newPanelUpdateTestEngine()
|
||||
|
||||
form := url.Values{"dev": {"notabool"}}
|
||||
req := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status %d, body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var env hostEnvelope
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode envelope: %v body=%s", err, w.Body.String())
|
||||
}
|
||||
if env.Success {
|
||||
t.Fatal("updatePanel with dev=notabool: success = true, want false")
|
||||
}
|
||||
if len(env.Obj) != 0 && string(env.Obj) != "null" {
|
||||
t.Fatalf("updatePanel error response must not carry an obj/runId: got %s", env.Obj)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user