mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-18 19:15:03 +03:00
Compare commits
183 Commits
v3.4.0
...
42690e1b8c
| Author | SHA1 | Date | |
|---|---|---|---|
| 42690e1b8c | |||
| f431e9cc03 | |||
| f4199353da | |||
| 5c5a509605 | |||
| a067f817ae | |||
| 7c183dbd97 | |||
| 567a4ac4fe | |||
| 7db92d6318 | |||
| e424cc0f4d | |||
| 57300f44bd | |||
| 328d920e98 | |||
| 61e12e4c29 | |||
| 8ee79cf447 | |||
| bc309ed9f8 | |||
| 15faec6258 | |||
| 9b91f0f42e | |||
| 2c49dbf54e | |||
| cc3303dd8c | |||
| 52d4af71bc | |||
| 7cb2adf429 | |||
| 6e75938c61 | |||
| ad7a0f8164 | |||
| 406ce54fb2 | |||
| 43500a5470 | |||
| 659f0f404c | |||
| 6214ff4edc | |||
| 84b6423020 | |||
| 27fd19895a | |||
| a1ca43d869 | |||
| 977fe4b4ea | |||
| d8b9f535ff | |||
| d97bd8643e | |||
| 5e9606aa4d | |||
| f36f481e02 | |||
| de70ecb026 | |||
| ed66209e38 | |||
| 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 | |||
| f3a57d4c57 | |||
| 86813758cc | |||
| 8332ba67ae | |||
| d8221a8153 | |||
| 789e92cddc | |||
| 7a5d6da28c | |||
| 71aca2018a | |||
| 6c71b725da | |||
| a329882e0e | |||
| 60c54827aa | |||
| aef35ee0de | |||
| 2b10808fbd | |||
| 25a86b9ee2 | |||
| 51ffba5961 | |||
| 5713c09980 | |||
| 7f8cbf4c4b | |||
| bbfbd7eba6 | |||
| 79069d2b64 | |||
| 9c8cd08f90 | |||
| 33aada0c7c | |||
| e44075a6e0 | |||
| 56b0be0b6a | |||
| 9b8a0c9b17 | |||
| d1c0d77023 | |||
| 63fca9ef88 | |||
| 2e851978e6 | |||
| fa1a19c03c | |||
| 7efa0d9ddd | |||
| d12b186a69 | |||
| 39eb5baf42 | |||
| 876d55f274 | |||
| 1bad2fcba1 | |||
| 4c177f0cf1 | |||
| 797b08cd07 | |||
| 439245d42b | |||
| 535b89a352 | |||
| 7a2179535a | |||
| 6964d84742 | |||
| 451263f1db | |||
| 8e4c368200 | |||
| 522b1b64b0 | |||
| b1fb39c486 | |||
| 9381fa284b | |||
| 30796dc2ce | |||
| dc6d13b58f | |||
| e27f2490b2 | |||
| df0e52cda8 | |||
| 1d69508263 | |||
| 8f65aa7e4b | |||
| 293c1e44dc | |||
| 69ad8b76e1 | |||
| b32837e523 | |||
| 9dec15bd4b | |||
| e64e998194 | |||
| a4be5a0deb | |||
| e4b881e58a | |||
| 2adb59bd64 | |||
| bcd1358032 | |||
| e8878b71a4 | |||
| 11c5b53fac | |||
| 896016f7f6 | |||
| e2d25d0ac7 | |||
| fe025e8af3 | |||
| 3ba43bd86d | |||
| ae9bbdf267 | |||
| 2830f97f50 | |||
| 1d1128cf94 | |||
| aad2b3eb1e | |||
| 93ff60e568 | |||
| 23e73cd4a3 | |||
| b0c1156dd6 | |||
| 5dbd5b1d12 | |||
| bd60e770f4 | |||
| a5e865c109 | |||
| 82600936d6 | |||
| 14de0557f9 | |||
| c93beef267 | |||
| 48c2fb27b8 |
+172
-1
@@ -1,6 +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_DEBUG=true
|
||||||
XUI_DB_FOLDER=x-ui
|
XUI_DB_FOLDER=x-ui
|
||||||
XUI_LOG_FOLDER=x-ui
|
XUI_LOG_FOLDER=x-ui
|
||||||
XUI_BIN_FOLDER=x-ui
|
XUI_BIN_FOLDER=x-ui
|
||||||
XUI_INIT_WEB_BASE_PATH=/
|
XUI_INIT_WEB_BASE_PATH=/
|
||||||
# XUI_PORT=8080
|
|
||||||
|
# ==============================================================================
|
||||||
|
# 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
|
||||||
|
|||||||
+1
-7
@@ -1,12 +1,6 @@
|
|||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
DockerInit.sh text eol=lf
|
|
||||||
DockerEntrypoint.sh text eol=lf
|
|
||||||
frontend/src/generated/** text eol=lf
|
frontend/src/generated/** text eol=lf
|
||||||
frontend/public/openapi.json text eol=lf
|
frontend/public/openapi.json text eol=lf
|
||||||
frontend/src/test/__snapshots__/** text eol=lf
|
frontend/src/test/__snapshots__/** text eol=lf
|
||||||
|
*.go text eol=lf
|
||||||
# Cloud-image deploy assets are consumed on Linux — force LF regardless of host.
|
|
||||||
*.service text eol=lf
|
|
||||||
deploy/**/*.service text eol=lf
|
|
||||||
deploy/**/*.hcl text eol=lf
|
|
||||||
deploy/**/*.yaml text eol=lf
|
deploy/**/*.yaml text eol=lf
|
||||||
@@ -37,6 +37,39 @@ jobs:
|
|||||||
go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt
|
go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt
|
||||||
go test -shuffle=on -count=1 $(cat /tmp/go-packages.txt)
|
go test -shuffle=on -count=1 $(cat /tmp/go-packages.txt)
|
||||||
|
|
||||||
|
postgres-durable-first:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
POSTGRES_DB: xui_durable
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U postgres -d xui_durable"
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
- uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
- name: Stub internal/web/dist for go:embed
|
||||||
|
run: mkdir -p internal/web/dist && touch internal/web/dist/.gitkeep
|
||||||
|
- name: PostgreSQL durable-first tests
|
||||||
|
run: |
|
||||||
|
set -o pipefail
|
||||||
|
XUI_DB_TYPE=postgres XUI_DB_DSN="host=127.0.0.1 port=5432 user=postgres password=postgres dbname=xui_durable sslmode=disable" \
|
||||||
|
go test ./internal/web/service -run 'PostgresCommitFailure' -count=1 -v | tee /tmp/postgres-durable-first.log
|
||||||
|
if grep -q -- '--- SKIP' /tmp/postgres-durable-first.log; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
codegen:
|
codegen:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -102,6 +135,21 @@ jobs:
|
|||||||
go test -run '^$' -fuzz 'FuzzParseLink$' -fuzztime=30s ./internal/util/link/
|
go test -run '^$' -fuzz 'FuzzParseLink$' -fuzztime=30s ./internal/util/link/
|
||||||
go test -run '^$' -fuzz 'FuzzDecodeCertPin$' -fuzztime=30s ./internal/web/runtime/
|
go test -run '^$' -fuzz 'FuzzDecodeCertPin$' -fuzztime=30s ./internal/web/runtime/
|
||||||
|
|
||||||
|
golangci:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
- uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: true
|
||||||
|
- name: Stub internal/web/dist for go:embed
|
||||||
|
run: mkdir -p internal/web/dist && touch internal/web/dist/.gitkeep
|
||||||
|
- name: golangci-lint
|
||||||
|
uses: golangci/golangci-lint-action@v9
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -30,7 +30,8 @@ jobs:
|
|||||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||||
allowed_non_write_users: "*"
|
allowed_non_write_users: "*"
|
||||||
claude_args: |
|
claude_args: |
|
||||||
--model claude-sonnet-4-6
|
--model claude-sonnet-5
|
||||||
|
--effort xhigh
|
||||||
--max-turns 300
|
--max-turns 300
|
||||||
--allowedTools "Bash(gh:*),Read,Glob,Grep"
|
--allowedTools "Bash(gh:*),Read,Glob,Grep"
|
||||||
prompt: |
|
prompt: |
|
||||||
@@ -282,7 +283,8 @@ jobs:
|
|||||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||||
allowed_non_write_users: "*"
|
allowed_non_write_users: "*"
|
||||||
claude_args: |
|
claude_args: |
|
||||||
--model claude-opus-4-8
|
--model claude-sonnet-5
|
||||||
|
--effort max
|
||||||
--max-turns 250
|
--max-turns 250
|
||||||
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep"
|
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep"
|
||||||
prompt: |
|
prompt: |
|
||||||
@@ -500,7 +502,8 @@ jobs:
|
|||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||||
claude_args: |
|
claude_args: |
|
||||||
--model claude-opus-4-8
|
--model claude-sonnet-5
|
||||||
|
--effort max
|
||||||
--max-turns 250
|
--max-turns 250
|
||||||
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep,Edit,Write"
|
--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.
|
--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.
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
name: Docs CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths:
|
||||||
|
- 'docs/**'
|
||||||
|
- '.github/workflows/docs-ci.yml'
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- 'docs/**'
|
||||||
|
- '.github/workflows/docs-ci.yml'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: docs
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- uses: pnpm/action-setup@v6
|
||||||
|
with:
|
||||||
|
version: 11
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: pnpm
|
||||||
|
cache-dependency-path: docs/pnpm-lock.yaml
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm typecheck
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: pnpm lint
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: pnpm test
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: pnpm build
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
name: Docs Deploy (GitHub Pages)
|
||||||
|
|
||||||
|
# Static-export deploy of docs/ to GitHub Pages. Pages must be enabled in repo
|
||||||
|
# settings (Source: GitHub Actions) and the docs.sanaei.dev custom domain
|
||||||
|
# attached to this repository. The site URL defaults to the production domain in
|
||||||
|
# docs/lib/shared.ts, so NEXT_PUBLIC_SITE_URL is optional.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths:
|
||||||
|
- 'docs/**'
|
||||||
|
- '.github/workflows/docs-deploy.yml'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: pages
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: docs
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
- uses: pnpm/action-setup@v6
|
||||||
|
with:
|
||||||
|
version: 11
|
||||||
|
- uses: actions/setup-node@v6
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: pnpm
|
||||||
|
cache-dependency-path: docs/pnpm-lock.yaml
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
- name: Build (static export)
|
||||||
|
env:
|
||||||
|
DEPLOY_TARGET: static
|
||||||
|
NEXT_PUBLIC_SITE_URL: ${{ vars.NEXT_PUBLIC_SITE_URL }}
|
||||||
|
run: pnpm build
|
||||||
|
- name: Mirror default locale (en) to the site root
|
||||||
|
# hideLocale makes most English links unprefixed (/, /docs/...), but the
|
||||||
|
# language switcher still targets /en/... . The export emits pages only
|
||||||
|
# under /en/, and there is no i18n middleware on a static host — so copy
|
||||||
|
# the English build to the root (data files included) while KEEPING /en/
|
||||||
|
# in place. That way both /docs/... and /en/docs/... resolve. Other
|
||||||
|
# locales stay under /fa, /ru, /zh.
|
||||||
|
run: cp -a out/en/. out/
|
||||||
|
- uses: actions/upload-pages-artifact@v5
|
||||||
|
with:
|
||||||
|
path: docs/out
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
needs: build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
steps:
|
||||||
|
- id: deployment
|
||||||
|
uses: actions/deploy-pages@v5
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
name: Build Cloud Images
|
|
||||||
|
|
||||||
# Build golden cloud images from a published release, for amd64 and arm64:
|
|
||||||
# * qemu -> qcow2 attached to the GitHub release (always)
|
|
||||||
# * amazon-ebs -> AWS AMI (only when AWS credentials are configured)
|
|
||||||
#
|
|
||||||
# Images contain NO database and NO baked credentials; first boot generates
|
|
||||||
# unique per-instance credentials (see deploy/firstboot + deploy/packer).
|
|
||||||
|
|
||||||
on:
|
|
||||||
release:
|
|
||||||
types: [published]
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
tag:
|
|
||||||
description: "Release tag to build images for (e.g. v3.3.1)"
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: image-${{ github.event.release.tag_name || inputs.tag }}
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
# Resolve the tag and wait until BOTH arch tarballs are actually published
|
|
||||||
# (the release matrix uploads assets one by one, so 'published' can fire
|
|
||||||
# before the tarballs exist).
|
|
||||||
setup:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
tag: ${{ steps.resolve.outputs.tag }}
|
|
||||||
steps:
|
|
||||||
- name: Resolve tag
|
|
||||||
id: resolve
|
|
||||||
run: |
|
|
||||||
if [ "${{ github.event_name }}" = "release" ]; then
|
|
||||||
TAG="${{ github.event.release.tag_name }}"
|
|
||||||
else
|
|
||||||
TAG="${{ inputs.tag }}"
|
|
||||||
fi
|
|
||||||
[ -n "$TAG" ] || { echo "::error::no tag resolved"; exit 1; }
|
|
||||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Wait for released binary assets (amd64 + arm64)
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
TAG: ${{ steps.resolve.outputs.tag }}
|
|
||||||
run: |
|
|
||||||
want="x-ui-linux-amd64.tar.gz x-ui-linux-arm64.tar.gz"
|
|
||||||
for i in $(seq 1 30); do
|
|
||||||
names=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets -q '.assets[].name')
|
|
||||||
missing=""
|
|
||||||
for w in $want; do
|
|
||||||
echo "$names" | grep -qx "$w" || missing="$missing $w"
|
|
||||||
done
|
|
||||||
if [ -z "$missing" ]; then
|
|
||||||
echo "All assets present on $TAG"
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
echo "Waiting for$missing on $TAG ($i/30)..."
|
|
||||||
sleep 20
|
|
||||||
done
|
|
||||||
echo "::error::missing release assets on $TAG after 10 minutes:$missing"
|
|
||||||
exit 1
|
|
||||||
|
|
||||||
# Gate the AWS AMI build so forks without secrets skip it cleanly
|
|
||||||
# (secrets cannot be referenced directly in job-level `if`).
|
|
||||||
check-aws:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
enabled: ${{ steps.c.outputs.enabled }}
|
|
||||||
use_oidc: ${{ steps.c.outputs.use_oidc }}
|
|
||||||
steps:
|
|
||||||
- id: c
|
|
||||||
env:
|
|
||||||
ROLE: ${{ secrets.AWS_ROLE_ARN }}
|
|
||||||
KEY: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
|
||||||
run: |
|
|
||||||
if [ -n "$ROLE" ]; then
|
|
||||||
echo "enabled=true" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "use_oidc=true" >> "$GITHUB_OUTPUT"
|
|
||||||
elif [ -n "$KEY" ]; then
|
|
||||||
echo "enabled=true" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "use_oidc=false" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "enabled=false" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "use_oidc=false" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "::notice::No AWS credentials configured; skipping the AMI build."
|
|
||||||
fi
|
|
||||||
|
|
||||||
qemu-image:
|
|
||||||
needs: setup
|
|
||||||
timeout-minutes: 90
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- arch: amd64
|
|
||||||
runner: ubuntu-latest
|
|
||||||
qemu_pkgs: qemu-system-x86 qemu-utils
|
|
||||||
- arch: arm64
|
|
||||||
runner: ubuntu-24.04-arm
|
|
||||||
qemu_pkgs: qemu-system-arm qemu-efi-aarch64 qemu-utils
|
|
||||||
runs-on: ${{ matrix.runner }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Install QEMU
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y --no-install-recommends ${{ matrix.qemu_pkgs }}
|
|
||||||
|
|
||||||
- name: Setup Packer
|
|
||||||
uses: hashicorp/setup-packer@v3
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
- name: Verify released binary asset
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
run: |
|
|
||||||
mkdir -p _asset
|
|
||||||
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \
|
|
||||||
--pattern "x-ui-linux-${{ matrix.arch }}.tar.gz" --dir _asset
|
|
||||||
ls -la _asset
|
|
||||||
|
|
||||||
- name: Select accelerator
|
|
||||||
id: accel
|
|
||||||
run: |
|
|
||||||
if [ -e /dev/kvm ]; then echo "value=kvm" >> "$GITHUB_OUTPUT"; else echo "value=tcg" >> "$GITHUB_OUTPUT"; fi
|
|
||||||
|
|
||||||
- name: Packer init
|
|
||||||
run: packer init deploy/packer/
|
|
||||||
|
|
||||||
- name: Build qcow2 image
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
ACCEL: ${{ steps.accel.outputs.value }}
|
|
||||||
run: |
|
|
||||||
packer build -only='qemu.x-ui' \
|
|
||||||
-var "xui_version=${TAG}" \
|
|
||||||
-var "xui_arch=${{ matrix.arch }}" \
|
|
||||||
-var "qemu_accelerator=${ACCEL}" \
|
|
||||||
deploy/packer/
|
|
||||||
|
|
||||||
- name: Compress qcow2
|
|
||||||
id: pack
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
run: |
|
|
||||||
cd deploy/packer/output-qemu
|
|
||||||
src="3x-ui-ubuntu-24.04-${{ matrix.arch }}.qcow2"
|
|
||||||
out="3x-ui-ubuntu-24.04-${TAG}-${{ matrix.arch }}.qcow2.xz"
|
|
||||||
xz -T0 -6 -c "$src" > "$out"
|
|
||||||
sha256sum "$out" > "${out}.sha256"
|
|
||||||
echo "file=deploy/packer/output-qemu/${out}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "sha=deploy/packer/output-qemu/${out}.sha256" >> "$GITHUB_OUTPUT"
|
|
||||||
ls -la
|
|
||||||
|
|
||||||
- name: Attach qcow2 to release
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
run: |
|
|
||||||
gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" --clobber \
|
|
||||||
"${{ steps.pack.outputs.file }}" "${{ steps.pack.outputs.sha }}"
|
|
||||||
|
|
||||||
- name: Summary
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
ACCEL: ${{ steps.accel.outputs.value }}
|
|
||||||
run: |
|
|
||||||
{
|
|
||||||
echo "## QEMU image (${{ matrix.arch }})"
|
|
||||||
echo "- Tag: \`${TAG}\`"
|
|
||||||
echo "- Accelerator: \`${ACCEL}\`"
|
|
||||||
echo "- Attached: \`$(basename "${{ steps.pack.outputs.file }}")\`"
|
|
||||||
} >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
|
|
||||||
ami-image:
|
|
||||||
needs: [setup, check-aws]
|
|
||||||
if: needs.check-aws.outputs.enabled == 'true'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 60
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
id-token: write
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- arch: amd64
|
|
||||||
instance_type: t3.small
|
|
||||||
- arch: arm64
|
|
||||||
instance_type: t4g.small
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Setup Packer
|
|
||||||
uses: hashicorp/setup-packer@v3
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
- name: Configure AWS credentials (OIDC)
|
|
||||||
if: needs.check-aws.outputs.use_oidc == 'true'
|
|
||||||
uses: aws-actions/configure-aws-credentials@v6
|
|
||||||
with:
|
|
||||||
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
|
|
||||||
aws-region: ${{ vars.AWS_REGION || 'eu-central-1' }}
|
|
||||||
|
|
||||||
- name: Configure AWS credentials (access keys)
|
|
||||||
if: needs.check-aws.outputs.use_oidc != 'true'
|
|
||||||
uses: aws-actions/configure-aws-credentials@v6
|
|
||||||
with:
|
|
||||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
|
||||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
|
||||||
aws-region: ${{ vars.AWS_REGION || 'eu-central-1' }}
|
|
||||||
|
|
||||||
- name: Verify released binary asset
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
run: |
|
|
||||||
mkdir -p _asset
|
|
||||||
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \
|
|
||||||
--pattern "x-ui-linux-${{ matrix.arch }}.tar.gz" --dir _asset
|
|
||||||
ls -la _asset
|
|
||||||
|
|
||||||
- name: Packer init
|
|
||||||
run: packer init deploy/packer/
|
|
||||||
|
|
||||||
- name: Build AMI
|
|
||||||
env:
|
|
||||||
TAG: ${{ needs.setup.outputs.tag }}
|
|
||||||
REGION: ${{ vars.AWS_REGION || 'eu-central-1' }}
|
|
||||||
run: |
|
|
||||||
packer build -only='amazon-ebs.x-ui' \
|
|
||||||
-var "xui_version=${TAG}" \
|
|
||||||
-var "xui_arch=${{ matrix.arch }}" \
|
|
||||||
-var "instance_type=${{ matrix.instance_type }}" \
|
|
||||||
-var "region=${REGION}" \
|
|
||||||
deploy/packer/
|
|
||||||
|
|
||||||
- name: Publish AMI id to summary
|
|
||||||
env:
|
|
||||||
REGION: ${{ vars.AWS_REGION || 'eu-central-1' }}
|
|
||||||
run: |
|
|
||||||
AMI_ID=$(jq -r '.builds[] | select(.builder_type=="amazon-ebs") | .artifact_id' packer-manifest.json | tail -1 | cut -d: -f2)
|
|
||||||
{
|
|
||||||
echo "## AWS AMI (${{ matrix.arch }})"
|
|
||||||
echo "- Region: \`${REGION}\`"
|
|
||||||
echo "- Instance type: \`${{ matrix.instance_type }}\`"
|
|
||||||
echo "- AMI ID: \`${AMI_ID}\`"
|
|
||||||
} >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
@@ -97,7 +97,13 @@ jobs:
|
|||||||
export CC=$(realpath "$(find "$TOOLCHAIN_DIR/bin" -name '*-gcc.br_real' -type f -executable | head -n1)")
|
export CC=$(realpath "$(find "$TOOLCHAIN_DIR/bin" -name '*-gcc.br_real' -type f -executable | head -n1)")
|
||||||
[ -z "$CC" ] && { echo "No gcc.br_real found in $TOOLCHAIN_DIR/bin" >&2; exit 1; }
|
[ -z "$CC" ] && { echo "No gcc.br_real found in $TOOLCHAIN_DIR/bin" >&2; exit 1; }
|
||||||
cd -
|
cd -
|
||||||
go build -ldflags "-w -s -linkmode external -extldflags '-static'" -o xui-release -v main.go
|
# Stamp the commit into per-commit (dev channel) builds only; tagged
|
||||||
|
# stable releases stay unstamped so config.IsDevBuild() returns false.
|
||||||
|
LDFLAGS="-w -s -linkmode external -extldflags '-static'"
|
||||||
|
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
|
||||||
|
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA::8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
fi
|
||||||
|
go build -ldflags "$LDFLAGS" -o xui-release -v main.go
|
||||||
file xui-release
|
file xui-release
|
||||||
ldd xui-release || echo "Static binary confirmed"
|
ldd xui-release || echo "Static binary confirmed"
|
||||||
|
|
||||||
@@ -112,7 +118,7 @@ jobs:
|
|||||||
cd x-ui/bin
|
cd x-ui/bin
|
||||||
|
|
||||||
# Download dependencies
|
# Download dependencies
|
||||||
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.6.22/"
|
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.6.27/"
|
||||||
if [ "${{ matrix.platform }}" == "amd64" ]; then
|
if [ "${{ matrix.platform }}" == "amd64" ]; then
|
||||||
wget -q ${Xray_URL}Xray-linux-64.zip
|
wget -q ${Xray_URL}Xray-linux-64.zip
|
||||||
unzip Xray-linux-64.zip
|
unzip Xray-linux-64.zip
|
||||||
@@ -150,14 +156,20 @@ jobs:
|
|||||||
wget -q -O geoip_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat
|
wget -q -O geoip_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
wget -q -O geosite_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat
|
wget -q -O geosite_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat
|
||||||
mv xray xray-linux-${{ matrix.platform }}
|
mv xray xray-linux-${{ matrix.platform }}
|
||||||
# mtg (MTProto sidecar) - only for arches mtg publishes
|
# mtg-multi (MTProto sidecar) ships prebuilt release binaries whose
|
||||||
MTG_VER="2.2.8"
|
# platform labels match our matrix, so download and unpack the matching
|
||||||
|
# archive. Only the platforms the fork publishes are packaged. The tag
|
||||||
|
# is resolved from the fork's latest release so it never needs bumping
|
||||||
|
# here; the token only lifts the API rate limit for a public read.
|
||||||
|
MTG_MULTI_VER=$(curl -sfL -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" "https://api.github.com/repos/mhsanaei/mtg-multi/releases/latest" | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n 1)
|
||||||
|
if [ -z "$MTG_MULTI_VER" ]; then echo "could not resolve the latest mtg-multi release tag"; exit 1; fi
|
||||||
case "${{ matrix.platform }}" in
|
case "${{ matrix.platform }}" in
|
||||||
amd64|arm64|armv7|armv6|386)
|
amd64|arm64|armv7|armv6|386)
|
||||||
wget -q "https://github.com/9seconds/mtg/releases/download/v${MTG_VER}/mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
|
MTG_PKG="mtg-multi-${MTG_MULTI_VER#v}-linux-${{ matrix.platform }}"
|
||||||
tar -xzf "mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
|
curl -sfLRO "https://github.com/mhsanaei/mtg-multi/releases/download/${MTG_MULTI_VER}/${MTG_PKG}.tar.gz"
|
||||||
mv "mtg-${MTG_VER}-linux-${{ matrix.platform }}/mtg" "mtg-linux-${{ matrix.platform }}" 2>/dev/null || mv mtg "mtg-linux-${{ matrix.platform }}"
|
tar -xzf "${MTG_PKG}.tar.gz"
|
||||||
rm -rf "mtg-${MTG_VER}-linux-${{ matrix.platform }}" "mtg-${MTG_VER}-linux-${{ matrix.platform }}.tar.gz"
|
mv "${MTG_PKG}/mtg-multi" "mtg-linux-${{ matrix.platform }}"
|
||||||
|
rm -rf "${MTG_PKG}" "${MTG_PKG}.tar.gz"
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
cd ../..
|
cd ../..
|
||||||
@@ -245,7 +257,12 @@ jobs:
|
|||||||
go version
|
go version
|
||||||
gcc --version
|
gcc --version
|
||||||
|
|
||||||
go build -ldflags "-w -s" -o xui-release.exe -v main.go
|
# Stamp the commit into per-commit (dev channel) builds only.
|
||||||
|
LDFLAGS="-w -s"
|
||||||
|
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
|
||||||
|
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA:0:8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
fi
|
||||||
|
go build -ldflags "$LDFLAGS" -o xui-release.exe -v main.go
|
||||||
|
|
||||||
- name: Copy and download resources
|
- name: Copy and download resources
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
@@ -256,7 +273,7 @@ jobs:
|
|||||||
cd x-ui\bin
|
cd x-ui\bin
|
||||||
|
|
||||||
# Download Xray for Windows
|
# Download Xray for Windows
|
||||||
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.6.22/"
|
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.6.27/"
|
||||||
Invoke-WebRequest -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip"
|
Invoke-WebRequest -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip"
|
||||||
Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath .
|
Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath .
|
||||||
Remove-Item "Xray-windows-64.zip"
|
Remove-Item "Xray-windows-64.zip"
|
||||||
@@ -269,13 +286,16 @@ jobs:
|
|||||||
Invoke-WebRequest -Uri "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "geosite_RU.dat"
|
Invoke-WebRequest -Uri "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "geosite_RU.dat"
|
||||||
Rename-Item xray.exe xray-windows-amd64.exe
|
Rename-Item xray.exe xray-windows-amd64.exe
|
||||||
|
|
||||||
# Download mtg (MTProto sidecar) for Windows
|
# mtg-multi (MTProto sidecar) publishes a prebuilt Windows binary, so
|
||||||
$MTG_VER = "2.2.8"
|
# download and unpack it instead of compiling. The tag tracks the
|
||||||
Invoke-WebRequest -Uri "https://github.com/9seconds/mtg/releases/download/v$MTG_VER/mtg-$MTG_VER-windows-amd64.zip" -OutFile "mtg-windows-amd64.zip"
|
# fork's latest release so it never needs bumping here.
|
||||||
Expand-Archive -Path "mtg-windows-amd64.zip" -DestinationPath "mtg-tmp"
|
$MTG_MULTI_VER = (Invoke-RestMethod -Uri "https://api.github.com/repos/mhsanaei/mtg-multi/releases/latest" -Headers @{ Authorization = "Bearer ${{ secrets.GITHUB_TOKEN }}"; "User-Agent" = "x-ui-release" }).tag_name
|
||||||
$mtgExe = Get-ChildItem -Path "mtg-tmp" -Recurse -Filter "mtg.exe" | Select-Object -First 1
|
if (-not $MTG_MULTI_VER) { throw "could not resolve the latest mtg-multi release tag" }
|
||||||
Move-Item $mtgExe.FullName "mtg-windows-amd64.exe"
|
$MTG_PKG = "mtg-multi-$($MTG_MULTI_VER.TrimStart('v'))-windows-amd64"
|
||||||
Remove-Item "mtg-windows-amd64.zip", "mtg-tmp" -Recurse -Force
|
curl.exe -sfLRO "https://github.com/mhsanaei/mtg-multi/releases/download/$MTG_MULTI_VER/$MTG_PKG.zip"
|
||||||
|
Expand-Archive -Path "$MTG_PKG.zip" -DestinationPath "mtg-tmp" -Force
|
||||||
|
Move-Item "mtg-tmp/$MTG_PKG/mtg-multi.exe" "mtg-windows-amd64.exe"
|
||||||
|
Remove-Item -Recurse -Force "mtg-tmp", "$MTG_PKG.zip"
|
||||||
|
|
||||||
cd ..
|
cd ..
|
||||||
Copy-Item -Path ..\windows_files\* -Destination . -Recurse
|
Copy-Item -Path ..\windows_files\* -Destination . -Recurse
|
||||||
@@ -302,3 +322,61 @@ jobs:
|
|||||||
asset_name: x-ui-windows-amd64.zip
|
asset_name: x-ui-windows-amd64.zip
|
||||||
overwrite: true
|
overwrite: true
|
||||||
prerelease: true
|
prerelease: true
|
||||||
|
|
||||||
|
# =================================
|
||||||
|
# Rolling dev channel (per-commit)
|
||||||
|
# =================================
|
||||||
|
# Publishes/overwrites the build artifacts to a single fixed-tag pre-release
|
||||||
|
# `dev-latest`, force-moved to the new commit on every push to main. The panel's
|
||||||
|
# "Dev" update channel installs from this tag. `--latest=false` is load-bearing:
|
||||||
|
# it keeps releases/latest pointing at the real stable tag, so the stable
|
||||||
|
# channel is unaffected.
|
||||||
|
publish-dev:
|
||||||
|
name: Publish rolling dev release
|
||||||
|
needs: [build, build-windows]
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
# Serialize racing pushes; never cancel an in-flight upload, or the dev
|
||||||
|
# release could be left with a partial asset set.
|
||||||
|
concurrency:
|
||||||
|
group: dev-release
|
||||||
|
cancel-in-progress: false
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Download all build artifacts
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
path: dev-artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Publish dev-latest pre-release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
COMMIT: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
short="${COMMIT::8}"
|
||||||
|
notes="Rolling development build — installs via the panel's Dev update channel.
|
||||||
|
|
||||||
|
commit=${COMMIT}
|
||||||
|
built=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
|
||||||
|
Automated per-commit build from main. Not a stable release."
|
||||||
|
|
||||||
|
# Force-move the dev-latest tag to this commit so the release tracks it.
|
||||||
|
git tag -f dev-latest "${COMMIT}"
|
||||||
|
git push -f origin refs/tags/dev-latest
|
||||||
|
|
||||||
|
if gh release view dev-latest >/dev/null 2>&1; then
|
||||||
|
gh release edit dev-latest --prerelease --latest=false \
|
||||||
|
--title "Dev build ${short}" --notes "${notes}"
|
||||||
|
else
|
||||||
|
gh release create dev-latest --prerelease --latest=false \
|
||||||
|
--target "${COMMIT}" --title "Dev build ${short}" --notes "${notes}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
gh release upload dev-latest dev-artifacts/*.tar.gz dev-artifacts/*.zip --clobber
|
||||||
|
|||||||
@@ -1,10 +1,23 @@
|
|||||||
name: Deploy Smoke Tests
|
name: Deploy Smoke Tests
|
||||||
|
|
||||||
# Container smoke tests for the unattended install path and first-boot
|
# Container smoke test for the unattended (cloud-init) install path.
|
||||||
# credential generation. 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 — passing the
|
||||||
|
# tag as an explicit version, so the green result verifies the release
|
||||||
|
# actually being shipped. That job deliberately runs the script from the
|
||||||
|
# default branch rather than checking out the tag: workflow_run executes in
|
||||||
|
# main's cache scope, so executing checked-out code there is a cache-poisoning
|
||||||
|
# surface (CodeQL actions/cache-poisoning/poisonable-step), and users pipe
|
||||||
|
# main's install.sh anyway.
|
||||||
|
# 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:
|
on:
|
||||||
push:
|
push:
|
||||||
|
branches:
|
||||||
|
- "**"
|
||||||
paths:
|
paths:
|
||||||
- "install.sh"
|
- "install.sh"
|
||||||
- "deploy/**"
|
- "deploy/**"
|
||||||
@@ -14,12 +27,16 @@ on:
|
|||||||
- "install.sh"
|
- "install.sh"
|
||||||
- "deploy/**"
|
- "deploy/**"
|
||||||
- ".github/workflows/smoke.yml"
|
- ".github/workflows/smoke.yml"
|
||||||
|
workflow_run:
|
||||||
|
workflows: ["Release 3X-UI"]
|
||||||
|
types: [completed]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
noninteractive-install:
|
noninteractive-install:
|
||||||
|
if: github.event_name != 'workflow_run'
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -31,7 +48,13 @@ jobs:
|
|||||||
- name: Non-interactive install smoke test
|
- name: Non-interactive install smoke test
|
||||||
run: bash deploy/test/smoke-noninteractive.sh
|
run: bash deploy/test/smoke-noninteractive.sh
|
||||||
|
|
||||||
first-boot:
|
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:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -40,5 +63,7 @@ jobs:
|
|||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
- name: First-boot credential smoke test
|
- name: Pinned release install smoke test
|
||||||
run: bash deploy/test/smoke-firstboot.sh
|
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/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
.cursor/
|
.cursor/
|
||||||
.claude/
|
.claude/*
|
||||||
.cache/
|
.cache/
|
||||||
.sync*
|
.sync*
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
version: "2"
|
||||||
|
|
||||||
|
run:
|
||||||
|
build-tags: []
|
||||||
|
timeout: 5m
|
||||||
|
|
||||||
|
linters:
|
||||||
|
default: standard
|
||||||
|
enable:
|
||||||
|
- bodyclose
|
||||||
|
- errorlint
|
||||||
|
- noctx
|
||||||
|
- misspell
|
||||||
|
- rowserrcheck
|
||||||
|
- sqlclosecheck
|
||||||
|
- unconvert
|
||||||
|
- usestdlibvars
|
||||||
|
exclusions:
|
||||||
|
generated: lax
|
||||||
|
presets:
|
||||||
|
- std-error-handling
|
||||||
|
paths:
|
||||||
|
- frontend
|
||||||
|
- internal/web/dist
|
||||||
|
rules:
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- errcheck
|
||||||
|
- bodyclose
|
||||||
|
- noctx
|
||||||
|
# tools/openapigen relies on go/parser.ParseDir; migrating it to
|
||||||
|
# golang.org/x/tools/go/packages is a generator change, out of scope here.
|
||||||
|
- linters:
|
||||||
|
- staticcheck
|
||||||
|
text: "SA1019: parser.ParseDir"
|
||||||
|
# ST1005 (capitalized error strings) conflicts with intentional
|
||||||
|
# user-facing error copy that tests assert verbatim.
|
||||||
|
- linters:
|
||||||
|
- staticcheck
|
||||||
|
text: "ST1005:"
|
||||||
|
|
||||||
|
formatters:
|
||||||
|
enable:
|
||||||
|
- gofumpt
|
||||||
|
- goimports
|
||||||
|
settings:
|
||||||
|
goimports:
|
||||||
|
local-prefixes:
|
||||||
|
- github.com/mhsanaei/3x-ui
|
||||||
|
exclusions:
|
||||||
|
paths:
|
||||||
|
- frontend
|
||||||
|
- internal/web/dist
|
||||||
Vendored
+29
@@ -115,6 +115,35 @@
|
|||||||
"$go"
|
"$go"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"label": "go: golangci-lint run",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "golangci-lint",
|
||||||
|
"args": [
|
||||||
|
"run"
|
||||||
|
],
|
||||||
|
"options": {
|
||||||
|
"cwd": "${workspaceFolder}"
|
||||||
|
},
|
||||||
|
"problemMatcher": [
|
||||||
|
"$go"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "go: golangci-lint run --fix",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "golangci-lint",
|
||||||
|
"args": [
|
||||||
|
"run",
|
||||||
|
"--fix"
|
||||||
|
],
|
||||||
|
"options": {
|
||||||
|
"cwd": "${workspaceFolder}"
|
||||||
|
},
|
||||||
|
"problemMatcher": [
|
||||||
|
"$go"
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"label": "frontend: ncu -u",
|
"label": "frontend: ncu -u",
|
||||||
"type": "shell",
|
"type": "shell",
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
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.
|
||||||
|
Runs Xray-core as a managed child process (`internal/xray/process.go`) and
|
||||||
|
imports `github.com/xtls/xray-core` for config types + gRPC stats/handler/router
|
||||||
|
API. MTProto inbounds run a second managed child — the `mtg-multi` binary
|
||||||
|
(`github.com/mhsanaei/mtg-multi`, a multi-secret fork built from source;
|
||||||
|
`internal/mtproto/`) — outside Xray, one process per inbound serving each
|
||||||
|
client's FakeTLS secret via the fork's `[secrets]` section (plus per-client
|
||||||
|
ad-tags via `[secret-ad-tags]` and per-client data quota / expiry via
|
||||||
|
`[secret-limits]`, mapped from the client's `totalGB`/`expiryTime`). Client,
|
||||||
|
ad-tag and quota/expiry edits are hot-applied through the fork's management API
|
||||||
|
(`PUT /secrets`, bearer-token guarded) so connections survive; the manager
|
||||||
|
falls back to a process restart on older binaries. A client's panel-side
|
||||||
|
traffic reset also calls `POST /secrets/{name}/reset-quota` so a renewed client
|
||||||
|
is not re-blocked by the sidecar's quota counter.
|
||||||
|
- Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux; the executable dir on
|
||||||
|
Windows), PostgreSQL optional (`XUI_DB_TYPE` / `XUI_DB_DSN`). The CGo SQLite
|
||||||
|
driver (`mattn/go-sqlite3`) needs a C compiler — `CGO_ENABLED=0` builds fail.
|
||||||
|
- Frontend: React 19 + Ant Design 6 + Vite 8 + TypeScript in `frontend/`,
|
||||||
|
built into `internal/web/dist/` (gitignored) and embedded via `embed.FS`.
|
||||||
|
|
||||||
|
## Repo map
|
||||||
|
- `main.go` — entry point + `x-ui` CLI (run, migrate, migrate-db, setting, cert).
|
||||||
|
- `internal/config/` — env parsing (XUI_DEBUG, XUI_LOG_LEVEL, XUI_LOG_FOLDER,
|
||||||
|
XUI_BIN_FOLDER, XUI_SKIP_HSTS, XUI_PORT, XUI_DB_*).
|
||||||
|
- `internal/database/` + `internal/database/model/` — GORM schema (Inbound,
|
||||||
|
Client, Setting, User), inbound Protocol enum, AutoMigrate + hand-written
|
||||||
|
migrations in `db.go`.
|
||||||
|
- `internal/xray/` — Xray child-process lifecycle, config generation, gRPC API.
|
||||||
|
- `internal/mtproto/` — MTProto inbounds via the bundled `mtg-multi` binary.
|
||||||
|
- `internal/sub/` — subscription server (raw / JSON / Clash).
|
||||||
|
- `internal/eventbus/` — in-process pub/sub (outbound/node health, xray.crash,
|
||||||
|
cpu.high, memory.high, login.attempt).
|
||||||
|
- `internal/logger/`, `internal/util/` (link, crypto, sys, ldap, …),
|
||||||
|
`internal/tunnelmonitor/` — shared infrastructure.
|
||||||
|
- `internal/web/` — Gin server (embeds `dist/` + `translation/`).
|
||||||
|
- `controller/` — panel + REST API handlers; OpenAPI at /panel/api/openapi.json.
|
||||||
|
- `service/` — business logic (InboundService, SettingService, XrayService,
|
||||||
|
node sync); subpackages tgbot/, email/, outbound/, panel/, integration/.
|
||||||
|
- `job/` — cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP).
|
||||||
|
- `middleware/`, `entity/`, `global/`, `session/` (CSRF), `network/`,
|
||||||
|
`runtime/` (master/sub-node over mTLS), `websocket/`.
|
||||||
|
- `locale/` + `translation/` — i18n, 13 embedded locale JSON files.
|
||||||
|
- `frontend/` — React + TS source (see `frontend/CLAUDE.md`).
|
||||||
|
- `tools/openapigen/` — Go generator that emits frontend types + Zod/JSON schemas
|
||||||
|
into `frontend/src/generated/` from Go structs. The OpenAPI doc itself
|
||||||
|
(`frontend/public/openapi.json`) is assembled from those + `endpoints.ts` by
|
||||||
|
`frontend/scripts/build-openapi.mjs`.
|
||||||
|
|
||||||
|
## Hard rules (non-negotiable)
|
||||||
|
- NO `//` line comments in committed Go/TS. Names carry meaning; rename instead
|
||||||
|
of annotating. Exempt: `//go:build`, `//go:generate`, and other directives.
|
||||||
|
HTML `<!-- -->` is fine. (A linter cannot enforce this — you must.)
|
||||||
|
- New `g.POST`/`g.GET` in `internal/web/controller/` REQUIRES a matching entry
|
||||||
|
in `frontend/src/pages/api-docs/endpoints.ts`, then `make gen` (or
|
||||||
|
`cd frontend && npm run gen`). It is a hand-maintained registry — nothing checks
|
||||||
|
it against the Go routes, so an omitted route silently vanishes from the docs.
|
||||||
|
- Response examples come from Go struct `example:` tags via `tools/openapigen` —
|
||||||
|
never hand-write them. A new struct must be added to openapigen's `StructAllow`
|
||||||
|
allowlist (`tools/openapigen/main.go`) or it is silently omitted from
|
||||||
|
schemas/examples (and `build-openapi.mjs` then fails on the missing schema).
|
||||||
|
- A new English i18n key must be added to EVERY locale JSON in
|
||||||
|
`internal/web/translation/` (13 files). Missing keys fall back to en-US (or
|
||||||
|
render the raw key if absent there too); nothing fails the build, so they are
|
||||||
|
easy to miss.
|
||||||
|
- DB / model changes require a migration in `internal/database/db.go`.
|
||||||
|
- Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `docs`,
|
||||||
|
`style`): `<area>: short imperative summary`, then a body explaining the why.
|
||||||
|
|
||||||
|
## Go conventions
|
||||||
|
- Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests,
|
||||||
|
`t.Helper()` on helpers. Assert the exact value / typed error / emitted
|
||||||
|
string, never just `err != nil`. Prefer real deps over mocks: throwaway DB via
|
||||||
|
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` +
|
||||||
|
`t.Cleanup(func() { _ = database.CloseDB() })`; `httptest` for HTTP.
|
||||||
|
`internal/sub`'s `initSubDB(t)` is the template.
|
||||||
|
- Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`.
|
||||||
|
|
||||||
|
## Frontend conventions (summary; full version in frontend/CLAUDE.md)
|
||||||
|
- Ant Design 6 only — no Tailwind/shadcn. Targeted tweaks, not rewrites.
|
||||||
|
- TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in
|
||||||
|
`src/schemas/` are the source of truth; infer types with `z.infer`, never
|
||||||
|
hand-write. Do not edit `src/generated/`.
|
||||||
|
- Editing `frontend/src` does NOT change what users see until the Vite build is
|
||||||
|
regenerated into `internal/web/dist/`. In `XUI_DEBUG=true`, HTML is served from
|
||||||
|
the frozen embedded FS but JS/CSS off disk — after `npm run build` you MUST
|
||||||
|
restart `go run .` or you get a blank page with 404s.
|
||||||
|
- After touching share-link logic (`src/lib/xray/`), run `npm run test` (golden
|
||||||
|
fixtures); regenerate snapshots (`npx vitest run -u`) only for intentional
|
||||||
|
output changes, never to make a red test green.
|
||||||
|
|
||||||
|
## Build, test, verify
|
||||||
|
Run `make help` for all targets. The full local gate that mirrors CI:
|
||||||
|
|
||||||
|
make verify
|
||||||
|
|
||||||
|
Common targets: `make gen` (regenerate Zod/OpenAPI), `make lint` (Go + frontend),
|
||||||
|
`make test` (Go `-shuffle=on` + frontend), `make race`, `make build`. See `Makefile`.
|
||||||
|
|
||||||
|
## Definition of done (before opening a PR)
|
||||||
|
1. `make gen` and confirm `git diff` on `frontend/src/generated` +
|
||||||
|
`frontend/public/openapi.json` is clean.
|
||||||
|
2. `make verify` passes.
|
||||||
|
3. Diff is focused; refactors are separate from feature work.
|
||||||
+4
-4
@@ -151,7 +151,7 @@ Panel navigation happens client-side through React Router, and per-route code is
|
|||||||
- **Local UI state stays in the page** (`useState`); shared concerns go through contexts and hooks in `src/hooks/` (`useTheme`, `useWebSocket`, `useClients`, `useDatepicker`, …). Prefer extending an existing hook over introducing a new global.
|
- **Local UI state stays in the page** (`useState`); shared concerns go through contexts and hooks in `src/hooks/` (`useTheme`, `useWebSocket`, `useClients`, `useDatepicker`, …). Prefer extending an existing hook over introducing a new global.
|
||||||
- **Zod is the single source of truth.** Schemas in `src/schemas/` define the xray config model; every API response is parsed through them, every form field validates against them, and TypeScript types are inferred with `z.infer` — never hand-written. Go-side types are mirrored into `src/generated/` by `npm run gen:zod` (do not hand-edit that folder).
|
- **Zod is the single source of truth.** Schemas in `src/schemas/` define the xray config model; every API response is parsed through them, every form field validates against them, and TypeScript types are inferred with `z.infer` — never hand-written. Go-side types are mirrored into `src/generated/` by `npm run gen:zod` (do not hand-edit that folder).
|
||||||
- **xray domain logic** — link generation, protocol defaults, form ⇄ wire adapters — lives as pure functions in `src/lib/xray/`. `src/models/` keeps only thin legacy types still being migrated onto schemas.
|
- **xray domain logic** — link generation, protocol defaults, form ⇄ wire adapters — lives as pure functions in `src/lib/xray/`. `src/models/` keeps only thin legacy types still being migrated onto schemas.
|
||||||
- **HTTP** goes through `HttpUtil` in `src/utils/index.ts`, a thin Axios wrapper that handles CSRF, response toasts, and a `silent: true` opt-out for bulk operations that would otherwise spam toasts. The Axios setup itself lives in `src/api/axios-init.ts`.
|
- **HTTP** goes through `HttpUtil` in `src/utils/index.ts`, a thin `fetch` wrapper that handles CSRF, response toasts, and a `silent: true` opt-out for bulk operations that would otherwise spam toasts. The `fetch` setup itself (base path, CSRF, 401/403 handling) lives in `src/api/http-init.ts`.
|
||||||
|
|
||||||
### i18n
|
### i18n
|
||||||
|
|
||||||
@@ -184,11 +184,11 @@ Only a genuinely **standalone bundle** (like `login` or `subpage`, reachable wit
|
|||||||
- **Ant Design 6** is the only UI kit — no Tailwind, no shadcn. A previous attempt to migrate was rolled back. Small, targeted UX tweaks beat sweeping rewrites; raise broader visual changes for discussion before implementing.
|
- **Ant Design 6** is the only UI kit — no Tailwind, no shadcn. A previous attempt to migrate was rolled back. Small, targeted UX tweaks beat sweeping rewrites; raise broader visual changes for discussion before implementing.
|
||||||
- **Function components + hooks** everywhere. No class components.
|
- **Function components + hooks** everywhere. No class components.
|
||||||
- **No `//` line comments** in committed JS/TS/Vue/Go. HTML `<!-- ... -->` is fine for template structure. Names should carry the meaning; rename rather than annotate. Comments are reserved for the *why*, and only when the reason is surprising.
|
- **No `//` line comments** in committed JS/TS/Vue/Go. HTML `<!-- ... -->` is fine for template structure. Names should carry the meaning; rename rather than annotate. Comments are reserved for the *why*, and only when the reason is surprising.
|
||||||
- **RTL is a first-class concern.** Persian and Arabic users matter — RTL is enabled through AntD's `ConfigProvider direction="rtl"`. When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows.
|
- **Persian and Arabic users are first-class.** When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows. (Full RTL layout is not currently wired through AntD `ConfigProvider direction` — only the Jalali date picker is RTL-aware — so treat RTL as an open area, not a solved one.)
|
||||||
- **Schemas over `any`.** New config shapes go in `src/schemas/`; `@typescript-eslint/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
|
- **Schemas over `any`.** New config shapes go in `src/schemas/`; `@typescript-eslint/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
|
||||||
- **Document new endpoints.** Every new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry in `src/pages/api-docs/endpoints.ts` — it drives both the in-panel API docs and the generated OpenAPI/Zod (`npm run gen:api` / `gen:zod`).
|
- **Document new endpoints.** Every new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry in `src/pages/api-docs/endpoints.ts` — it drives both the in-panel API docs and the generated OpenAPI/Zod (`npm run gen:api` / `gen:zod`).
|
||||||
- **Do not break link generation.** Share-link logic lives in `src/lib/xray/` (`inbound-link.ts`, `outbound-link-parser.ts`, …) and is round-tripped by the golden fixture suite — run `npm run test` after any change to URL generation, defaults, or TLS/Reality handling, and regenerate snapshots (`npx vitest run -u`) only for intentional changes. Two runtime paths consume it: the **inbounds page** and the **clients page** subscription links (`/panel/api/clients/subLinks/:subId` → backend `GetSubs`); exercise both.
|
- **Do not break link generation.** Share-link logic lives in `src/lib/xray/` (`inbound-link.ts`, `outbound-link-parser.ts`, …) and is round-tripped by the golden fixture suite — run `npm run test` after any change to URL generation, defaults, or TLS/Reality handling, and regenerate snapshots (`npx vitest run -u`) only for intentional changes. Two runtime paths consume it: the **inbounds page** and the **clients page** subscription links (`/panel/api/clients/subLinks/:subId` → backend `GetSubs`); exercise both.
|
||||||
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — currently `8.0.16` — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
|
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — read the live version there rather than trusting a number quoted here — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
|
||||||
|
|
||||||
### Project layout
|
### Project layout
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ frontend/
|
|||||||
├── pages/ — one folder per route (index, inbounds, clients, groups, nodes, settings, xray, api-docs) plus login, sub
|
├── pages/ — one folder per route (index, inbounds, clients, groups, nodes, settings, xray, api-docs) plus login, sub
|
||||||
├── components/ — cross-page React components
|
├── components/ — cross-page React components
|
||||||
├── hooks/ — reusable hooks (useTheme, useWebSocket, useClients, useDatepicker, …)
|
├── hooks/ — reusable hooks (useTheme, useWebSocket, useClients, useDatepicker, …)
|
||||||
├── api/ — Axios + CSRF interceptor, TanStack Query provider/keys, WebSocket client
|
├── api/ — fetch client + CSRF handling, TanStack Query provider/keys, WebSocket client
|
||||||
├── i18n/ — react-i18next bootstrap (JSON lives in internal/web/translation/)
|
├── i18n/ — react-i18next bootstrap (JSON lives in internal/web/translation/)
|
||||||
├── lib/xray/ — pure xray logic: link generation, defaults, form ⇄ wire adapters
|
├── lib/xray/ — pure xray logic: link generation, defaults, form ⇄ wire adapters
|
||||||
├── schemas/ — Zod source of truth for the xray config model
|
├── schemas/ — Zod source of truth for the xray config model
|
||||||
|
|||||||
@@ -69,5 +69,14 @@ EOF
|
|||||||
fail2ban-client -x start
|
fail2ban-client -x start
|
||||||
fi
|
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
|
# Run x-ui
|
||||||
exec /app/x-ui
|
exec /app/x-ui
|
||||||
|
|||||||
+18
-12
@@ -3,45 +3,51 @@ case $1 in
|
|||||||
amd64)
|
amd64)
|
||||||
ARCH="64"
|
ARCH="64"
|
||||||
FNAME="amd64"
|
FNAME="amd64"
|
||||||
MTG_ARCH="amd64"
|
|
||||||
;;
|
;;
|
||||||
i386)
|
i386)
|
||||||
ARCH="32"
|
ARCH="32"
|
||||||
FNAME="i386"
|
FNAME="i386"
|
||||||
MTG_ARCH="386"
|
|
||||||
;;
|
;;
|
||||||
armv8 | arm64 | aarch64)
|
armv8 | arm64 | aarch64)
|
||||||
ARCH="arm64-v8a"
|
ARCH="arm64-v8a"
|
||||||
FNAME="arm64"
|
FNAME="arm64"
|
||||||
MTG_ARCH="arm64"
|
|
||||||
;;
|
;;
|
||||||
armv7 | arm | arm32)
|
armv7 | arm | arm32)
|
||||||
ARCH="arm32-v7a"
|
ARCH="arm32-v7a"
|
||||||
FNAME="arm32"
|
FNAME="arm32"
|
||||||
MTG_ARCH="armv7"
|
|
||||||
;;
|
;;
|
||||||
armv6)
|
armv6)
|
||||||
ARCH="arm32-v6"
|
ARCH="arm32-v6"
|
||||||
FNAME="armv6"
|
FNAME="armv6"
|
||||||
MTG_ARCH="armv6"
|
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
ARCH="64"
|
ARCH="64"
|
||||||
FNAME="amd64"
|
FNAME="amd64"
|
||||||
MTG_ARCH="amd64"
|
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
MTG_VER="2.2.8"
|
MTG_MULTI_VER=$(curl -sfL "https://api.github.com/repos/mhsanaei/mtg-multi/releases/latest" | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n 1)
|
||||||
|
if [ -z "$MTG_MULTI_VER" ]; then
|
||||||
|
echo "DockerInit: could not resolve the latest mtg-multi release tag" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
mkdir -p build/bin
|
mkdir -p build/bin
|
||||||
cd build/bin
|
cd build/bin
|
||||||
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.6.22/Xray-linux-${ARCH}.zip"
|
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.6.27/Xray-linux-${ARCH}.zip"
|
||||||
unzip "Xray-linux-${ARCH}.zip"
|
unzip "Xray-linux-${ARCH}.zip"
|
||||||
rm -f "Xray-linux-${ARCH}.zip" geoip.dat geosite.dat
|
rm -f "Xray-linux-${ARCH}.zip" geoip.dat geosite.dat
|
||||||
mv xray "xray-linux-${FNAME}"
|
mv xray "xray-linux-${FNAME}"
|
||||||
curl -sfLRO "https://github.com/9seconds/mtg/releases/download/v${MTG_VER}/mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
|
# mtg-multi (MTProto sidecar) ships prebuilt release binaries for every target
|
||||||
tar -xzf "mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
|
# we package, so download and unpack the matching one instead of compiling.
|
||||||
mv "mtg-${MTG_VER}-linux-${MTG_ARCH}/mtg" "mtg-linux-${FNAME}" 2>/dev/null || mv mtg "mtg-linux-${FNAME}"
|
case $FNAME in
|
||||||
rm -rf "mtg-${MTG_VER}-linux-${MTG_ARCH}" "mtg-${MTG_VER}-linux-${MTG_ARCH}.tar.gz"
|
i386) MTGARCH="386" ;;
|
||||||
|
arm32) MTGARCH="armv7" ;;
|
||||||
|
*) MTGARCH="$FNAME" ;;
|
||||||
|
esac
|
||||||
|
MTG_PKG="mtg-multi-${MTG_MULTI_VER#v}-linux-${MTGARCH}"
|
||||||
|
curl -sfLRO "https://github.com/mhsanaei/mtg-multi/releases/download/${MTG_MULTI_VER}/${MTG_PKG}.tar.gz"
|
||||||
|
tar -xzf "${MTG_PKG}.tar.gz"
|
||||||
|
mv "${MTG_PKG}/mtg-multi" "mtg-linux-${FNAME}"
|
||||||
|
rm -rf "${MTG_PKG}" "${MTG_PKG}.tar.gz"
|
||||||
chmod +x "mtg-linux-${FNAME}"
|
chmod +x "mtg-linux-${FNAME}"
|
||||||
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat
|
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Canonical task runner. Mirrors .github/workflows/ci.yml so `make verify`
|
||||||
|
# reproduces the PR gate locally. Run `make help` for the list.
|
||||||
|
|
||||||
|
SHELL := bash
|
||||||
|
GO_PKGS = $(shell go list ./... | grep -v '/frontend/node_modules/')
|
||||||
|
FRONTEND = frontend
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := help
|
||||||
|
|
||||||
|
.PHONY: help
|
||||||
|
help: ## Show this help
|
||||||
|
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
|
||||||
|
awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}'
|
||||||
|
|
||||||
|
# go:embed of internal/web/dist needs the dir to exist even when the
|
||||||
|
# frontend bundle has not been built. CI stubs it the same way.
|
||||||
|
.PHONY: dist-stub
|
||||||
|
dist-stub:
|
||||||
|
@mkdir -p internal/web/dist && touch internal/web/dist/.gitkeep
|
||||||
|
|
||||||
|
.PHONY: gen
|
||||||
|
gen: ## Regenerate Zod schemas + OpenAPI from Go sources
|
||||||
|
cd $(FRONTEND) && npm run gen
|
||||||
|
|
||||||
|
.PHONY: gen-check
|
||||||
|
gen-check: gen ## Fail if generated files are stale
|
||||||
|
git diff --exit-code -- frontend/src/generated frontend/public/openapi.json
|
||||||
|
|
||||||
|
.PHONY: lint-go
|
||||||
|
lint-go: dist-stub ## golangci-lint on Go sources
|
||||||
|
golangci-lint run
|
||||||
|
|
||||||
|
.PHONY: lint-fe
|
||||||
|
lint-fe: ## ESLint on frontend sources
|
||||||
|
cd $(FRONTEND) && npm run lint
|
||||||
|
|
||||||
|
.PHONY: lint
|
||||||
|
lint: lint-go lint-fe ## All linters
|
||||||
|
|
||||||
|
.PHONY: typecheck
|
||||||
|
typecheck: ## tsc --noEmit
|
||||||
|
cd $(FRONTEND) && npm run typecheck
|
||||||
|
|
||||||
|
.PHONY: test-go
|
||||||
|
test-go: dist-stub ## Go tests (shuffle, no cache)
|
||||||
|
go test -shuffle=on -count=1 $(GO_PKGS)
|
||||||
|
|
||||||
|
.PHONY: race
|
||||||
|
race: dist-stub ## Go tests with the race detector (needs a C compiler)
|
||||||
|
go test -race -shuffle=on -count=1 $(GO_PKGS)
|
||||||
|
|
||||||
|
.PHONY: test-fe
|
||||||
|
test-fe: ## Frontend tests (vitest)
|
||||||
|
cd $(FRONTEND) && npm test
|
||||||
|
|
||||||
|
.PHONY: test
|
||||||
|
test: test-go test-fe ## All tests
|
||||||
|
|
||||||
|
.PHONY: vulncheck
|
||||||
|
vulncheck: dist-stub ## govulncheck
|
||||||
|
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
|
||||||
|
|
||||||
|
.PHONY: build-fe
|
||||||
|
build-fe: ## Build the Vite bundles into internal/web/dist
|
||||||
|
cd $(FRONTEND) && npm run build
|
||||||
|
|
||||||
|
.PHONY: build
|
||||||
|
build: build-fe ## Build the frontend then the Go binary
|
||||||
|
go build ./...
|
||||||
|
|
||||||
|
# The PR gate. Matches ci.yml: codegen freshness, both linters, typecheck,
|
||||||
|
# both test suites, and a full build.
|
||||||
|
.PHONY: verify
|
||||||
|
verify: gen-check lint typecheck test build ## Full local gate (mirrors CI)
|
||||||
|
@echo "verify: OK"
|
||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** هي لوحة تحكم ويب متقدمة ومفتوحة المصدر لإدارة خوادم [Xray-core](https://github.com/XTLS/Xray-core). توفّر واجهة نظيفة ومتعددة اللغات لنشر وتكوين ومراقبة مجموعة واسعة من بروتوكولات الوكيل وVPN — من خادم VPS واحد إلى عمليات النشر متعددة العقد.
|
**3X-UI** هي لوحة تحكم ويب متقدمة ومفتوحة المصدر لإدارة خوادم [Xray-core](https://github.com/XTLS/Xray-core). توفّر واجهة نظيفة ومتعددة اللغات لنشر وتكوين ومراقبة مجموعة واسعة من بروتوكولات الوكيل وVPN — من خادم VPS واحد إلى عمليات النشر متعددة العقد.
|
||||||
@@ -33,7 +32,7 @@
|
|||||||
- **إحصائيات الترافيك** — لكل اتصال وارد، ولكل عميل، ولكل اتصال صادر، مع عناصر تحكم لإعادة التعيين.
|
- **إحصائيات الترافيك** — لكل اتصال وارد، ولكل عميل، ولكل اتصال صادر، مع عناصر تحكم لإعادة التعيين.
|
||||||
- **دعم العقد المتعددة** — إدارة وتوسيع عبر عدة خوادم من لوحة واحدة.
|
- **دعم العقد المتعددة** — إدارة وتوسيع عبر عدة خوادم من لوحة واحدة.
|
||||||
- **الاتصالات الصادرة والتوجيه** — WARP، NordVPN، قواعد توجيه مخصصة، موازنات تحميل، وتسلسل الوكلاء الصادرة.
|
- **الاتصالات الصادرة والتوجيه** — WARP، NordVPN، قواعد توجيه مخصصة، موازنات تحميل، وتسلسل الوكلاء الصادرة.
|
||||||
- **خادم اشتراك مدمج** بصيغ إخراج متعددة.
|
- **خادم اشتراك مدمج** بصيغ إخراج متعددة و[قوالب صفحات مخصصة](docs/custom-subscription-templates.md).
|
||||||
- **روبوت تيليجرام** للمراقبة والإدارة عن بُعد.
|
- **روبوت تيليجرام** للمراقبة والإدارة عن بُعد.
|
||||||
- **واجهة RESTful API** مع توثيق Swagger داخل اللوحة.
|
- **واجهة RESTful API** مع توثيق Swagger داخل اللوحة.
|
||||||
- **تخزين مرن** — SQLite (افتراضي) أو PostgreSQL.
|
- **تخزين مرن** — SQLite (افتراضي) أو PostgreSQL.
|
||||||
@@ -73,10 +72,32 @@
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
لتثبيت إصدار محدد، أضِف وسمه (مثل `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
لتثبيت بنية **dev** المتجددة (أحدث إصدار أولي لكل التزام (commit) من `main`، وليس إصدارًا مستقرًا)، مرّر `dev-latest`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
أثناء التثبيت، يتم إنشاء اسم مستخدم وكلمة مرور ومسار وصول عشوائية. بعد التثبيت، شغّل `x-ui` لفتح قائمة الإدارة، حيث يمكنك بدء/إيقاف الخدمة، وعرض أو إعادة تعيين بيانات تسجيل الدخول، وإدارة شهادات SSL، والمزيد.
|
أثناء التثبيت، يتم إنشاء اسم مستخدم وكلمة مرور ومسار وصول عشوائية. بعد التثبيت، شغّل `x-ui` لفتح قائمة الإدارة، حيث يمكنك بدء/إيقاف الخدمة، وعرض أو إعادة تعيين بيانات تسجيل الدخول، وإدارة شهادات SSL، والمزيد.
|
||||||
|
|
||||||
للحصول على الوثائق الكاملة، يرجى زيارة [ويكي المشروع](https://github.com/MHSanaei/3x-ui/wiki).
|
للحصول على الوثائق الكاملة، يرجى زيارة [ويكي المشروع](https://github.com/MHSanaei/3x-ui/wiki).
|
||||||
|
|
||||||
|
### التثبيت غير التفاعلي
|
||||||
|
|
||||||
|
يعمل المثبِّت أيضًا **بشكل غير تفاعلي** لـ cloud-init.
|
||||||
|
عيّن `XUI_NONINTERACTIVE=1` (أو مرّره عبر أنبوب دون TTY) وسيتولى التثبيت من البداية إلى النهاية
|
||||||
|
دون أي مطالبات، مُنشئًا بيانات اعتماد عشوائية وكاتبًا إياها في
|
||||||
|
`/etc/x-ui/install-result.env`. راجع [`deploy/`](deploy/) لـ:
|
||||||
|
|
||||||
|
- [بيانات مستخدم cloud-init](deploy/cloud-init/) — تثبيت غير تفاعلي على أي سحابة (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [ملاحظات Hetzner Cloud](deploy/marketplace/hetzner/) — نشر يعتمد على cloud-init على Hetzner
|
||||||
|
|
||||||
## المنصات المدعومة
|
## المنصات المدعومة
|
||||||
|
|
||||||
**أنظمة التشغيل:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
|
**أنظمة التشغيل:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | تفعيل فرض حدود IP المعتمد على Fail2ban | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | تفعيل فرض حدود IP المعتمد على Fail2ban | `true` |
|
||||||
| `XUI_LOG_LEVEL` | مستوى السجل (`debug`، `info`، `warning`، `error`) | `info` |
|
| `XUI_LOG_LEVEL` | مستوى السجل (`debug`، `info`، `warning`، `error`) | `info` |
|
||||||
| `XUI_DEBUG` | تفعيل وضع التصحيح | `false` |
|
| `XUI_DEBUG` | تفعيل وضع التصحيح | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | تفعيل مراقب صحة النفق (يفحص عنوان URL ويعيد تشغيل xray بعد فشل متكرر؛ إعادة التشغيل تقطع جميع العملاء) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | الوكيل الذي يُرسَل عبره الفحص؛ وجّهه إلى اتصال xray وارد محلي ليختبر الفحص النفق (مثل `socks5://127.0.0.1:1080`). القيمة الفارغة تعني أن الفحص يتحقق فقط من اتصال المضيف | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | عنوان 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` |
|
||||||
|
|
||||||
## اللغات المدعومة
|
## اللغات المدعومة
|
||||||
|
|
||||||
|
|||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** es un panel de control web avanzado y de código abierto para gestionar servidores [Xray-core](https://github.com/XTLS/Xray-core). Ofrece una interfaz limpia y multilingüe para desplegar, configurar y monitorear una amplia gama de protocolos de proxy y VPN — desde un único VPS hasta despliegues multinodo.
|
**3X-UI** es un panel de control web avanzado y de código abierto para gestionar servidores [Xray-core](https://github.com/XTLS/Xray-core). Ofrece una interfaz limpia y multilingüe para desplegar, configurar y monitorear una amplia gama de protocolos de proxy y VPN — desde un único VPS hasta despliegues multinodo.
|
||||||
@@ -33,7 +32,7 @@ Construido como un fork mejorado del proyecto X-UI original, 3X-UI añade un sop
|
|||||||
- **Estadísticas de tráfico** — por entrada, por cliente y por salida, con controles de reinicio.
|
- **Estadísticas de tráfico** — por entrada, por cliente y por salida, con controles de reinicio.
|
||||||
- **Soporte multinodo** — gestiona y escala a través de varios servidores desde un único panel.
|
- **Soporte multinodo** — gestiona y escala a través de varios servidores desde un único panel.
|
||||||
- **Salida y enrutamiento** — WARP, NordVPN, reglas de enrutamiento personalizadas, balanceadores de carga y encadenamiento de proxy de salida.
|
- **Salida y enrutamiento** — WARP, NordVPN, reglas de enrutamiento personalizadas, balanceadores de carga y encadenamiento de proxy de salida.
|
||||||
- **Servidor de suscripción integrado** con múltiples formatos de salida.
|
- **Servidor de suscripción integrado** con múltiples formatos de salida y [plantillas de página personalizables](docs/custom-subscription-templates.md).
|
||||||
- **Bot de Telegram** para monitorización y gestión remotas.
|
- **Bot de Telegram** para monitorización y gestión remotas.
|
||||||
- **API RESTful** con documentación Swagger dentro del panel.
|
- **API RESTful** con documentación Swagger dentro del panel.
|
||||||
- **Almacenamiento flexible** — SQLite (predeterminado) o PostgreSQL.
|
- **Almacenamiento flexible** — SQLite (predeterminado) o PostgreSQL.
|
||||||
@@ -73,10 +72,32 @@ Construido como un fork mejorado del proyecto X-UI original, 3X-UI añade un sop
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Para instalar una versión específica, añade su etiqueta (p. ej. `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Para instalar la versión **dev** continua (la última prelanzamiento por commit desde `main`, no una versión estable), pasa `dev-latest`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
Durante la instalación se generan un nombre de usuario, una contraseña y una ruta de acceso aleatorios. Tras la instalación, ejecuta `x-ui` para abrir el menú de gestión, donde puedes iniciar/detener el servicio, ver o restablecer tus credenciales de acceso, gestionar certificados SSL y mucho más.
|
Durante la instalación se generan un nombre de usuario, una contraseña y una ruta de acceso aleatorios. Tras la instalación, ejecuta `x-ui` para abrir el menú de gestión, donde puedes iniciar/detener el servicio, ver o restablecer tus credenciales de acceso, gestionar certificados SSL y mucho más.
|
||||||
|
|
||||||
Para la documentación completa, visita la [Wiki del proyecto](https://github.com/MHSanaei/3x-ui/wiki).
|
Para la documentación completa, visita la [Wiki del proyecto](https://github.com/MHSanaei/3x-ui/wiki).
|
||||||
|
|
||||||
|
### Instalación desatendida
|
||||||
|
|
||||||
|
El instalador también se ejecuta de forma **no interactiva** para cloud-init.
|
||||||
|
Define `XUI_NONINTERACTIVE=1` (o canalízalo sin TTY) y realizará la instalación de principio a fin sin
|
||||||
|
ninguna pregunta, generando credenciales aleatorias y escribiéndolas en
|
||||||
|
`/etc/x-ui/install-result.env`. Consulta [`deploy/`](deploy/) para:
|
||||||
|
|
||||||
|
- [User-data de cloud-init](deploy/cloud-init/) — instalación desatendida en cualquier nube (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [Notas de Hetzner Cloud](deploy/marketplace/hetzner/) — despliegue basado en cloud-init en Hetzner
|
||||||
|
|
||||||
## Plataformas Compatibles
|
## Plataformas Compatibles
|
||||||
|
|
||||||
**Sistemas operativos:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine y Windows.
|
**Sistemas operativos:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine y Windows.
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | Habilitar la aplicación de límites de IP basada en Fail2ban | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | Habilitar la aplicación de límites de IP basada en Fail2ban | `true` |
|
||||||
| `XUI_LOG_LEVEL` | Nivel de registro (`debug`, `info`, `warning`, `error`) | `info` |
|
| `XUI_LOG_LEVEL` | Nivel de registro (`debug`, `info`, `warning`, `error`) | `info` |
|
||||||
| `XUI_DEBUG` | Habilitar el modo de depuración | `false` |
|
| `XUI_DEBUG` | Habilitar el modo de depuración | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | Habilitar el monitor de salud del túnel (sondea una URL y reinicia xray tras fallos repetidos; un reinicio desconecta a todos los clientes) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | Proxy a través del cual se envía el sondeo; apúntalo a una entrada local de xray para que el sondeo pruebe el túnel (p. ej. `socks5://127.0.0.1:1080`). Vacío significa que el sondeo solo comprueba la conectividad del host | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | URL sondeada para verificar la salud del túnel | `https://www.cloudflare.com/cdn-cgi/trace` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_INTERVAL` | Intervalo entre sondeos | `30s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Tiempo de espera por sondeo | `10s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_FAILURES` | Fallos consecutivos antes de que se active un reinicio | `3` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Retardo mínimo entre reinicios consecutivos | `5m` |
|
||||||
|
|
||||||
## Idiomas Compatibles
|
## Idiomas Compatibles
|
||||||
|
|
||||||
|
|||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** یک پنل کنترل وب پیشرفته و متنباز برای مدیریت سرورهای [Xray-core](https://github.com/XTLS/Xray-core) است. این پنل یک رابط کاربری تمیز و چندزبانه برای استقرار، پیکربندی و نظارت بر طیف گستردهای از پروتکلهای پراکسی و VPN ارائه میدهد — از یک VPS تکی تا استقرارهای چندنودی.
|
**3X-UI** یک پنل کنترل وب پیشرفته و متنباز برای مدیریت سرورهای [Xray-core](https://github.com/XTLS/Xray-core) است. این پنل یک رابط کاربری تمیز و چندزبانه برای استقرار، پیکربندی و نظارت بر طیف گستردهای از پروتکلهای پراکسی و VPN ارائه میدهد — از یک VPS تکی تا استقرارهای چندنودی.
|
||||||
@@ -33,7 +32,7 @@
|
|||||||
- **آمار ترافیک** — بهازای هر اینباند، هر کلاینت و هر اوتباند، همراه با کنترل بازنشانی (reset).
|
- **آمار ترافیک** — بهازای هر اینباند، هر کلاینت و هر اوتباند، همراه با کنترل بازنشانی (reset).
|
||||||
- **پشتیبانی از چند نود** — مدیریت و مقیاسدهی روی چندین سرور از یک پنل واحد.
|
- **پشتیبانی از چند نود** — مدیریت و مقیاسدهی روی چندین سرور از یک پنل واحد.
|
||||||
- **اوتباند و مسیریابی** — WARP، NordVPN، قوانین مسیریابی سفارشی، متعادلکنندههای بار (load balancer) و زنجیرهکردن پراکسی اوتباند.
|
- **اوتباند و مسیریابی** — WARP، NordVPN، قوانین مسیریابی سفارشی، متعادلکنندههای بار (load balancer) و زنجیرهکردن پراکسی اوتباند.
|
||||||
- **سرور سابسکریپشن داخلی** با چندین فرمت خروجی.
|
- **سرور سابسکریپشن داخلی** با چندین فرمت خروجی و [قالبهای صفحهی سفارشی](docs/custom-subscription-templates.md).
|
||||||
- **ربات تلگرام** برای نظارت و مدیریت از راه دور.
|
- **ربات تلگرام** برای نظارت و مدیریت از راه دور.
|
||||||
- **RESTful API** همراه با مستندات Swagger درونپنل.
|
- **RESTful API** همراه با مستندات Swagger درونپنل.
|
||||||
- **ذخیرهسازی منعطف** — SQLite (پیشفرض) یا PostgreSQL.
|
- **ذخیرهسازی منعطف** — SQLite (پیشفرض) یا PostgreSQL.
|
||||||
@@ -73,10 +72,32 @@
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
برای نصب یک نسخهی مشخص، تگ آن را در انتها اضافه کنید (مثلاً `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
برای نصب نسخهی غلتانِ **dev** (آخرین پیشانتشار بهازای هر کامیت از شاخهی `main`، نه یک انتشار پایدار)، مقدار `dev-latest` را پاس دهید:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
در حین نصب، یک نام کاربری، رمز عبور و مسیر دسترسی تصادفی تولید میشود. پس از نصب، دستور `x-ui` را اجرا کنید تا منوی مدیریت باز شود؛ در آنجا میتوانید سرویس را شروع/متوقف کنید، اطلاعات ورود خود را ببینید یا بازنشانی کنید، گواهیهای SSL را مدیریت کنید و کارهای دیگری انجام دهید.
|
در حین نصب، یک نام کاربری، رمز عبور و مسیر دسترسی تصادفی تولید میشود. پس از نصب، دستور `x-ui` را اجرا کنید تا منوی مدیریت باز شود؛ در آنجا میتوانید سرویس را شروع/متوقف کنید، اطلاعات ورود خود را ببینید یا بازنشانی کنید، گواهیهای SSL را مدیریت کنید و کارهای دیگری انجام دهید.
|
||||||
|
|
||||||
برای مستندات کامل، لطفاً به [ویکی پروژه](https://github.com/MHSanaei/3x-ui/wiki) مراجعه کنید.
|
برای مستندات کامل، لطفاً به [ویکی پروژه](https://github.com/MHSanaei/3x-ui/wiki) مراجعه کنید.
|
||||||
|
|
||||||
|
### نصب بدون نظارت
|
||||||
|
|
||||||
|
نصبکننده بهصورت **غیرتعاملی** نیز برای cloud-init اجرا میشود.
|
||||||
|
`XUI_NONINTERACTIVE=1` را تنظیم کنید (یا بدون TTY از طریق pipe اجرا کنید) تا نصب بهصورت سرتاسری و بدون
|
||||||
|
هیچ پرسشی انجام شود، اطلاعات ورود تصادفی تولید کرده و آنها را در
|
||||||
|
`/etc/x-ui/install-result.env` مینویسد. برای موارد زیر به [`deploy/`](deploy/) مراجعه کنید:
|
||||||
|
|
||||||
|
- [user-data مربوط به Cloud-init](deploy/cloud-init/) — نصب بدون نظارت روی هر ابری (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [یادداشتهای Hetzner Cloud](deploy/marketplace/hetzner/) — استقرار مبتنی بر cloud-init روی Hetzner
|
||||||
|
|
||||||
## پلتفرمهای پشتیبانیشده
|
## پلتفرمهای پشتیبانیشده
|
||||||
|
|
||||||
**سیستمعاملها:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
|
**سیستمعاملها:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | فعالسازی اعمال محدودیت IP مبتنی بر Fail2ban | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | فعالسازی اعمال محدودیت IP مبتنی بر Fail2ban | `true` |
|
||||||
| `XUI_LOG_LEVEL` | سطح گزارشگیری (`debug`، `info`، `warning`، `error`) | `info` |
|
| `XUI_LOG_LEVEL` | سطح گزارشگیری (`debug`، `info`، `warning`، `error`) | `info` |
|
||||||
| `XUI_DEBUG` | فعالسازی حالت دیباگ | `false` |
|
| `XUI_DEBUG` | فعالسازی حالت دیباگ | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | فعالسازی پایشگر سلامت تونل (یک URL را پروب میکند و پس از خطاهای مکرر، xray را ریاستارت میکند؛ یک ریاستارت همهی کلاینتها را قطع میکند) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | پراکسیای که پروب از طریق آن ارسال میشود؛ آن را به یک اینباند محلی xray اشاره دهید تا پروب خودِ تونل را آزمایش کند (مثلاً `socks5://127.0.0.1:1080`). خالی بودن یعنی پروب فقط اتصال به هاست را بررسی میکند | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | 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` |
|
||||||
|
|
||||||
## زبانهای پشتیبانیشده
|
## زبانهای پشتیبانیشده
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** is an advanced, open-source web control panel for managing [Xray-core](https://github.com/XTLS/Xray-core) servers. It provides a clean, multi-language interface for deploying, configuring, and monitoring a wide range of proxy and VPN protocols — from a single VPS to multi-node deployments.
|
**3X-UI** is an advanced, open-source web control panel for managing [Xray-core](https://github.com/XTLS/Xray-core) servers. It provides a clean, multi-language interface for deploying, configuring, and monitoring a wide range of proxy and VPN protocols — from a single VPS to multi-node deployments.
|
||||||
@@ -73,21 +72,31 @@ Built as an enhanced fork of the original X-UI project, 3X-UI adds broader proto
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To install a specific version, append its tag (e.g. `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
To install the rolling **dev** build (latest per-commit pre-release from `main`, not a stable release), pass `dev-latest`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
During installation a random username, password, and access path are generated. After installation, run `x-ui` to open the management menu, where you can start/stop the service, view or reset your login credentials, manage SSL certificates, and more.
|
During installation a random username, password, and access path are generated. After installation, run `x-ui` to open the management menu, where you can start/stop the service, view or reset your login credentials, manage SSL certificates, and more.
|
||||||
|
|
||||||
For full documentation, please visit the [project Wiki](https://github.com/MHSanaei/3x-ui/wiki).
|
For full documentation, please visit the [project Wiki](https://github.com/MHSanaei/3x-ui/wiki).
|
||||||
|
|
||||||
### Unattended install & cloud images
|
### Unattended install
|
||||||
|
|
||||||
The installer also runs **non-interactively** for cloud-init and golden images.
|
The installer also runs **non-interactively** for cloud-init.
|
||||||
Set `XUI_NONINTERACTIVE=1` (or pipe with no TTY) and it installs end-to-end with
|
Set `XUI_NONINTERACTIVE=1` (or pipe with no TTY) and it installs end-to-end with
|
||||||
zero prompts, generating random credentials and writing them to
|
zero prompts, generating random credentials and writing them to
|
||||||
`/etc/x-ui/install-result.env`. See [`deploy/`](deploy/) for:
|
`/etc/x-ui/install-result.env`. See [`deploy/`](deploy/) for:
|
||||||
|
|
||||||
- [Cloud-init user-data](deploy/cloud-init/) — unattended install on any cloud (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
- [Cloud-init user-data](deploy/cloud-init/) — unattended install on any cloud (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
- [Packer golden image](deploy/packer/) — build an AWS EC2 AMI + qcow2 (amd64/arm64) with per-instance credentials generated on first boot
|
- [Hetzner Cloud notes](deploy/marketplace/hetzner/) — cloud-init deployment on Hetzner
|
||||||
- [Amazon Lightsail](deploy/lightsail/) — launch script + reusable snapshot builder
|
|
||||||
- [AWS Marketplace checklist](deploy/marketplace/aws/)
|
|
||||||
|
|
||||||
## Supported Platforms
|
## Supported Platforms
|
||||||
|
|
||||||
@@ -146,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | Enable Fail2ban-based IP-limit enforcement | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | Enable Fail2ban-based IP-limit enforcement | `true` |
|
||||||
| `XUI_LOG_LEVEL` | Log verbosity (`debug`, `info`, `warning`, `error`) | `info` |
|
| `XUI_LOG_LEVEL` | Log verbosity (`debug`, `info`, `warning`, `error`) | `info` |
|
||||||
| `XUI_DEBUG` | Enable debug mode | `false` |
|
| `XUI_DEBUG` | Enable debug mode | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | Enable the tunnel health monitor (probes a URL and restarts xray after repeated failures; a restart drops all clients) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | Proxy the probe is sent through; point it at a local xray inbound so the probe tests the tunnel (e.g. `socks5://127.0.0.1:1080`). Empty means the probe only checks host connectivity | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | URL probed for tunnel health | `https://www.cloudflare.com/cdn-cgi/trace` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_INTERVAL` | Interval between probes | `30s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Per-probe timeout | `10s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_FAILURES` | Consecutive failures before a restart is triggered | `3` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Minimum delay between consecutive restarts | `5m` |
|
||||||
|
|
||||||
## Supported Languages
|
## Supported Languages
|
||||||
|
|
||||||
|
|||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** — продвинутая веб-панель управления с открытым исходным кодом для управления серверами [Xray-core](https://github.com/XTLS/Xray-core). Она предоставляет аккуратный многоязычный интерфейс для развёртывания, настройки и мониторинга широкого спектра протоколов прокси и VPN — от одного VPS до развёртываний с несколькими узлами.
|
**3X-UI** — продвинутая веб-панель управления с открытым исходным кодом для управления серверами [Xray-core](https://github.com/XTLS/Xray-core). Она предоставляет аккуратный многоязычный интерфейс для развёртывания, настройки и мониторинга широкого спектра протоколов прокси и VPN — от одного VPS до развёртываний с несколькими узлами.
|
||||||
@@ -33,7 +32,7 @@
|
|||||||
- **Статистика трафика** — по каждому входящему, по каждому клиенту и по каждому исходящему, с возможностью сброса.
|
- **Статистика трафика** — по каждому входящему, по каждому клиенту и по каждому исходящему, с возможностью сброса.
|
||||||
- **Поддержка нескольких узлов** — управление и масштабирование на несколько серверов из одной панели.
|
- **Поддержка нескольких узлов** — управление и масштабирование на несколько серверов из одной панели.
|
||||||
- **Исходящие подключения и маршрутизация** — WARP, NordVPN, пользовательские правила маршрутизации, балансировщики нагрузки и цепочки исходящих прокси.
|
- **Исходящие подключения и маршрутизация** — WARP, NordVPN, пользовательские правила маршрутизации, балансировщики нагрузки и цепочки исходящих прокси.
|
||||||
- **Встроенный сервер подписок** с несколькими форматами вывода.
|
- **Встроенный сервер подписок** с несколькими форматами вывода и [пользовательскими шаблонами страниц](docs/custom-subscription-templates.md).
|
||||||
- **Telegram-бот** для удалённого мониторинга и управления.
|
- **Telegram-бот** для удалённого мониторинга и управления.
|
||||||
- **RESTful API** с документацией Swagger внутри панели.
|
- **RESTful API** с документацией Swagger внутри панели.
|
||||||
- **Гибкое хранилище** — SQLite (по умолчанию) или PostgreSQL.
|
- **Гибкое хранилище** — SQLite (по умолчанию) или PostgreSQL.
|
||||||
@@ -73,10 +72,32 @@
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Чтобы установить конкретную версию, добавьте её тег (например, `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Чтобы установить скользящую **dev**-сборку (новейший предварительный релиз по каждому коммиту из ветки `main`, а не стабильный релиз), передайте `dev-latest`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
Во время установки генерируются случайные имя пользователя, пароль и путь доступа. После установки выполните `x-ui`, чтобы открыть меню управления, где можно запускать/останавливать сервис, просматривать или сбрасывать учётные данные для входа, управлять SSL-сертификатами и многое другое.
|
Во время установки генерируются случайные имя пользователя, пароль и путь доступа. После установки выполните `x-ui`, чтобы открыть меню управления, где можно запускать/останавливать сервис, просматривать или сбрасывать учётные данные для входа, управлять SSL-сертификатами и многое другое.
|
||||||
|
|
||||||
Полную документацию смотрите в [вики проекта](https://github.com/MHSanaei/3x-ui/wiki).
|
Полную документацию смотрите в [вики проекта](https://github.com/MHSanaei/3x-ui/wiki).
|
||||||
|
|
||||||
|
### Автоматическая установка
|
||||||
|
|
||||||
|
Установщик также работает в **неинтерактивном** режиме для cloud-init.
|
||||||
|
Задайте `XUI_NONINTERACTIVE=1` (или передайте по конвейеру без TTY), и установка пройдёт от начала до конца
|
||||||
|
без единого запроса: будут сгенерированы случайные учётные данные и записаны в
|
||||||
|
`/etc/x-ui/install-result.env`. Смотрите [`deploy/`](deploy/) для:
|
||||||
|
|
||||||
|
- [Cloud-init user-data](deploy/cloud-init/) — автоматическая установка в любом облаке (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [Заметки по Hetzner Cloud](deploy/marketplace/hetzner/) — развёртывание на Hetzner на базе cloud-init
|
||||||
|
|
||||||
## Поддерживаемые платформы
|
## Поддерживаемые платформы
|
||||||
|
|
||||||
**Операционные системы:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine и Windows.
|
**Операционные системы:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine и Windows.
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | Включить применение лимитов IP на основе Fail2ban | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | Включить применение лимитов IP на основе Fail2ban | `true` |
|
||||||
| `XUI_LOG_LEVEL` | Уровень логирования (`debug`, `info`, `warning`, `error`) | `info` |
|
| `XUI_LOG_LEVEL` | Уровень логирования (`debug`, `info`, `warning`, `error`) | `info` |
|
||||||
| `XUI_DEBUG` | Включить режим отладки | `false` |
|
| `XUI_DEBUG` | Включить режим отладки | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | Включить монитор состояния туннеля (опрашивает URL и перезапускает xray после многократных сбоев; перезапуск отключает всех клиентов) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | Прокси, через который отправляется проба; укажите локальный входящий xray, чтобы проба проверяла туннель (например, `socks5://127.0.0.1:1080`). Пустое значение означает, что проба проверяет только связь с хостом | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | 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` |
|
||||||
|
|
||||||
## Поддерживаемые языки
|
## Поддерживаемые языки
|
||||||
|
|
||||||
|
|||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI**, [Xray-core](https://github.com/XTLS/Xray-core) sunucularını yönetmek için geliştirilmiş profesyonel, açık kaynaklı bir web kontrol panelidir. Tek bir sanal sunucudan (VPS) çok düğümlü (multi-node) dağıtımlara kadar çok çeşitli proxy ve VPN protokollerini kurmak, yapılandırmak ve izlemek için temiz, çok dilli bir arayüz sağlar.
|
**3X-UI**, [Xray-core](https://github.com/XTLS/Xray-core) sunucularını yönetmek için geliştirilmiş profesyonel, açık kaynaklı bir web kontrol panelidir. Tek bir sanal sunucudan (VPS) çok düğümlü (multi-node) dağıtımlara kadar çok çeşitli proxy ve VPN protokollerini kurmak, yapılandırmak ve izlemek için temiz, çok dilli bir arayüz sağlar.
|
||||||
@@ -33,7 +32,7 @@ Orijinal X-UI projesinin geliştirilmiş bir çatallaması (fork) olarak inşa e
|
|||||||
- **Trafik istatistikleri** — Gelen bağlantı (Inbound), istemci ve giden bağlantı (Outbound) bazında istatistikler ve sıfırlama kontrolleri.
|
- **Trafik istatistikleri** — Gelen bağlantı (Inbound), istemci ve giden bağlantı (Outbound) bazında istatistikler ve sıfırlama kontrolleri.
|
||||||
- **Çoklu düğüm (Multi-node) desteği** — Tek bir panel üzerinden birden fazla sunucuyu yönetin ve ölçeklendirin.
|
- **Çoklu düğüm (Multi-node) desteği** — Tek bir panel üzerinden birden fazla sunucuyu yönetin ve ölçeklendirin.
|
||||||
- **Giden bağlantı (Outbound) ve yönlendirme** — WARP, NordVPN, özel yönlendirme kuralları, yük dengeleyiciler (load balancers) ve giden bağlantı proxy zincirleme (proxy chaining).
|
- **Giden bağlantı (Outbound) ve yönlendirme** — WARP, NordVPN, özel yönlendirme kuralları, yük dengeleyiciler (load balancers) ve giden bağlantı proxy zincirleme (proxy chaining).
|
||||||
- **Dahili abonelik sunucusu** (Birden fazla çıktı formatı ile).
|
- **Dahili abonelik sunucusu** (Birden fazla çıktı formatı ve [özel sayfa şablonları](docs/custom-subscription-templates.md) ile).
|
||||||
- Uzaktan izleme ve yönetim için **Telegram botu**.
|
- Uzaktan izleme ve yönetim için **Telegram botu**.
|
||||||
- Panel içi Swagger dokümantasyonuna sahip **RESTful API**.
|
- Panel içi Swagger dokümantasyonuna sahip **RESTful API**.
|
||||||
- **Esnek depolama** — SQLite (varsayılan) veya PostgreSQL.
|
- **Esnek depolama** — SQLite (varsayılan) veya PostgreSQL.
|
||||||
@@ -73,10 +72,32 @@ Orijinal X-UI projesinin geliştirilmiş bir çatallaması (fork) olarak inşa e
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Belirli bir sürümü kurmak için, etiketini (ör. `v3.4.0`) ekleyin:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Sürekli güncellenen **dev** sürümünü (kararlı bir sürüm değil; `main` dalından her commit'te oluşturulan en son ön sürüm) kurmak için `dev-latest` değerini geçirin:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
Kurulum sırasında rastgele bir kullanıcı adı, şifre ve erişim yolu oluşturulur. Kurulumdan sonra, hizmeti başlatabileceğiniz/durdurabileceğiniz, giriş bilgilerinizi görüntüleyebileceğiniz veya sıfırlayabileceğiniz, SSL sertifikalarını yönetebileceğiniz ve çok daha fazlasını yapabileceğiniz yönetim menüsünü açmak için terminalde `x-ui` komutunu çalıştırın.
|
Kurulum sırasında rastgele bir kullanıcı adı, şifre ve erişim yolu oluşturulur. Kurulumdan sonra, hizmeti başlatabileceğiniz/durdurabileceğiniz, giriş bilgilerinizi görüntüleyebileceğiniz veya sıfırlayabileceğiniz, SSL sertifikalarını yönetebileceğiniz ve çok daha fazlasını yapabileceğiniz yönetim menüsünü açmak için terminalde `x-ui` komutunu çalıştırın.
|
||||||
|
|
||||||
Tam dokümantasyon için lütfen [proje Wiki sayfasını](https://github.com/MHSanaei/3x-ui/wiki) ziyaret edin.
|
Tam dokümantasyon için lütfen [proje Wiki sayfasını](https://github.com/MHSanaei/3x-ui/wiki) ziyaret edin.
|
||||||
|
|
||||||
|
### Etkileşimsiz kurulum
|
||||||
|
|
||||||
|
Yükleyici, cloud-init için **etkileşimsiz** olarak da çalışır.
|
||||||
|
`XUI_NONINTERACTIVE=1` ayarlayın (veya TTY olmadan boru hattına aktarın); kurulum baştan
|
||||||
|
sona hiçbir soru sormadan tamamlanır, rastgele kimlik bilgileri oluşturup bunları
|
||||||
|
`/etc/x-ui/install-result.env` dosyasına yazar. Şunlar için [`deploy/`](deploy/) klasörüne bakın:
|
||||||
|
|
||||||
|
- [Cloud-init user-data](deploy/cloud-init/) — herhangi bir bulutta etkileşimsiz kurulum (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [Hetzner Cloud notları](deploy/marketplace/hetzner/) — Hetzner üzerinde cloud-init tabanlı dağıtım
|
||||||
|
|
||||||
## Desteklenen Platformlar
|
## Desteklenen Platformlar
|
||||||
|
|
||||||
**İşletim sistemleri:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine ve Windows.
|
**İşletim sistemleri:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine ve Windows.
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | Fail2ban tabanlı IP limit uygulamasını etkinleştir | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | Fail2ban tabanlı IP limit uygulamasını etkinleştir | `true` |
|
||||||
| `XUI_LOG_LEVEL` | Günlük (Log) ayrıntı seviyesi (`debug`, `info`, `warning`, `error`) | `info` |
|
| `XUI_LOG_LEVEL` | Günlük (Log) ayrıntı seviyesi (`debug`, `info`, `warning`, `error`) | `info` |
|
||||||
| `XUI_DEBUG` | Hata ayıklama (debug) modunu etkinleştir | `false` |
|
| `XUI_DEBUG` | Hata ayıklama (debug) modunu etkinleştir | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | Tünel sağlık izleyicisini etkinleştir (bir URL'yi yoklar ve tekrarlanan başarısızlıklardan sonra xray'i yeniden başlatır; yeniden başlatma tüm istemcilerin bağlantısını düşürür) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | Yoklamanın gönderildiği proxy; yoklamanın tüneli test etmesi için bunu yerel bir xray gelen bağlantısına yönlendirin (ör. `socks5://127.0.0.1:1080`). Boş bırakılırsa yoklama yalnızca ana makine bağlantısını kontrol eder | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | Tünel sağlığı için yoklanan URL | `https://www.cloudflare.com/cdn-cgi/trace` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_INTERVAL` | Yoklamalar arasındaki aralık | `30s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Yoklama başına zaman aşımı | `10s` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_FAILURES` | Yeniden başlatma tetiklenmeden önceki ardışık başarısızlık sayısı | `3` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Ardışık yeniden başlatmalar arasındaki minimum gecikme | `5m` |
|
||||||
|
|
||||||
## Desteklenen Diller
|
## Desteklenen Diller
|
||||||
|
|
||||||
|
|||||||
+30
-2
@@ -14,7 +14,6 @@
|
|||||||
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
<a href="https://github.com/MHSanaei/3x-ui/releases/latest"><img src="https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg" alt="Downloads"></a>
|
||||||
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
<a href="https://www.gnu.org/licenses/gpl-3.0.en.html"><img src="https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true" alt="License"></a>
|
||||||
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
<a href="https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3"><img src="https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg" alt="Go Reference"></a>
|
||||||
<a href="https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3"><img src="https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3" alt="Go Report Card"></a>
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**3X-UI** 是一个先进的开源 Web 控制面板,用于管理 [Xray-core](https://github.com/XTLS/Xray-core) 服务器。它提供简洁、多语言的界面,用于部署、配置和监控各种代理与 VPN 协议——从单台 VPS 到多节点部署。
|
**3X-UI** 是一个先进的开源 Web 控制面板,用于管理 [Xray-core](https://github.com/XTLS/Xray-core) 服务器。它提供简洁、多语言的界面,用于部署、配置和监控各种代理与 VPN 协议——从单台 VPS 到多节点部署。
|
||||||
@@ -33,7 +32,7 @@
|
|||||||
- **流量统计** — 按入站、按客户端、按出站统计,并支持重置控制。
|
- **流量统计** — 按入站、按客户端、按出站统计,并支持重置控制。
|
||||||
- **多节点支持** — 从单一面板管理并扩展到多台服务器。
|
- **多节点支持** — 从单一面板管理并扩展到多台服务器。
|
||||||
- **出站与路由** — WARP、NordVPN、自定义路由规则、负载均衡器和出站代理链。
|
- **出站与路由** — WARP、NordVPN、自定义路由规则、负载均衡器和出站代理链。
|
||||||
- **内置订阅服务器**,支持多种输出格式。
|
- **内置订阅服务器**,支持多种输出格式和[自定义页面模板](docs/custom-subscription-templates.md)。
|
||||||
- **Telegram 机器人**,用于远程监控和管理。
|
- **Telegram 机器人**,用于远程监控和管理。
|
||||||
- **RESTful API**,带有面板内置的 Swagger 文档。
|
- **RESTful API**,带有面板内置的 Swagger 文档。
|
||||||
- **灵活的存储** — SQLite(默认)或 PostgreSQL。
|
- **灵活的存储** — SQLite(默认)或 PostgreSQL。
|
||||||
@@ -73,10 +72,32 @@
|
|||||||
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
若要安装特定版本,请在命令后附加对应的标签(例如 `v3.4.0`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
|
||||||
|
```
|
||||||
|
|
||||||
|
若要安装滚动更新的 **dev** 版本(来自 `main` 的最新逐次提交预发布版本,而非稳定版本),请传入 `dev-latest`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
|
||||||
|
```
|
||||||
|
|
||||||
安装过程中会生成随机的用户名、密码和访问路径。安装完成后,运行 `x-ui` 打开管理菜单,您可以在其中启动/停止服务、查看或重置登录凭据、管理 SSL 证书等。
|
安装过程中会生成随机的用户名、密码和访问路径。安装完成后,运行 `x-ui` 打开管理菜单,您可以在其中启动/停止服务、查看或重置登录凭据、管理 SSL 证书等。
|
||||||
|
|
||||||
完整文档请参阅 [项目Wiki](https://github.com/MHSanaei/3x-ui/wiki)。
|
完整文档请参阅 [项目Wiki](https://github.com/MHSanaei/3x-ui/wiki)。
|
||||||
|
|
||||||
|
### 无人值守安装
|
||||||
|
|
||||||
|
安装程序也可以**非交互式**运行,适用于 cloud-init。
|
||||||
|
设置 `XUI_NONINTERACTIVE=1`(或在无 TTY 的情况下通过管道传入),它就会全程
|
||||||
|
零提示地完成端到端安装,生成随机凭据并写入
|
||||||
|
`/etc/x-ui/install-result.env`。请参阅 [`deploy/`](deploy/):
|
||||||
|
|
||||||
|
- [Cloud-init user-data](deploy/cloud-init/) — 在任意云平台上无人值守安装(Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
|
||||||
|
- [Hetzner Cloud 说明](deploy/marketplace/hetzner/) — 在 Hetzner 上基于 cloud-init 的部署
|
||||||
|
|
||||||
## 支持的平台
|
## 支持的平台
|
||||||
|
|
||||||
**操作系统:** Ubuntu、Debian、Armbian、Fedora、CentOS、RHEL、AlmaLinux、Rocky Linux、Oracle Linux、Amazon Linux、Virtuozzo、Arch、Manjaro、Parch、openSUSE (Tumbleweed / Leap)、Alpine 和 Windows。
|
**操作系统:** Ubuntu、Debian、Armbian、Fedora、CentOS、RHEL、AlmaLinux、Rocky Linux、Oracle Linux、Amazon Linux、Virtuozzo、Arch、Manjaro、Parch、openSUSE (Tumbleweed / Leap)、Alpine 和 Windows。
|
||||||
@@ -134,6 +155,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
|
|||||||
| `XUI_ENABLE_FAIL2BAN` | 启用基于 Fail2ban 的 IP 限制 | `true` |
|
| `XUI_ENABLE_FAIL2BAN` | 启用基于 Fail2ban 的 IP 限制 | `true` |
|
||||||
| `XUI_LOG_LEVEL` | 日志级别(`debug`、`info`、`warning`、`error`) | `info` |
|
| `XUI_LOG_LEVEL` | 日志级别(`debug`、`info`、`warning`、`error`) | `info` |
|
||||||
| `XUI_DEBUG` | 启用调试模式 | `false` |
|
| `XUI_DEBUG` | 启用调试模式 | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_MONITOR` | 启用隧道健康监控(探测某个 URL,在连续多次失败后重启 xray;重启会断开所有客户端) | `false` |
|
||||||
|
| `XUI_TUNNEL_HEALTH_PROXY` | 探测请求所经过的代理;将其指向本地 xray 入站,使探测能够测试隧道(例如 `socks5://127.0.0.1:1080`)。留空表示探测仅检查主机连通性 | — |
|
||||||
|
| `XUI_TUNNEL_HEALTH_URL` | 用于检测隧道健康状况的探测 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` |
|
||||||
|
|
||||||
## 支持的语言
|
## 支持的语言
|
||||||
|
|
||||||
|
|||||||
+9
-16
@@ -1,27 +1,20 @@
|
|||||||
# Cloud deployment & golden images
|
# Cloud deployment (unattended install)
|
||||||
|
|
||||||
Tooling to ship the 3x-ui panel as a cloud image or via unattended install,
|
Tooling to ship the 3x-ui panel via unattended install, with **per-instance
|
||||||
with **per-instance credentials generated on first boot** (never `admin/admin`,
|
credentials generated on first boot** (never `admin/admin`, never a shared
|
||||||
never a shared session secret). Everything here supports **amd64 and arm64**.
|
session secret). Works on amd64 and arm64.
|
||||||
|
|
||||||
| Path | What it is | Use when |
|
| Path | What it is | Use when |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| [`cloud-init/`](cloud-init/) | Generic cloud-init user-data (unattended `install.sh`) | Any cloud, no image build |
|
| [`cloud-init/`](cloud-init/) | Generic cloud-init user-data (unattended `install.sh`) | Any cloud, no image build |
|
||||||
| [`packer/`](packer/) | Packer build → AWS AMI + qcow2/raw | Reusable / Marketplace images |
|
|
||||||
| [`lightsail/`](lightsail/) | Launch script + snapshot builder | Amazon Lightsail |
|
|
||||||
| [`firstboot/`](firstboot/) | First-boot unit + script that mints per-instance creds | Used by the Packer/Lightsail images |
|
|
||||||
| [`marketplace/aws/`](marketplace/aws/) | AWS Marketplace submission checklist | Publishing an EC2 AMI |
|
|
||||||
| [`marketplace/hetzner/`](marketplace/hetzner/) | Hetzner Cloud notes | Hetzner deployments |
|
| [`marketplace/hetzner/`](marketplace/hetzner/) | Hetzner Cloud notes | Hetzner deployments |
|
||||||
| [`test/`](test/) | Container smoke tests | Verifying the install/firstboot paths |
|
| [`test/`](test/) | Container smoke test | Verifying the install path |
|
||||||
|
|
||||||
## Two models
|
## How it works
|
||||||
|
|
||||||
- **Non-interactive install (cloud-init):** `install.sh` runs unattended when
|
`install.sh` runs unattended when `XUI_NONINTERACTIVE=1` or stdin is not a TTY.
|
||||||
`XUI_NONINTERACTIVE=1` or stdin is not a TTY. Each instance installs and
|
Each instance installs and configures itself with random credentials. See
|
||||||
configures itself with random credentials. See [`cloud-init/README.md`](cloud-init/README.md).
|
[`cloud-init/README.md`](cloud-init/README.md).
|
||||||
- **Golden image (Packer):** the image contains the panel but **no DB and no
|
|
||||||
secrets**; `firstboot` generates unique credentials on first boot. See
|
|
||||||
[`packer/README.md`](packer/README.md).
|
|
||||||
|
|
||||||
## Unattended install knobs
|
## Unattended install knobs
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
# 3x-ui via cloud-init (generic, no golden image)
|
# 3x-ui via cloud-init
|
||||||
|
|
||||||
This is the **secondary** deployment path: a single [`cloud-init.yaml`](cloud-init.yaml)
|
A single [`cloud-init.yaml`](cloud-init.yaml) user-data file that installs 3x-ui
|
||||||
user-data file that installs 3x-ui non-interactively on a fresh Ubuntu/Debian
|
non-interactively on a fresh Ubuntu/Debian VM and generates **unique random
|
||||||
VM and generates **unique random credentials per instance**. Use it when you do
|
credentials per instance**. It works on any cloud-init platform.
|
||||||
not want to build a golden image — it works on any cloud-init platform.
|
|
||||||
|
|
||||||
> For AWS Marketplace / reusable images, use the Packer build in
|
|
||||||
> [`../packer/`](../packer/) instead.
|
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
|
|
||||||
@@ -53,7 +49,6 @@ Edit the `export XUI_*` lines inside the `write_files` block of
|
|||||||
`hcloud server create --image ubuntu-24.04 --user-data-from-file cloud-init.yaml ...`
|
`hcloud server create --image ubuntu-24.04 --user-data-from-file cloud-init.yaml ...`
|
||||||
- **AWS EC2** — *Advanced details → User data*: paste the file. Or
|
- **AWS EC2** — *Advanced details → User data*: paste the file. Or
|
||||||
`aws ec2 run-instances --user-data file://cloud-init.yaml ...`
|
`aws ec2 run-instances --user-data file://cloud-init.yaml ...`
|
||||||
(For a reusable Marketplace image use the Packer AMI build instead.)
|
|
||||||
- **DigitalOcean** — *Create Droplet → Advanced options → Add Initialization
|
- **DigitalOcean** — *Create Droplet → Advanced options → Add Initialization
|
||||||
scripts (user data)*: paste the file. Or `doctl compute droplet create --user-data-file cloud-init.yaml ...`
|
scripts (user data)*: paste the file. Or `doctl compute droplet create --user-data-file cloud-init.yaml ...`
|
||||||
- **Vultr** — *Deploy → Additional Features → Cloud-Init User-Data*: paste the file.
|
- **Vultr** — *Deploy → Additional Features → Cloud-Init User-Data*: paste the file.
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=3x-ui first-boot per-instance credential generation
|
|
||||||
Documentation=https://github.com/MHSanaei/3x-ui
|
|
||||||
# Run after the network and cloud-init are up, but BEFORE the panel starts, so
|
|
||||||
# the panel never serves the default admin/admin account.
|
|
||||||
After=network-online.target cloud-init.service
|
|
||||||
Wants=network-online.target
|
|
||||||
Before=x-ui.service
|
|
||||||
# Skip entirely once the sentinel exists (cheap guard; the script re-checks too).
|
|
||||||
ConditionPathExists=!/etc/x-ui/.firstboot-done
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
RemainAfterExit=yes
|
|
||||||
# Inherit the same DB configuration the panel uses (sqlite default / postgres).
|
|
||||||
EnvironmentFile=-/etc/default/x-ui
|
|
||||||
EnvironmentFile=-/etc/conf.d/x-ui
|
|
||||||
EnvironmentFile=-/etc/sysconfig/x-ui
|
|
||||||
ExecStart=/usr/local/x-ui/x-ui-firstboot.sh
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# x-ui-firstboot.sh — generate per-instance 3x-ui panel credentials on first boot.
|
|
||||||
#
|
|
||||||
# A golden image (AMI / qcow2) MUST ship without an initialized x-ui.db: the
|
|
||||||
# panel seeds a hardcoded admin/admin user and generates its session secret +
|
|
||||||
# panel GUID on first start, so a baked DB would make every clone share the same
|
|
||||||
# credentials and secret. This script runs ONCE, before x-ui.service starts, and
|
|
||||||
# replaces the default admin with fresh random credentials on a random high port.
|
|
||||||
#
|
|
||||||
# Idempotent: a sentinel file guards against re-running. If a non-default admin
|
|
||||||
# already exists (operator pre-configured the box), regeneration is skipped.
|
|
||||||
#
|
|
||||||
# Wired up by deploy/packer/scripts/provision.sh; ordered Before=x-ui.service.
|
|
||||||
|
|
||||||
set -u
|
|
||||||
|
|
||||||
SENTINEL="/etc/x-ui/.firstboot-done"
|
|
||||||
CRED_FILE="/etc/x-ui/credentials.txt"
|
|
||||||
MOTD_FILE="/etc/motd"
|
|
||||||
XUI_DIR="${XUI_MAIN_FOLDER:-/usr/local/x-ui}"
|
|
||||||
XUI_BIN="${XUI_DIR}/x-ui"
|
|
||||||
|
|
||||||
log() { echo "[x-ui-firstboot] $*"; }
|
|
||||||
|
|
||||||
# Already provisioned — nothing to do (idempotent on re-run / re-image).
|
|
||||||
if [ -f "$SENTINEL" ]; then
|
|
||||||
log "sentinel $SENTINEL present; skipping."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ ! -x "$XUI_BIN" ]; then
|
|
||||||
log "ERROR: x-ui binary not found at $XUI_BIN"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Inherit DB configuration (sqlite default; postgres via XUI_DB_TYPE/XUI_DB_DSN)
|
|
||||||
# from the same env files the systemd unit loads, so the binary talks to the
|
|
||||||
# same database the panel will use.
|
|
||||||
for ef in /etc/default/x-ui /etc/conf.d/x-ui /etc/sysconfig/x-ui; do
|
|
||||||
if [ -r "$ef" ]; then
|
|
||||||
set -a
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
. "$ef"
|
|
||||||
set +a
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
install -d -m 755 /etc/x-ui 2> /dev/null || true
|
|
||||||
|
|
||||||
# Defense-in-depth: make sure the panel is not running while we mutate the DB.
|
|
||||||
if command -v systemctl > /dev/null 2>&1; then
|
|
||||||
systemctl stop x-ui > /dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
gen_random_string() {
|
|
||||||
local length="$1"
|
|
||||||
openssl rand -base64 $((length * 2)) | tr -dc 'a-zA-Z0-9' | head -c "$length"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Best-effort public IPv4 for the displayed access URL (cosmetic only — the
|
|
||||||
# panel binds 0.0.0.0). Falls back to the primary local IP, then a placeholder.
|
|
||||||
detect_ip() {
|
|
||||||
local ip=""
|
|
||||||
local url
|
|
||||||
for url in https://api4.ipify.org https://ipv4.icanhazip.com https://4.ident.me; do
|
|
||||||
ip=$(curl -fsS4 --max-time 3 "$url" 2> /dev/null | tr -d '[:space:]')
|
|
||||||
if [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
|
||||||
echo "$ip"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
ip=$(hostname -I 2> /dev/null | awk '{print $1}')
|
|
||||||
if [ -n "$ip" ]; then
|
|
||||||
echo "$ip"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
echo "<server-ip>"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Detect whether the seeded admin/admin default is still in place.
|
|
||||||
default_creds=$("$XUI_BIN" setting -show true 2> /dev/null | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
|
|
||||||
|
|
||||||
# The parse MUST yield exactly "true" or "false". If the command failed or its
|
|
||||||
# output format changed, refuse to proceed: do NOT write the sentinel, so the
|
|
||||||
# next boot retries instead of silently leaving admin/admin in place.
|
|
||||||
if [ "$default_creds" != "true" ] && [ "$default_creds" != "false" ]; then
|
|
||||||
log "ERROR: could not determine credential state (hasDefaultCredential='${default_creds}'); not writing sentinel, will retry next boot."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$default_creds" = "false" ]; then
|
|
||||||
log "non-default admin already configured; skipping credential regeneration."
|
|
||||||
{
|
|
||||||
echo "3x-ui first-boot: a non-default admin account already exists on this"
|
|
||||||
echo "instance, so credentials were left unchanged."
|
|
||||||
} > "$MOTD_FILE" 2> /dev/null || true
|
|
||||||
: > "$SENTINEL" 2> /dev/null || true
|
|
||||||
chmod 600 "$SENTINEL" 2> /dev/null || true
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "generating per-instance credentials..."
|
|
||||||
|
|
||||||
NEW_USER="${XUI_USERNAME:-$(gen_random_string 10)}"
|
|
||||||
NEW_PASS="${XUI_PASSWORD:-$(gen_random_string 16)}"
|
|
||||||
NEW_PATH="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
|
|
||||||
NEW_PORT="${XUI_PANEL_PORT:-$(shuf -i 1024-62000 -n 1)}"
|
|
||||||
|
|
||||||
# Clean settings slate: drops any baked port/webBasePath and forces the panel
|
|
||||||
# to regenerate its session secret + panel GUID on next start (per-instance).
|
|
||||||
"$XUI_BIN" setting -reset > /dev/null 2>&1 || true
|
|
||||||
|
|
||||||
# Apply fresh random identity. UpdateFirstUser renames the seeded admin row and
|
|
||||||
# rehashes the password, so admin/admin no longer exists after this call.
|
|
||||||
if ! "$XUI_BIN" setting -username "$NEW_USER" -password "$NEW_PASS" -port "$NEW_PORT" -webBasePath "$NEW_PATH" > /dev/null 2>&1; then
|
|
||||||
log "ERROR: failed to apply new panel settings."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
API_TOKEN=$("$XUI_BIN" setting -getApiToken true 2> /dev/null | grep -Eo 'apiToken: .+' | awk '{print $2}')
|
|
||||||
SERVER_IP=$(detect_ip)
|
|
||||||
ACCESS_URL="http://${SERVER_IP}:${NEW_PORT}/${NEW_PATH}"
|
|
||||||
|
|
||||||
# Persist credentials for the operator (root-only). Values are shell-escaped
|
|
||||||
# with %q so the file stays safe to `source` even if a value contains shell
|
|
||||||
# metacharacters (the smoke test and operators source this file).
|
|
||||||
umask 077
|
|
||||||
{
|
|
||||||
echo "# 3x-ui per-instance credentials (generated on first boot)"
|
|
||||||
printf 'XUI_USERNAME=%q\n' "$NEW_USER"
|
|
||||||
printf 'XUI_PASSWORD=%q\n' "$NEW_PASS"
|
|
||||||
printf 'XUI_PANEL_PORT=%q\n' "$NEW_PORT"
|
|
||||||
printf 'XUI_WEB_BASE_PATH=%q\n' "$NEW_PATH"
|
|
||||||
printf 'XUI_ACCESS_URL=%q\n' "$ACCESS_URL"
|
|
||||||
printf 'XUI_API_TOKEN=%q\n' "$API_TOKEN"
|
|
||||||
} > "$CRED_FILE"
|
|
||||||
chmod 600 "$CRED_FILE" 2> /dev/null || true
|
|
||||||
|
|
||||||
# Friendly login banner shown on SSH / console before the panel is reachable.
|
|
||||||
# /etc/motd is world-readable, so it MUST NOT contain the password or API token;
|
|
||||||
# those secrets live only in ${CRED_FILE} (mode 600). Show non-secret info only.
|
|
||||||
cat > "$MOTD_FILE" 2> /dev/null << EOF
|
|
||||||
|
|
||||||
========================================================================
|
|
||||||
3x-ui panel — per-instance credentials (generated on first boot)
|
|
||||||
========================================================================
|
|
||||||
Access URL : ${ACCESS_URL}
|
|
||||||
Username : ${NEW_USER}
|
|
||||||
|
|
||||||
The password and API token are NOT shown here (this banner is
|
|
||||||
world-readable). Read them as root with:
|
|
||||||
sudo cat ${CRED_FILE}
|
|
||||||
|
|
||||||
Change the password after login. If no public IP is shown above,
|
|
||||||
replace <server-ip> with the address you reach this server on.
|
|
||||||
========================================================================
|
|
||||||
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# Mark complete so we never regenerate on subsequent boots.
|
|
||||||
: > "$SENTINEL" 2> /dev/null || true
|
|
||||||
chmod 600 "$SENTINEL" 2> /dev/null || true
|
|
||||||
|
|
||||||
log "done. Panel will start on port ${NEW_PORT} with a unique admin account."
|
|
||||||
exit 0
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
# 3x-ui on Amazon Lightsail
|
|
||||||
|
|
||||||
Two self-service ways to run 3x-ui on Lightsail, both producing **unique
|
|
||||||
per-instance credentials** (never `admin/admin`, never a shared secret).
|
|
||||||
|
|
||||||
> **Reality check.** The Lightsail *blueprint* list (WordPress, LAMP, GitLab…)
|
|
||||||
> is curated by AWS — you **cannot** self-publish your panel there, and Lightsail
|
|
||||||
> **cannot** launch from an arbitrary EC2 AMI. What you *can* do yourself is the
|
|
||||||
> two paths below. (For a public AWS listing you'd use the EC2 **AMI** +
|
|
||||||
> Marketplace path in [`../marketplace/aws/`](../marketplace/aws/), which is a
|
|
||||||
> different product from Lightsail.)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Path A — launch script (simplest, self-service)
|
|
||||||
|
|
||||||
Install on a fresh instance at creation time. No image to build.
|
|
||||||
|
|
||||||
1. **Create instance** → platform **Linux/Unix** → blueprint **OS Only → Ubuntu 24.04**.
|
|
||||||
2. **Add launch script** → paste [`launch-script.sh`](launch-script.sh).
|
|
||||||
3. Create the instance.
|
|
||||||
4. After it boots, read the credentials:
|
|
||||||
```bash
|
|
||||||
ssh ubuntu@<public-ip> 'sudo cat /etc/x-ui/install-result.env'
|
|
||||||
```
|
|
||||||
5. **Open the panel port** (see the firewall note below) and log in.
|
|
||||||
|
|
||||||
CLI equivalent:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
aws lightsail create-instances \
|
|
||||||
--instance-names my-3xui \
|
|
||||||
--availability-zone eu-central-1a \
|
|
||||||
--blueprint-id ubuntu_24_04 \
|
|
||||||
--bundle-id small_3_0 \
|
|
||||||
--user-data file://deploy/lightsail/launch-script.sh \
|
|
||||||
--region eu-central-1
|
|
||||||
```
|
|
||||||
|
|
||||||
By default the panel uses a **random** high port (in `install-result.env`). To
|
|
||||||
pin a known port so you can pre-open it, set `export XUI_PANEL_PORT=54321` inside
|
|
||||||
`launch-script.sh`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Path B — reusable snapshot (your own "ready image")
|
|
||||||
|
|
||||||
Build a Lightsail **snapshot** once; launch as many instances from it as you
|
|
||||||
like, each generating its own credentials on first boot (the golden-image model).
|
|
||||||
|
|
||||||
```bash
|
|
||||||
deploy/lightsail/build-snapshot.sh --region eu-central-1 --panel-port 54321
|
|
||||||
```
|
|
||||||
|
|
||||||
What it does: launches a temporary Ubuntu instance with
|
|
||||||
[`snapshot-userdata.sh`](snapshot-userdata.sh) (installs the panel, **no DB**,
|
|
||||||
enables the first-boot unit), strips all state via the shared
|
|
||||||
[`cleanup.sh`](../packer/scripts/cleanup.sh), then snapshots and deletes the
|
|
||||||
build instance. Requires `awscli`, `jq`, `ssh` and Lightsail permissions.
|
|
||||||
|
|
||||||
Launch instances from the snapshot:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
aws lightsail create-instances-from-snapshot \
|
|
||||||
--instance-snapshot-name 3x-ui-ubuntu-24.04-<stamp> \
|
|
||||||
--instance-names my-3xui-1 --bundle-id small_3_0 \
|
|
||||||
--availability-zone eu-central-1a --region eu-central-1
|
|
||||||
```
|
|
||||||
|
|
||||||
Each launched instance runs `x-ui-firstboot` and writes its unique credentials to
|
|
||||||
`/etc/x-ui/credentials.txt` + `/etc/motd`. With `--panel-port` the port is the
|
|
||||||
same across instances (only the credentials differ), so you can pre-open it.
|
|
||||||
|
|
||||||
> Lightsail snapshots are **private to your AWS account** (and region). To use one
|
|
||||||
> elsewhere you can export it to EC2 (`aws lightsail export-snapshot`) and share
|
|
||||||
> the resulting AMI.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Lightsail firewall note (important)
|
|
||||||
|
|
||||||
Lightsail's per-instance firewall only opens **22 / 80 / 443** by default. The
|
|
||||||
panel runs on a different port, so you must open it:
|
|
||||||
|
|
||||||
- Console: instance → **Networking → IPv4 Firewall → Add rule** (TCP, the panel port).
|
|
||||||
- CLI:
|
|
||||||
```bash
|
|
||||||
aws lightsail open-instance-public-ports --region eu-central-1 \
|
|
||||||
--instance-name my-3xui \
|
|
||||||
--port-info fromPort=54321,toPort=54321,protocol=TCP
|
|
||||||
```
|
|
||||||
|
|
||||||
The panel port is in `/etc/x-ui/install-result.env` (Path A) or
|
|
||||||
`/etc/x-ui/credentials.txt` (Path B), or fixed via `--panel-port` / `XUI_PANEL_PORT`.
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# build-snapshot.sh — build a reusable Amazon Lightsail snapshot of 3x-ui.
|
|
||||||
#
|
|
||||||
# Flow (mirrors the Packer golden-image model, via the Lightsail API):
|
|
||||||
# 1. create an Ubuntu Lightsail instance with snapshot-userdata.sh
|
|
||||||
# (installs the panel, NO database, enables the first-boot unit)
|
|
||||||
# 2. wait for provisioning, then (optionally) pin a known panel port and run
|
|
||||||
# the shared cleanup.sh (wipes any DB/creds/keys/host-keys/cloud-init state)
|
|
||||||
# 3. stop the instance and create an instance snapshot
|
|
||||||
# 4. delete the build instance (unless --keep-instance)
|
|
||||||
#
|
|
||||||
# Every instance you later launch from the snapshot generates its OWN unique
|
|
||||||
# credentials on first boot (see deploy/firstboot/). The snapshot is private to
|
|
||||||
# your AWS account.
|
|
||||||
#
|
|
||||||
# Requirements: awscli v2, jq, ssh. AWS credentials with Lightsail permissions.
|
|
||||||
# Usage:
|
|
||||||
# deploy/lightsail/build-snapshot.sh --region eu-central-1 [options]
|
|
||||||
# Options:
|
|
||||||
# --region <r> AWS region (default: $AWS_REGION or eu-central-1)
|
|
||||||
# --blueprint-id <id> Lightsail blueprint (default: ubuntu_24_04)
|
|
||||||
# --bundle-id <id> Lightsail bundle/size (default: small_3_0)
|
|
||||||
# --availability-zone <z> AZ (default: <region>a)
|
|
||||||
# --panel-port <p> Pin the panel port in the snapshot so you can pre-open
|
|
||||||
# it in the Lightsail firewall (default: random per instance)
|
|
||||||
# --snapshot-name <n> Snapshot name (default: 3x-ui-ubuntu-24.04-<timestamp>)
|
|
||||||
# --keep-instance Do not delete the build instance afterwards
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
REGION="${AWS_REGION:-eu-central-1}"
|
|
||||||
BLUEPRINT="ubuntu_24_04"
|
|
||||||
BUNDLE="small_3_0"
|
|
||||||
AZ=""
|
|
||||||
PANEL_PORT=""
|
|
||||||
SNAPSHOT_NAME=""
|
|
||||||
KEEP_INSTANCE=0
|
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
||||||
STAMP="$(date +%Y%m%d-%H%M%S)"
|
|
||||||
INSTANCE_NAME="3xui-build-${STAMP}"
|
|
||||||
KEY_FILE=""
|
|
||||||
|
|
||||||
log() { echo "[build-snapshot] $*"; }
|
|
||||||
die() {
|
|
||||||
echo "[build-snapshot] ERROR: $*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
while [ $# -gt 0 ]; do
|
|
||||||
case "$1" in
|
|
||||||
--region) REGION="$2"; shift 2 ;;
|
|
||||||
--blueprint-id) BLUEPRINT="$2"; shift 2 ;;
|
|
||||||
--bundle-id) BUNDLE="$2"; shift 2 ;;
|
|
||||||
--availability-zone) AZ="$2"; shift 2 ;;
|
|
||||||
--panel-port) PANEL_PORT="$2"; shift 2 ;;
|
|
||||||
--snapshot-name) SNAPSHOT_NAME="$2"; shift 2 ;;
|
|
||||||
--keep-instance) KEEP_INSTANCE=1; shift ;;
|
|
||||||
-h | --help) sed -n '2,40p' "$0"; exit 0 ;;
|
|
||||||
*) die "unknown option: $1" ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
[ -n "$AZ" ] || AZ="${REGION}a"
|
|
||||||
[ -n "$SNAPSHOT_NAME" ] || SNAPSHOT_NAME="3x-ui-ubuntu-24.04-${STAMP}"
|
|
||||||
|
|
||||||
for cmd in aws jq ssh; do
|
|
||||||
command -v "$cmd" > /dev/null 2>&1 || die "'$cmd' is required"
|
|
||||||
done
|
|
||||||
|
|
||||||
SSH_OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o LogLevel=ERROR)
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
[ -n "$KEY_FILE" ] && rm -f "$KEY_FILE"
|
|
||||||
if [ "$KEEP_INSTANCE" -eq 0 ]; then
|
|
||||||
aws lightsail delete-instance --instance-name "$INSTANCE_NAME" --region "$REGION" > /dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
trap cleanup EXIT
|
|
||||||
|
|
||||||
wait_state() {
|
|
||||||
local want="$1" tries="${2:-60}" st
|
|
||||||
for _ in $(seq 1 "$tries"); do
|
|
||||||
st=$(aws lightsail get-instance-state --instance-name "$INSTANCE_NAME" --region "$REGION" \
|
|
||||||
--query 'state.name' --output text 2> /dev/null || echo "")
|
|
||||||
[ "$st" = "$want" ] && return 0
|
|
||||||
sleep 5
|
|
||||||
done
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
log "creating build instance ${INSTANCE_NAME} (${BLUEPRINT}/${BUNDLE}) in ${REGION}..."
|
|
||||||
aws lightsail create-instances \
|
|
||||||
--instance-names "$INSTANCE_NAME" \
|
|
||||||
--availability-zone "$AZ" \
|
|
||||||
--blueprint-id "$BLUEPRINT" \
|
|
||||||
--bundle-id "$BUNDLE" \
|
|
||||||
--user-data "file://${SCRIPT_DIR}/snapshot-userdata.sh" \
|
|
||||||
--region "$REGION" > /dev/null
|
|
||||||
|
|
||||||
log "waiting for instance to run..."
|
|
||||||
wait_state running 60 || die "instance did not reach 'running'"
|
|
||||||
|
|
||||||
IP=$(aws lightsail get-instance --instance-name "$INSTANCE_NAME" --region "$REGION" \
|
|
||||||
--query 'instance.publicIpAddress' --output text)
|
|
||||||
if [ -z "$IP" ] || [ "$IP" = "None" ]; then die "no public IP"; fi
|
|
||||||
log "instance IP: ${IP}"
|
|
||||||
|
|
||||||
KEY_FILE="$(mktemp)"
|
|
||||||
# download-default-key-pair returns the key in 'privateKeyBase64'. Despite the
|
|
||||||
# name, the CLI historically emits the plaintext PEM (-----BEGIN...); the API
|
|
||||||
# docs describe it as base64. Handle both: write PEM as-is, else base64-decode.
|
|
||||||
KEY_RAW="$(aws lightsail download-default-key-pair --region "$REGION" \
|
|
||||||
--query 'privateKeyBase64' --output text)"
|
|
||||||
[ -n "$KEY_RAW" ] && [ "$KEY_RAW" != "None" ] || die "failed to download default key pair"
|
|
||||||
case "$KEY_RAW" in
|
|
||||||
*-----BEGIN*) printf '%s\n' "$KEY_RAW" > "$KEY_FILE" ;;
|
|
||||||
*) printf '%s' "$KEY_RAW" | base64 -d > "$KEY_FILE" 2> /dev/null \
|
|
||||||
|| die "private key is neither PEM nor valid base64" ;;
|
|
||||||
esac
|
|
||||||
grep -q -- "-----BEGIN" "$KEY_FILE" || die "downloaded key is not a valid PEM private key"
|
|
||||||
chmod 600 "$KEY_FILE"
|
|
||||||
|
|
||||||
log "waiting for provisioning to finish (this installs the panel)..."
|
|
||||||
ok=0
|
|
||||||
for _ in $(seq 1 72); do # ~12 min
|
|
||||||
if ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
|
|
||||||
'test -f /var/lib/3xui-provision-done' 2> /dev/null; then
|
|
||||||
ok=1
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
sleep 10
|
|
||||||
done
|
|
||||||
[ "$ok" -eq 1 ] || die "provisioning did not complete in time"
|
|
||||||
log "provisioning complete."
|
|
||||||
|
|
||||||
if [ -n "$PANEL_PORT" ]; then
|
|
||||||
log "pinning panel port ${PANEL_PORT} (username/password stay random)..."
|
|
||||||
ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
|
|
||||||
"echo 'XUI_PANEL_PORT=${PANEL_PORT}' | sudo tee -a /etc/default/x-ui >/dev/null"
|
|
||||||
fi
|
|
||||||
|
|
||||||
log "stripping instance state (shared cleanup.sh)..."
|
|
||||||
ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
|
|
||||||
'curl -fsSL https://raw.githubusercontent.com/MHSanaei/3x-ui/main/deploy/packer/scripts/cleanup.sh | sudo bash'
|
|
||||||
|
|
||||||
log "stopping instance..."
|
|
||||||
aws lightsail stop-instance --instance-name "$INSTANCE_NAME" --region "$REGION" > /dev/null
|
|
||||||
wait_state stopped 60 || die "instance did not stop"
|
|
||||||
|
|
||||||
log "creating snapshot ${SNAPSHOT_NAME}..."
|
|
||||||
aws lightsail create-instance-snapshot \
|
|
||||||
--instance-name "$INSTANCE_NAME" \
|
|
||||||
--instance-snapshot-name "$SNAPSHOT_NAME" \
|
|
||||||
--region "$REGION" > /dev/null
|
|
||||||
|
|
||||||
log "waiting for snapshot to become available..."
|
|
||||||
snap_ok=0
|
|
||||||
for _ in $(seq 1 120); do # ~20 min
|
|
||||||
state=$(aws lightsail get-instance-snapshot --instance-snapshot-name "$SNAPSHOT_NAME" \
|
|
||||||
--region "$REGION" --query 'instanceSnapshot.state' --output text 2> /dev/null || echo "")
|
|
||||||
[ "$state" = "available" ] && {
|
|
||||||
snap_ok=1
|
|
||||||
break
|
|
||||||
}
|
|
||||||
sleep 10
|
|
||||||
done
|
|
||||||
[ "$snap_ok" -eq 1 ] || die "snapshot did not become available"
|
|
||||||
|
|
||||||
log "DONE."
|
|
||||||
echo
|
|
||||||
echo "================================================================"
|
|
||||||
echo " Lightsail snapshot ready: ${SNAPSHOT_NAME} (region ${REGION})"
|
|
||||||
echo "================================================================"
|
|
||||||
echo " Launch an instance from it:"
|
|
||||||
echo " aws lightsail create-instances-from-snapshot \\"
|
|
||||||
echo " --instance-snapshot-name ${SNAPSHOT_NAME} \\"
|
|
||||||
echo " --instance-names my-3xui-1 --bundle-id ${BUNDLE} \\"
|
|
||||||
echo " --availability-zone ${AZ} --region ${REGION}"
|
|
||||||
if [ -n "$PANEL_PORT" ]; then
|
|
||||||
echo
|
|
||||||
echo " Then open the panel port (pinned to ${PANEL_PORT}):"
|
|
||||||
echo " aws lightsail open-instance-public-ports --region ${REGION} \\"
|
|
||||||
echo " --instance-name my-3xui-1 \\"
|
|
||||||
echo " --port-info fromPort=${PANEL_PORT},toPort=${PANEL_PORT},protocol=TCP"
|
|
||||||
else
|
|
||||||
echo
|
|
||||||
echo " Each instance picks a RANDOM panel port. After it boots, read it from"
|
|
||||||
echo " sudo cat /etc/x-ui/credentials.txt"
|
|
||||||
echo " and open that TCP port in the instance's Lightsail IPv4 firewall."
|
|
||||||
fi
|
|
||||||
echo "================================================================"
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Amazon Lightsail launch script for 3x-ui (self-service, per-instance creds).
|
|
||||||
#
|
|
||||||
# Use it one of two ways when creating an Ubuntu 24.04 Lightsail instance:
|
|
||||||
# * Console: "Add launch script" -> paste this file.
|
|
||||||
# * CLI: aws lightsail create-instances --user-data file://launch-script.sh ...
|
|
||||||
#
|
|
||||||
# It installs the latest 3x-ui release non-interactively and generates unique
|
|
||||||
# random credentials for THIS instance. The full credentials land in
|
|
||||||
# /etc/x-ui/install-result.env (mode 600); /etc/motd shows only the URL + username.
|
|
||||||
#
|
|
||||||
# IMPORTANT (Lightsail firewall): Lightsail only opens 22/80/443 by default. The
|
|
||||||
# panel listens on a random high port, so after boot read the port from
|
|
||||||
# /etc/x-ui/install-result.env and open it under the instance's Networking tab
|
|
||||||
# (IPv4 Firewall), or pin a known port below and pre-open it.
|
|
||||||
set -e
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
# --- Non-interactive install knobs ------------------------------------------
|
|
||||||
export XUI_NONINTERACTIVE=1
|
|
||||||
export XUI_SSL_MODE="${XUI_SSL_MODE:-none}"
|
|
||||||
# Pin a known panel port so you can pre-open it in the Lightsail firewall
|
|
||||||
# (otherwise a random high port is chosen). Username/password stay random:
|
|
||||||
# export XUI_PANEL_PORT="54321"
|
|
||||||
# Other optional pins (unset => secure random):
|
|
||||||
# export XUI_USERNAME="admin2"
|
|
||||||
# export XUI_PASSWORD="change-me"
|
|
||||||
# export XUI_WEB_BASE_PATH="panel"
|
|
||||||
# Domain TLS instead of plain HTTP:
|
|
||||||
# export XUI_SSL_MODE="domain" XUI_DOMAIN="panel.example.com" XUI_ACME_EMAIL="you@example.com"
|
|
||||||
# ----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
curl -fsSL https://raw.githubusercontent.com/MHSanaei/3x-ui/main/install.sh | bash
|
|
||||||
|
|
||||||
# /etc/motd is world-readable, so it gets ONLY non-secret info (URL + username);
|
|
||||||
# the full credentials stay in the root-only /etc/x-ui/install-result.env
|
|
||||||
# (mode 600) — read them with `sudo cat` over SSH.
|
|
||||||
if [ -r /etc/x-ui/install-result.env ]; then
|
|
||||||
# shellcheck disable=SC1091
|
|
||||||
. /etc/x-ui/install-result.env
|
|
||||||
{
|
|
||||||
echo
|
|
||||||
echo "=== 3x-ui panel (generated on first boot) ==="
|
|
||||||
echo "URL: ${XUI_ACCESS_URL:-unknown}"
|
|
||||||
echo "Username: ${XUI_USERNAME:-unknown}"
|
|
||||||
echo "Password + API token: sudo cat /etc/x-ui/install-result.env"
|
|
||||||
echo "Open the panel port in the Lightsail IPv4 firewall, then log in."
|
|
||||||
echo "============================================="
|
|
||||||
} >> /etc/motd 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
#
|
|
||||||
# Lightsail snapshot provisioning user-data (used by build-snapshot.sh).
|
|
||||||
#
|
|
||||||
# Installs the 3x-ui panel into a build instance but creates NO database and
|
|
||||||
# NO credentials, and enables the first-boot unit. The instance is then snapshot
|
|
||||||
# so that every instance launched from the snapshot generates its own unique
|
|
||||||
# credentials on first boot (see deploy/firstboot/).
|
|
||||||
#
|
|
||||||
# This is the Lightsail equivalent of deploy/packer/scripts/provision.sh. It is
|
|
||||||
# NOT for end users — use deploy/lightsail/launch-script.sh for a direct install.
|
|
||||||
set -e
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
REPO=MHSanaei/3x-ui
|
|
||||||
XUI_DIR=/usr/local/x-ui
|
|
||||||
RAW="https://raw.githubusercontent.com/${REPO}/main"
|
|
||||||
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends \
|
|
||||||
ca-certificates curl tar tzdata socat openssl cron jq
|
|
||||||
|
|
||||||
ARCH=$(dpkg --print-architecture) # amd64 | arm64
|
|
||||||
VER=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | jq -r .tag_name)
|
|
||||||
if [ -z "$VER" ] || [ "$VER" = "null" ]; then
|
|
||||||
echo "failed to resolve 3x-ui version" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
tmp=$(mktemp -d)
|
|
||||||
curl -fL4 --retry 3 -o "${tmp}/x.tar.gz" \
|
|
||||||
"https://github.com/${REPO}/releases/download/${VER}/x-ui-linux-${ARCH}.tar.gz"
|
|
||||||
|
|
||||||
systemctl stop x-ui > /dev/null 2>&1 || true
|
|
||||||
rm -rf "$XUI_DIR"
|
|
||||||
tar -xzf "${tmp}/x.tar.gz" -C /usr/local/
|
|
||||||
chmod +x "${XUI_DIR}/x-ui" "${XUI_DIR}/x-ui.sh"
|
|
||||||
chmod +x "${XUI_DIR}"/bin/* 2> /dev/null || true
|
|
||||||
cp -f "${XUI_DIR}/x-ui.sh" /usr/bin/x-ui
|
|
||||||
chmod +x /usr/bin/x-ui
|
|
||||||
mkdir -p /var/log/x-ui
|
|
||||||
|
|
||||||
# Panel + first-boot systemd units.
|
|
||||||
install -m 644 "${XUI_DIR}/x-ui.service.debian" /etc/systemd/system/x-ui.service
|
|
||||||
curl -fL4 -o "${XUI_DIR}/x-ui-firstboot.sh" "${RAW}/deploy/firstboot/x-ui-firstboot.sh"
|
|
||||||
curl -fL4 -o /etc/systemd/system/x-ui-firstboot.service "${RAW}/deploy/firstboot/x-ui-firstboot.service"
|
|
||||||
chmod 755 "${XUI_DIR}/x-ui-firstboot.sh"
|
|
||||||
chmod 644 /etc/systemd/system/x-ui-firstboot.service
|
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable x-ui-firstboot.service
|
|
||||||
systemctl enable x-ui.service
|
|
||||||
|
|
||||||
# No DB, no creds in the image — first boot generates them per-instance.
|
|
||||||
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* /etc/x-ui/.firstboot-done 2> /dev/null || true
|
|
||||||
|
|
||||||
# Marker that build-snapshot.sh polls for over SSH.
|
|
||||||
touch /var/lib/3xui-provision-done
|
|
||||||
echo "[snapshot-userdata] provisioned 3x-ui ${VER} (${ARCH}); no DB created."
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
# Publishing 3x-ui to the AWS Marketplace (AMI)
|
|
||||||
|
|
||||||
This is the checklist for turning the Packer-built AMI into an AWS Marketplace
|
|
||||||
listing. It assumes you have already built an AMI with
|
|
||||||
[`../../packer/`](../../packer/) (locally or via `.github/workflows/image.yml`).
|
|
||||||
|
|
||||||
> Do **not** commit AMI IDs, AWS account numbers, or credentials. The AMI ID is
|
|
||||||
> printed to the workflow job summary at build time.
|
|
||||||
|
|
||||||
## 1. Seller registration (one-time)
|
|
||||||
|
|
||||||
1. Sign in to the [AWS Marketplace Management Portal](https://aws.amazon.com/marketplace/management/)
|
|
||||||
with the AWS account that will own the listing.
|
|
||||||
2. Complete **seller registration** (legal entity, bank, tax interview). Required
|
|
||||||
before any product can be submitted.
|
|
||||||
|
|
||||||
## 2. Build a compliant AMI
|
|
||||||
|
|
||||||
Build in the seller account (or share the AMI into it):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd deploy/packer
|
|
||||||
packer init .
|
|
||||||
# amd64
|
|
||||||
packer build -only='amazon-ebs.x-ui' \
|
|
||||||
-var 'xui_version=vX.Y.Z' -var 'xui_arch=amd64' -var 'instance_type=t3.small' -var 'region=eu-central-1' .
|
|
||||||
# arm64 (Graviton)
|
|
||||||
packer build -only='amazon-ebs.x-ui' \
|
|
||||||
-var 'xui_version=vX.Y.Z' -var 'xui_arch=arm64' -var 'instance_type=t4g.small' -var 'region=eu-central-1' .
|
|
||||||
```
|
|
||||||
|
|
||||||
You can list both AMIs (amd64 + arm64) as architectures of a single Marketplace
|
|
||||||
product, or as separate products.
|
|
||||||
|
|
||||||
The image already satisfies the Marketplace AMI policies enforced by `harden.sh`
|
|
||||||
+ `cleanup.sh`:
|
|
||||||
|
|
||||||
- ✅ `PasswordAuthentication no`, `PermitRootLogin prohibit-password`
|
|
||||||
- ✅ no default OS account passwords (all locked)
|
|
||||||
- ✅ no baked `authorized_keys`, no SSH host keys (regenerated on boot)
|
|
||||||
- ✅ base OS = current Ubuntu 24.04 LTS, patched at build time
|
|
||||||
- ✅ no application default credentials — the panel admin is generated on first
|
|
||||||
boot on a random high port (no `admin/admin`, no shipped `x-ui.db`)
|
|
||||||
|
|
||||||
## 3. Run the self-service AMI scan
|
|
||||||
|
|
||||||
1. In the Management Portal: **Server products → AMIs → Upload/scan an AMI**.
|
|
||||||
2. Share the AMI with the AWS Marketplace scanning account when prompted
|
|
||||||
(the portal gives you the exact account id and the `modify-image-attribute`
|
|
||||||
command, or share it from the EC2 console).
|
|
||||||
3. Start the scan. It checks SSH config, default credentials, open ports, and
|
|
||||||
for malware. Fix any finding and re-scan.
|
|
||||||
|
|
||||||
Common scan findings and where they're handled:
|
|
||||||
|
|
||||||
| Finding | Fix (already in the build) |
|
|
||||||
| --- | --- |
|
|
||||||
| Password authentication enabled | `harden.sh` sshd drop-in |
|
|
||||||
| Root login with password | `harden.sh` `PermitRootLogin prohibit-password` |
|
|
||||||
| Default user password set | `harden.sh` `passwd -l` on all accounts |
|
|
||||||
| Authorized keys present | `cleanup.sh` removes them |
|
|
||||||
| Out-of-date packages | base image is the latest LTS; `provision.sh` runs `apt-get update` |
|
|
||||||
|
|
||||||
## 4. Create the product (limited / private first)
|
|
||||||
|
|
||||||
1. **Server products → Create new product → AMI** (or AMI + CloudFormation).
|
|
||||||
2. Add title, description, categories, pricing (free or paid), regions, the AMI
|
|
||||||
id, recommended instance types, and the **usage instructions** (tell buyers
|
|
||||||
to read `/etc/x-ui/credentials.txt` / MOTD after first boot for the generated
|
|
||||||
admin login, then change the password).
|
|
||||||
3. Submit as a **Limited** (private) listing first. AWS publishes it with
|
|
||||||
restricted visibility so only your account / allow-listed accounts see it.
|
|
||||||
|
|
||||||
## 5. Preview & launch test
|
|
||||||
|
|
||||||
1. From the limited listing, **subscribe and launch** a test instance.
|
|
||||||
2. SSH in, `sudo cat /etc/x-ui/credentials.txt`, open the panel URL, log in,
|
|
||||||
confirm the panel works and the credentials are unique to that instance.
|
|
||||||
3. Launch a second instance and confirm its credentials differ (no shared
|
|
||||||
secrets).
|
|
||||||
|
|
||||||
## 6. Go public
|
|
||||||
|
|
||||||
1. Once the scan passes and the preview looks correct, request **public
|
|
||||||
visibility** (move from Limited to Public) in the listing.
|
|
||||||
2. AWS does a final review before the listing goes live.
|
|
||||||
|
|
||||||
## References
|
|
||||||
|
|
||||||
- AWS Marketplace seller guide: <https://docs.aws.amazon.com/marketplace/latest/userguide/>
|
|
||||||
- AMI-based product requirements: <https://docs.aws.amazon.com/marketplace/latest/userguide/product-and-ami-policies.html>
|
|
||||||
- Self-service AMI scanning: <https://docs.aws.amazon.com/marketplace/latest/userguide/product-submission.html>
|
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
# 3x-ui on Hetzner Cloud
|
# 3x-ui on Hetzner Cloud
|
||||||
|
|
||||||
Hetzner Cloud does **not** have a third-party image marketplace the way AWS does.
|
Hetzner Cloud does **not** have a third-party image marketplace the way AWS does.
|
||||||
There are two practical ways to ship 3x-ui on Hetzner.
|
Ship 3x-ui via **cloud-init**: each instance installs non-interactively and
|
||||||
|
generates unique per-instance credentials (no `admin/admin`, no shared secret).
|
||||||
|
|
||||||
## Option A — cloud-init (recommended, no image build)
|
## cloud-init (no image build)
|
||||||
|
|
||||||
Use the generic user-data from [`../../cloud-init/`](../../cloud-init/). It installs
|
Use the generic user-data from [`../../cloud-init/`](../../cloud-init/). It installs
|
||||||
3x-ui non-interactively and generates unique per-instance credentials.
|
3x-ui non-interactively and generates unique per-instance credentials.
|
||||||
@@ -27,28 +28,6 @@ After boot, fetch the generated credentials:
|
|||||||
ssh root@<server-ip> 'cat /etc/x-ui/install-result.env'
|
ssh root@<server-ip> 'cat /etc/x-ui/install-result.env'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Option B — snapshot from the qcow2 / a configured server
|
|
||||||
|
|
||||||
Hetzner lets you create a **snapshot** of a running server and launch new
|
|
||||||
servers from it. Two ways to get there:
|
|
||||||
|
|
||||||
1. **From the Packer qcow2:** Hetzner does not allow direct qcow2 upload via the
|
|
||||||
normal API, but you can boot a server, write the image to its disk in rescue
|
|
||||||
mode, then take a snapshot — or simply use Option A, which needs no image.
|
|
||||||
2. **From a configured server:** spin up a server, install via cloud-init
|
|
||||||
(Option A), verify, then **delete `/etc/x-ui/x-ui.db` and the first-boot
|
|
||||||
sentinel** before snapshotting so clones regenerate their own credentials:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
systemctl stop x-ui
|
|
||||||
rm -f /etc/x-ui/x-ui.db /etc/x-ui/.firstboot-done /etc/x-ui/credentials.txt
|
|
||||||
# re-enable first-boot regeneration if you installed via Packer:
|
|
||||||
systemctl enable x-ui-firstboot 2>/dev/null || true
|
|
||||||
```
|
|
||||||
|
|
||||||
> ⚠️ If you snapshot a server **with** its `x-ui.db`, every clone shares the
|
|
||||||
> same admin credentials and session secret. Always remove the DB first.
|
|
||||||
|
|
||||||
## "App"-style listing
|
## "App"-style listing
|
||||||
|
|
||||||
Hetzner's curated apps live in the community repo
|
Hetzner's curated apps live in the community repo
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
# Packer build artifacts (never commit images or manifests)
|
|
||||||
output-qemu/
|
|
||||||
*.qcow2
|
|
||||||
*.raw
|
|
||||||
packer-manifest.json
|
|
||||||
packer_cache/
|
|
||||||
crash.log
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
# 3x-ui golden image (Packer)
|
|
||||||
|
|
||||||
Builds a cloud image with the 3x-ui panel pre-installed but **not configured**:
|
|
||||||
the image ships with **no database and no credentials**, and generates a unique
|
|
||||||
admin account on first boot. This is the **primary** path for AWS Marketplace
|
|
||||||
and any reusable image.
|
|
||||||
|
|
||||||
Two sources, one build:
|
|
||||||
|
|
||||||
| Source | Output | For |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `amazon-ebs` | AWS AMI | AWS / Marketplace |
|
|
||||||
| `qemu` | `qcow2` (+ `raw`) | Hetzner, DigitalOcean, Vultr, GCP, Azure, Oracle, bare metal |
|
|
||||||
|
|
||||||
Both sources build for **`amd64` and `arm64`** (select with `-var xui_arch=...`).
|
|
||||||
|
|
||||||
## Why no baked DB
|
|
||||||
|
|
||||||
3x-ui seeds a hardcoded `admin/admin` user and generates its session secret +
|
|
||||||
panel GUID the first time it starts. If an image shipped an initialized
|
|
||||||
`x-ui.db`, **every clone would share the same credentials and secret**. So the
|
|
||||||
build deliberately:
|
|
||||||
|
|
||||||
- installs the panel binary + systemd unit but **never starts it** and **never
|
|
||||||
creates a DB** (`scripts/provision.sh`);
|
|
||||||
- wipes any stray DB/credentials/host-keys at the end (`scripts/cleanup.sh`);
|
|
||||||
- enables `x-ui-firstboot.service`, which on first boot resets settings, sets a
|
|
||||||
random username/password on a random high port, regenerates the secret/GUID,
|
|
||||||
and writes the credentials to `/etc/x-ui/credentials.txt` + `/etc/motd`
|
|
||||||
(`deploy/firstboot/`).
|
|
||||||
|
|
||||||
## Prerequisites
|
|
||||||
|
|
||||||
- [Packer](https://developer.hashicorp.com/packer) ≥ 1.9
|
|
||||||
- For `qemu` amd64: `qemu-system-x86`, `qemu-utils` (and `/dev/kvm` for acceptable speed)
|
|
||||||
- For `qemu` arm64: `qemu-system-arm`, `qemu-efi-aarch64`, `qemu-utils` — best built on an
|
|
||||||
arm64 host (native KVM); cross-building from x86 works but uses slow TCG emulation
|
|
||||||
- For `amazon-ebs`: AWS credentials with EC2 build permissions (arm64 builds on a Graviton
|
|
||||||
instance such as `t4g.small`)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd deploy/packer
|
|
||||||
packer init .
|
|
||||||
packer fmt -check . # formatting
|
|
||||||
packer validate . # both sources
|
|
||||||
```
|
|
||||||
|
|
||||||
## Build
|
|
||||||
|
|
||||||
Build a specific release (recommended) or `latest`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# amd64 qcow2 (no cloud account needed)
|
|
||||||
packer build -only='qemu.x-ui' -var 'xui_version=v3.3.1' -var 'xui_arch=amd64' .
|
|
||||||
|
|
||||||
# arm64 qcow2 (run on an arm64 host for native KVM)
|
|
||||||
packer build -only='qemu.x-ui' -var 'xui_version=v3.3.1' -var 'xui_arch=arm64' .
|
|
||||||
|
|
||||||
# amd64 AWS AMI
|
|
||||||
packer build -only='amazon-ebs.x-ui' \
|
|
||||||
-var 'xui_version=v3.3.1' -var 'xui_arch=amd64' -var 'instance_type=t3.small' -var 'region=eu-central-1' .
|
|
||||||
|
|
||||||
# arm64 AWS AMI (Graviton)
|
|
||||||
packer build -only='amazon-ebs.x-ui' \
|
|
||||||
-var 'xui_version=v3.3.1' -var 'xui_arch=arm64' -var 'instance_type=t4g.small' -var 'region=eu-central-1' .
|
|
||||||
```
|
|
||||||
|
|
||||||
Outputs (per arch):
|
|
||||||
- `output-qemu/3x-ui-ubuntu-24.04-<arch>.qcow2` and `.raw`
|
|
||||||
- the AMI id (also recorded in `packer-manifest.json`)
|
|
||||||
|
|
||||||
If `/dev/kvm` is unavailable, add `-var 'qemu_accelerator=tcg'` (much slower).
|
|
||||||
|
|
||||||
## Key variables
|
|
||||||
|
|
||||||
See [`variables.pkr.hcl`](variables.pkr.hcl) for the full list.
|
|
||||||
|
|
||||||
| Variable | Default | Notes |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `xui_version` | `latest` | Release tag to install, e.g. `v3.3.1` |
|
|
||||||
| `xui_arch` | `amd64` | `amd64` or `arm64` (derives the base AMI / cloud image) |
|
|
||||||
| `region` | `eu-central-1` | AWS region (amazon-ebs) |
|
|
||||||
| `instance_type` | `t3.small` | EC2 build instance — must match the arch (`t4g.small` for arm64) |
|
|
||||||
| `qemu_accelerator` | `kvm` | `kvm` or `tcg` |
|
|
||||||
| `qemu_cpu` | `host` | arm64 `-cpu` model (`host` with KVM, `max` for TCG) |
|
|
||||||
| `ubuntu_version` | `24.04` | Base Ubuntu LTS (naming/tags) |
|
|
||||||
|
|
||||||
The CI workflow builds both arches automatically: amd64 qcow2 on a standard runner,
|
|
||||||
arm64 qcow2 on a native `ubuntu-24.04-arm` runner, and both AMIs from a single runner
|
|
||||||
(the build instance runs in AWS).
|
|
||||||
|
|
||||||
## First boot
|
|
||||||
|
|
||||||
On the first boot of any instance launched from the image:
|
|
||||||
|
|
||||||
1. `x-ui-firstboot.service` runs **before** `x-ui.service`.
|
|
||||||
2. It generates a unique admin username/password, a random panel port, a random
|
|
||||||
base path, and an API token.
|
|
||||||
3. Credentials are written to `/etc/x-ui/credentials.txt` (root-only) and shown
|
|
||||||
in `/etc/motd`. Retrieve them with `sudo cat /etc/x-ui/credentials.txt`.
|
|
||||||
4. The panel then starts on the random port. `admin/admin` never exists.
|
|
||||||
|
|
||||||
## CI
|
|
||||||
|
|
||||||
`.github/workflows/image.yml` runs this build on `release: published` (and via
|
|
||||||
`workflow_dispatch`), attaching the compressed `qcow2` to the release and
|
|
||||||
building the AMI when AWS credentials are configured.
|
|
||||||
|
|
||||||
## A note on host firewalls
|
|
||||||
|
|
||||||
`scripts/harden.sh` intentionally does **not** enable a restrictive host
|
|
||||||
firewall. 3x-ui opens Xray inbound ports on admin-chosen ports at runtime, which
|
|
||||||
a host firewall would block. Use your cloud provider's security groups/firewall
|
|
||||||
instead, and open the panel port + your inbound ports there. If you still want a
|
|
||||||
host firewall, add `ufw` rules in `harden.sh` allowing SSH, the panel port and
|
|
||||||
your inbound ports.
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# cleanup.sh — strip all instance-specific state and secrets from the image.
|
|
||||||
#
|
|
||||||
# Runs LAST. The output image must contain no panel database, no credentials,
|
|
||||||
# no SSH host keys, and no baked authorized_keys. Fails the build if any of
|
|
||||||
# those survive.
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
echo "[cleanup] removing panel database, credentials and first-boot sentinel..."
|
|
||||||
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* 2> /dev/null || true
|
|
||||||
rm -f /etc/x-ui/install-result.env /etc/x-ui/credentials.txt 2> /dev/null || true
|
|
||||||
rm -f /etc/x-ui/.firstboot-done 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] removing SSH host keys (regenerated on first boot)..."
|
|
||||||
rm -f /etc/ssh/ssh_host_* 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] removing any baked authorized_keys..."
|
|
||||||
rm -f /root/.ssh/authorized_keys 2> /dev/null || true
|
|
||||||
find /home -maxdepth 3 -name authorized_keys -type f -delete 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] resetting machine-id..."
|
|
||||||
truncate -s 0 /etc/machine-id 2> /dev/null || true
|
|
||||||
rm -f /var/lib/dbus/machine-id 2> /dev/null || true
|
|
||||||
ln -sf /etc/machine-id /var/lib/dbus/machine-id 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] resetting cloud-init so it re-runs on the real first boot..."
|
|
||||||
cloud-init clean --logs --seed > /dev/null 2>&1 || rm -rf /var/lib/cloud/* 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] truncating logs, history and package caches..."
|
|
||||||
find /var/log -type f -exec truncate -s 0 {} + 2> /dev/null || true
|
|
||||||
rm -rf /var/lib/x-ui /var/log/x-ui/* 2> /dev/null || true
|
|
||||||
apt-get clean || true
|
|
||||||
rm -rf /var/lib/apt/lists/* 2> /dev/null || true
|
|
||||||
rm -f /root/.bash_history 2> /dev/null || true
|
|
||||||
find /home -maxdepth 3 -name .bash_history -type f -delete 2> /dev/null || true
|
|
||||||
rm -rf /tmp/firstboot 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[cleanup] verifying the image is clean..."
|
|
||||||
fail=0
|
|
||||||
for f in /etc/x-ui/x-ui.db /etc/x-ui/credentials.txt /etc/x-ui/install-result.env /etc/x-ui/.firstboot-done; do
|
|
||||||
if [ -e "$f" ]; then
|
|
||||||
echo "[cleanup] FATAL: $f is present in the image" >&2
|
|
||||||
fail=1
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
if ls /etc/ssh/ssh_host_* > /dev/null 2>&1; then
|
|
||||||
echo "[cleanup] FATAL: SSH host keys present in the image" >&2
|
|
||||||
fail=1
|
|
||||||
fi
|
|
||||||
if [ -e /root/.ssh/authorized_keys ]; then
|
|
||||||
echo "[cleanup] FATAL: /root/.ssh/authorized_keys present in the image" >&2
|
|
||||||
fail=1
|
|
||||||
fi
|
|
||||||
if [ "$fail" -ne 0 ]; then
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "[cleanup] OK — no DB, no credentials, no host keys, no authorized_keys."
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# harden.sh — baseline OS hardening for AWS Marketplace AMI scanner compliance.
|
|
||||||
#
|
|
||||||
# Focus: the controls the scanner actually checks — key-only SSH, no root
|
|
||||||
# password login, and no default OS account passwords. A restrictive host
|
|
||||||
# firewall is intentionally NOT enforced by default because 3x-ui opens Xray
|
|
||||||
# inbound ports on admin-chosen ports at runtime (see README for the rationale
|
|
||||||
# and how to add ufw rules if you want them).
|
|
||||||
set -euo pipefail
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
echo "[harden] applying SSH hardening..."
|
|
||||||
install -d -m 755 /etc/ssh/sshd_config.d
|
|
||||||
cat > /etc/ssh/sshd_config.d/99-3xui-hardening.conf << 'EOF'
|
|
||||||
# 3x-ui golden image hardening (AWS Marketplace scanner compliance)
|
|
||||||
PasswordAuthentication no
|
|
||||||
PermitRootLogin prohibit-password
|
|
||||||
KbdInteractiveAuthentication no
|
|
||||||
ChallengeResponseAuthentication no
|
|
||||||
EOF
|
|
||||||
chmod 644 /etc/ssh/sshd_config.d/99-3xui-hardening.conf
|
|
||||||
|
|
||||||
echo "[harden] locking passwords on default OS accounts..."
|
|
||||||
# No account may ship with a usable password. Keys are provisioned per-instance
|
|
||||||
# by the cloud platform (EC2 metadata / cloud-init) on first boot.
|
|
||||||
# passwd -l locks the PASSWORD only; key-based login keeps working.
|
|
||||||
for u in root ubuntu admin; do
|
|
||||||
if id "$u" > /dev/null 2>&1; then
|
|
||||||
passwd -l "$u" > /dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "[harden] enabling automatic security updates..."
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends unattended-upgrades
|
|
||||||
systemctl enable unattended-upgrades > /dev/null 2>&1 || true
|
|
||||||
|
|
||||||
echo "[harden] done."
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# provision.sh — install the 3x-ui panel into a golden image (Packer).
|
|
||||||
#
|
|
||||||
# Self-contained: mirrors install.sh's download/extract logic but DELIBERATELY
|
|
||||||
# does NOT run config_after_install and does NOT create a database. The image
|
|
||||||
# must ship without /etc/x-ui/x-ui.db so that deploy/firstboot generates unique
|
|
||||||
# per-instance credentials on first boot. Both x-ui.service and
|
|
||||||
# x-ui-firstboot.service are enabled but NOT started here.
|
|
||||||
#
|
|
||||||
# Inputs (from Packer environment_vars):
|
|
||||||
# XUI_VERSION release tag (e.g. v3.3.1) or 'latest'
|
|
||||||
# XUI_ARCH amd64 (default) or arm64
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
XUI_VERSION="${XUI_VERSION:-latest}"
|
|
||||||
XUI_ARCH="${XUI_ARCH:-amd64}"
|
|
||||||
XUI_DIR="/usr/local/x-ui"
|
|
||||||
REPO="MHSanaei/3x-ui"
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
echo "[provision] installing base packages..."
|
|
||||||
apt-get update
|
|
||||||
apt-get install -y --no-install-recommends \
|
|
||||||
ca-certificates curl tar tzdata socat openssl cron jq
|
|
||||||
|
|
||||||
echo "[provision] resolving 3x-ui version..."
|
|
||||||
if [ "$XUI_VERSION" = "latest" ]; then
|
|
||||||
XUI_VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | jq -r '.tag_name')
|
|
||||||
fi
|
|
||||||
if [ -z "$XUI_VERSION" ] || [ "$XUI_VERSION" = "null" ]; then
|
|
||||||
echo "[provision] ERROR: could not resolve 3x-ui release tag" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "[provision] installing 3x-ui ${XUI_VERSION} (${XUI_ARCH})"
|
|
||||||
|
|
||||||
tarball="x-ui-linux-${XUI_ARCH}.tar.gz"
|
|
||||||
url="https://github.com/${REPO}/releases/download/${XUI_VERSION}/${tarball}"
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
trap 'rm -rf "$tmp"' EXIT
|
|
||||||
|
|
||||||
# Download the RELEASED binary tarball (no Go build inside the image).
|
|
||||||
curl -fL4 --retry 3 -o "${tmp}/${tarball}" "$url"
|
|
||||||
|
|
||||||
# Extract into /usr/local/ (the tarball contains an x-ui/ directory).
|
|
||||||
systemctl stop x-ui > /dev/null 2>&1 || true
|
|
||||||
rm -rf "$XUI_DIR"
|
|
||||||
tar -xzf "${tmp}/${tarball}" -C /usr/local/
|
|
||||||
chmod +x "${XUI_DIR}/x-ui" "${XUI_DIR}/x-ui.sh"
|
|
||||||
chmod +x "${XUI_DIR}"/bin/* 2> /dev/null || true
|
|
||||||
|
|
||||||
# Install the x-ui management CLI.
|
|
||||||
if [ -f "${XUI_DIR}/x-ui.sh" ]; then
|
|
||||||
cp -f "${XUI_DIR}/x-ui.sh" /usr/bin/x-ui
|
|
||||||
else
|
|
||||||
curl -fL4 -o /usr/bin/x-ui "https://raw.githubusercontent.com/${REPO}/main/x-ui.sh"
|
|
||||||
fi
|
|
||||||
chmod +x /usr/bin/x-ui
|
|
||||||
mkdir -p /var/log/x-ui
|
|
||||||
|
|
||||||
# Panel systemd unit (Ubuntu base => debian variant).
|
|
||||||
install -m 644 "${XUI_DIR}/x-ui.service.debian" /etc/systemd/system/x-ui.service
|
|
||||||
|
|
||||||
# First-boot per-instance credential unit + script (uploaded to /tmp/firstboot).
|
|
||||||
install -m 755 /tmp/firstboot/x-ui-firstboot.sh "${XUI_DIR}/x-ui-firstboot.sh"
|
|
||||||
install -m 644 /tmp/firstboot/x-ui-firstboot.service /etc/systemd/system/x-ui-firstboot.service
|
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
# Enable (start on next boot) but do NOT start now — there is no DB yet.
|
|
||||||
systemctl enable x-ui-firstboot.service
|
|
||||||
systemctl enable x-ui.service
|
|
||||||
|
|
||||||
# Belt-and-braces: ensure no DB / sentinel was created during provisioning.
|
|
||||||
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* /etc/x-ui/.firstboot-done 2> /dev/null || true
|
|
||||||
|
|
||||||
echo "[provision] done — panel installed, services enabled, NO database initialized."
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
// Input variables for the 3x-ui golden-image build.
|
|
||||||
// See README.md for usage. Override with -var / -var-file or env (PKR_VAR_*).
|
|
||||||
|
|
||||||
variable "xui_version" {
|
|
||||||
type = string
|
|
||||||
description = "3x-ui release tag to install, e.g. v3.3.1. 'latest' resolves the newest GitHub release at build time."
|
|
||||||
default = "latest"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "xui_arch" {
|
|
||||||
type = string
|
|
||||||
description = "CPU architecture to build for: amd64 or arm64."
|
|
||||||
default = "amd64"
|
|
||||||
validation {
|
|
||||||
condition = contains(["amd64", "arm64"], var.xui_arch)
|
|
||||||
error_message = "The xui_arch value must be 'amd64' or 'arm64'."
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "ubuntu_version" {
|
|
||||||
type = string
|
|
||||||
description = "Ubuntu LTS version label, used only for image naming/tags."
|
|
||||||
default = "24.04"
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- amazon-ebs (AMI) ---------------------------------------------------------
|
|
||||||
|
|
||||||
variable "region" {
|
|
||||||
type = string
|
|
||||||
description = "AWS region the AMI is built in."
|
|
||||||
default = "eu-central-1"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "instance_type" {
|
|
||||||
type = string
|
|
||||||
description = "EC2 instance type used to build the AMI. Must match xui_arch (e.g. t3.small for amd64, t4g.small for arm64/Graviton)."
|
|
||||||
default = "t3.small"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "ami_name_prefix" {
|
|
||||||
type = string
|
|
||||||
description = "Prefix for the produced AMI name."
|
|
||||||
default = "3x-ui"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "source_ami_filter_name" {
|
|
||||||
type = string
|
|
||||||
description = "Override for the Canonical Ubuntu base AMI name filter. Empty ⇒ derived from xui_arch (latest patched 24.04 LTS for that arch)."
|
|
||||||
default = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "ssh_username" {
|
|
||||||
type = string
|
|
||||||
description = "Default SSH user on the base Ubuntu cloud image."
|
|
||||||
default = "ubuntu"
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- qemu (qcow2 / raw) -------------------------------------------------------
|
|
||||||
|
|
||||||
variable "qemu_iso_url" {
|
|
||||||
type = string
|
|
||||||
description = "Override for the Ubuntu cloud image used as the qemu base disk. Empty ⇒ derived from xui_arch (amd64/arm64 cloud image)."
|
|
||||||
default = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_iso_checksum" {
|
|
||||||
type = string
|
|
||||||
description = "Checksum for the qemu base disk. 'file:<SHA256SUMS url>' auto-fetches; 'none' skips verification."
|
|
||||||
default = "file:https://cloud-images.ubuntu.com/releases/24.04/release/SHA256SUMS"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_accelerator" {
|
|
||||||
type = string
|
|
||||||
description = "QEMU accelerator: 'kvm' when /dev/kvm is available, else 'tcg' (slow software emulation)."
|
|
||||||
default = "kvm"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_headless" {
|
|
||||||
type = bool
|
|
||||||
description = "Run QEMU without a display (required on CI runners)."
|
|
||||||
default = true
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_build_password" {
|
|
||||||
type = string
|
|
||||||
description = "Temporary password injected via cloud-init for Packer's build-time SSH. Locked/removed before the image is finalized."
|
|
||||||
default = "packer-build-temp-pw"
|
|
||||||
sensitive = true
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- qemu arm64-only knobs (ignored for amd64) -------------------------------
|
|
||||||
|
|
||||||
variable "qemu_cpu" {
|
|
||||||
type = string
|
|
||||||
description = "QEMU -cpu model for arm64 builds: 'host' with KVM on an arm64 host, 'max' for TCG emulation."
|
|
||||||
default = "host"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_efi_code" {
|
|
||||||
type = string
|
|
||||||
description = "Path to the arm64 UEFI code firmware (AAVMF). Only used when xui_arch=arm64."
|
|
||||||
default = "/usr/share/AAVMF/AAVMF_CODE.fd"
|
|
||||||
}
|
|
||||||
|
|
||||||
variable "qemu_efi_vars" {
|
|
||||||
type = string
|
|
||||||
description = "Path to the arm64 UEFI vars firmware template (AAVMF). Only used when xui_arch=arm64."
|
|
||||||
default = "/usr/share/AAVMF/AAVMF_VARS.fd"
|
|
||||||
}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
// 3x-ui golden image — one build, two sources:
|
|
||||||
// * amazon-ebs : produces an AWS AMI (Marketplace-scannable)
|
|
||||||
// * qemu : produces a qcow2 (+ raw) for Hetzner/DO/Vultr/GCP/Azure/Oracle
|
|
||||||
//
|
|
||||||
// The image ships WITHOUT an initialized x-ui.db and WITHOUT any baked
|
|
||||||
// credentials. deploy/firstboot/x-ui-firstboot.{sh,service} generates unique
|
|
||||||
// per-instance credentials on first boot, before x-ui.service starts.
|
|
||||||
//
|
|
||||||
// Provisioner order is fixed: provision.sh -> harden.sh -> cleanup.sh.
|
|
||||||
|
|
||||||
packer {
|
|
||||||
required_plugins {
|
|
||||||
amazon = {
|
|
||||||
version = ">= 1.3.0"
|
|
||||||
source = "github.com/hashicorp/amazon"
|
|
||||||
}
|
|
||||||
qemu = {
|
|
||||||
version = ">= 1.1.0"
|
|
||||||
source = "github.com/hashicorp/qemu"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
locals {
|
|
||||||
build_stamp = formatdate("YYYYMMDD-hhmmss", timestamp())
|
|
||||||
image_name = "${var.ami_name_prefix}-ubuntu-${var.ubuntu_version}-${var.xui_arch}"
|
|
||||||
is_arm = var.xui_arch == "arm64"
|
|
||||||
|
|
||||||
# Base images are derived from xui_arch unless explicitly overridden.
|
|
||||||
source_ami_name = var.source_ami_filter_name != "" ? var.source_ami_filter_name : "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-${var.xui_arch}-server-*"
|
|
||||||
qemu_iso_url = var.qemu_iso_url != "" ? var.qemu_iso_url : "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-${var.xui_arch}.img"
|
|
||||||
}
|
|
||||||
|
|
||||||
source "amazon-ebs" "x-ui" {
|
|
||||||
region = var.region
|
|
||||||
instance_type = var.instance_type
|
|
||||||
ssh_username = var.ssh_username
|
|
||||||
|
|
||||||
ami_name = "${local.image_name}-${var.xui_version}-${local.build_stamp}"
|
|
||||||
ami_description = "3x-ui panel on Ubuntu ${var.ubuntu_version}. Per-instance credentials are generated on first boot."
|
|
||||||
|
|
||||||
source_ami_filter {
|
|
||||||
filters = {
|
|
||||||
name = local.source_ami_name
|
|
||||||
root-device-type = "ebs"
|
|
||||||
virtualization-type = "hvm"
|
|
||||||
}
|
|
||||||
owners = ["099720109477"] // Canonical
|
|
||||||
most_recent = true
|
|
||||||
}
|
|
||||||
|
|
||||||
launch_block_device_mappings {
|
|
||||||
device_name = "/dev/sda1"
|
|
||||||
volume_size = 8
|
|
||||||
volume_type = "gp3"
|
|
||||||
delete_on_termination = true
|
|
||||||
}
|
|
||||||
|
|
||||||
tags = {
|
|
||||||
Name = local.image_name
|
|
||||||
Project = "3x-ui"
|
|
||||||
XuiVersion = var.xui_version
|
|
||||||
BuildTool = "packer"
|
|
||||||
BaseOS = "ubuntu-${var.ubuntu_version}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
source "qemu" "x-ui" {
|
|
||||||
iso_url = local.qemu_iso_url
|
|
||||||
iso_checksum = var.qemu_iso_checksum
|
|
||||||
disk_image = true
|
|
||||||
disk_size = "10G"
|
|
||||||
format = "qcow2"
|
|
||||||
|
|
||||||
accelerator = var.qemu_accelerator
|
|
||||||
headless = var.qemu_headless
|
|
||||||
cpus = 2
|
|
||||||
memory = 2048
|
|
||||||
net_device = "virtio-net"
|
|
||||||
disk_interface = "virtio"
|
|
||||||
|
|
||||||
// Arch-specific QEMU machine. amd64 uses Packer defaults (BIOS boot, x86_64);
|
|
||||||
// arm64 needs the aarch64 binary, the 'virt' machine and UEFI (AAVMF) firmware.
|
|
||||||
qemu_binary = local.is_arm ? "qemu-system-aarch64" : null
|
|
||||||
machine_type = local.is_arm ? "virt" : null
|
|
||||||
efi_boot = local.is_arm
|
|
||||||
efi_firmware_code = local.is_arm ? var.qemu_efi_code : null
|
|
||||||
efi_firmware_vars = local.is_arm ? var.qemu_efi_vars : null
|
|
||||||
qemuargs = local.is_arm ? [["-cpu", var.qemu_cpu]] : []
|
|
||||||
|
|
||||||
output_directory = "output-qemu"
|
|
||||||
vm_name = "${local.image_name}.qcow2"
|
|
||||||
|
|
||||||
// Build-time access: a NoCloud seed sets a temporary password for the default
|
|
||||||
// user so Packer can SSH in. The seed is a separate CD-ROM (not part of the
|
|
||||||
// output disk); the password is locked by harden.sh and state wiped by cleanup.sh.
|
|
||||||
cd_label = "cidata"
|
|
||||||
cd_content = {
|
|
||||||
"meta-data" = ""
|
|
||||||
"user-data" = <<-EOT
|
|
||||||
#cloud-config
|
|
||||||
password: ${var.qemu_build_password}
|
|
||||||
chpasswd: { expire: false }
|
|
||||||
ssh_pwauth: true
|
|
||||||
EOT
|
|
||||||
}
|
|
||||||
|
|
||||||
ssh_username = var.ssh_username
|
|
||||||
ssh_password = var.qemu_build_password
|
|
||||||
ssh_timeout = "20m"
|
|
||||||
boot_wait = "45s"
|
|
||||||
|
|
||||||
shutdown_command = "sudo shutdown -P now"
|
|
||||||
}
|
|
||||||
|
|
||||||
build {
|
|
||||||
name = "3x-ui"
|
|
||||||
sources = ["source.amazon-ebs.x-ui", "source.qemu.x-ui"]
|
|
||||||
|
|
||||||
// Upload the first-boot unit + script so provision.sh can install them.
|
|
||||||
provisioner "shell" {
|
|
||||||
inline = ["mkdir -p /tmp/firstboot"]
|
|
||||||
}
|
|
||||||
provisioner "file" {
|
|
||||||
source = "${path.root}/../firstboot/x-ui-firstboot.sh"
|
|
||||||
destination = "/tmp/firstboot/x-ui-firstboot.sh"
|
|
||||||
}
|
|
||||||
provisioner "file" {
|
|
||||||
source = "${path.root}/../firstboot/x-ui-firstboot.service"
|
|
||||||
destination = "/tmp/firstboot/x-ui-firstboot.service"
|
|
||||||
}
|
|
||||||
|
|
||||||
provisioner "shell" {
|
|
||||||
environment_vars = [
|
|
||||||
"XUI_VERSION=${var.xui_version}",
|
|
||||||
"XUI_ARCH=${var.xui_arch}",
|
|
||||||
"DEBIAN_FRONTEND=noninteractive",
|
|
||||||
]
|
|
||||||
execute_command = "chmod +x {{ .Path }}; sudo -E bash {{ .Path }}"
|
|
||||||
scripts = [
|
|
||||||
"${path.root}/scripts/provision.sh",
|
|
||||||
"${path.root}/scripts/harden.sh",
|
|
||||||
"${path.root}/scripts/cleanup.sh",
|
|
||||||
]
|
|
||||||
// give cloud-init time to release apt locks on the very first boot
|
|
||||||
pause_before = "10s"
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert the qcow2 to raw for clouds that need it (qemu source only).
|
|
||||||
post-processor "shell-local" {
|
|
||||||
only = ["qemu.x-ui"]
|
|
||||||
inline = ["qemu-img convert -p -O raw output-qemu/${local.image_name}.qcow2 output-qemu/${local.image_name}.raw"]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Record the AMI id / artifacts for CI to surface.
|
|
||||||
post-processor "manifest" {
|
|
||||||
output = "packer-manifest.json"
|
|
||||||
strip_path = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
#
|
|
||||||
# smoke-firstboot.sh — verify the first-boot per-instance credential script.
|
|
||||||
#
|
|
||||||
# Installs the released x-ui binary into a container WITHOUT a database, runs
|
|
||||||
# x-ui-firstboot.sh, and asserts:
|
|
||||||
# * fresh random credentials are generated (no admin/admin)
|
|
||||||
# * /etc/x-ui/credentials.txt (600) and /etc/motd are written
|
|
||||||
# * the sentinel is created and a second run is a no-op (creds unchanged)
|
|
||||||
#
|
|
||||||
# Requires Docker and network access. Usage: bash deploy/test/smoke-firstboot.sh
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
|
||||||
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
|
|
||||||
|
|
||||||
if ! command -v docker > /dev/null 2>&1; then
|
|
||||||
echo "ERROR: docker is required for this smoke test." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== first-boot credential smoke test (image: $IMAGE) =="
|
|
||||||
|
|
||||||
docker run --rm \
|
|
||||||
-v "${REPO_ROOT}/deploy/firstboot/x-ui-firstboot.sh:/root/x-ui-firstboot.sh:ro" \
|
|
||||||
-e DEBIAN_FRONTEND=noninteractive \
|
|
||||||
"$IMAGE" bash -euo pipefail -c '
|
|
||||||
apt-get update -qq
|
|
||||||
apt-get install -y -qq curl tar openssl ca-certificates jq > /dev/null
|
|
||||||
|
|
||||||
echo "--- installing released x-ui binary (no DB, no systemd) ---"
|
|
||||||
REPO=MHSanaei/3x-ui
|
|
||||||
ARCH=$(dpkg --print-architecture) # amd64 | arm64
|
|
||||||
echo "container arch: $ARCH"
|
|
||||||
VER=$(curl --fail --location --silent --show-error \
|
|
||||||
--retry 5 --retry-all-errors --retry-delay 3 \
|
|
||||||
--connect-timeout 15 --max-time 60 \
|
|
||||||
"https://api.github.com/repos/${REPO}/releases/latest" | jq -r .tag_name)
|
|
||||||
[ -n "$VER" ] && [ "$VER" != "null" ] || { echo "FAIL: cannot resolve version"; exit 1; }
|
|
||||||
tmp=$(mktemp -d)
|
|
||||||
# 504s and other transient GitHub/CDN hiccups are retried; a real HTTP
|
|
||||||
# failure (e.g. missing arch asset) still aborts after the retries.
|
|
||||||
if ! curl -4 --fail --location --silent --show-error \
|
|
||||||
--retry 5 --retry-all-errors --retry-delay 3 \
|
|
||||||
--connect-timeout 15 --max-time 300 \
|
|
||||||
-o "${tmp}/x.tar.gz" \
|
|
||||||
"https://github.com/${REPO}/releases/download/${VER}/x-ui-linux-${ARCH}.tar.gz"; then
|
|
||||||
echo "FAIL: cannot download x-ui-linux-${ARCH}.tar.gz (${VER})" >&2; exit 1
|
|
||||||
fi
|
|
||||||
test -s "${tmp}/x.tar.gz" || { echo "FAIL: downloaded tarball is empty"; exit 1; }
|
|
||||||
tar -xzf "${tmp}/x.tar.gz" -C /usr/local/
|
|
||||||
chmod +x /usr/local/x-ui/x-ui
|
|
||||||
install -m 755 /root/x-ui-firstboot.sh /usr/local/x-ui/x-ui-firstboot.sh
|
|
||||||
|
|
||||||
# Guarantee a clean slate (the image must never ship a DB).
|
|
||||||
rm -f /etc/x-ui/x-ui.db /etc/x-ui/.firstboot-done
|
|
||||||
|
|
||||||
echo "--- run 1: generate per-instance credentials ---"
|
|
||||||
/usr/local/x-ui/x-ui-firstboot.sh
|
|
||||||
|
|
||||||
test -f /etc/x-ui/.firstboot-done || { echo "FAIL: sentinel not created"; exit 1; }
|
|
||||||
test -f /etc/x-ui/credentials.txt || { echo "FAIL: credentials.txt missing"; exit 1; }
|
|
||||||
perms=$(stat -c %a /etc/x-ui/credentials.txt)
|
|
||||||
[ "$perms" = "600" ] || { echo "FAIL: credentials.txt perms=$perms (want 600)"; exit 1; }
|
|
||||||
grep -q "3x-ui" /etc/motd || { echo "FAIL: motd not written"; exit 1; }
|
|
||||||
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
. /etc/x-ui/credentials.txt
|
|
||||||
[ -n "${XUI_USERNAME:-}" ] && [ "$XUI_USERNAME" != "admin" ] \
|
|
||||||
|| { echo "FAIL: username missing or still admin"; exit 1; }
|
|
||||||
first_user="$XUI_USERNAME"
|
|
||||||
|
|
||||||
/usr/local/x-ui/x-ui setting -show | grep -q "hasDefaultCredential: false" \
|
|
||||||
|| { echo "FAIL: hasDefaultCredential is not false"; exit 1; }
|
|
||||||
|
|
||||||
echo "--- run 2: must be a no-op (sentinel honored) ---"
|
|
||||||
/usr/local/x-ui/x-ui-firstboot.sh
|
|
||||||
# shellcheck disable=SC1090
|
|
||||||
. /etc/x-ui/credentials.txt
|
|
||||||
[ "$XUI_USERNAME" = "$first_user" ] \
|
|
||||||
|| { echo "FAIL: credentials changed on re-run"; exit 1; }
|
|
||||||
|
|
||||||
echo "SMOKE_PASS: firstboot user=$first_user (stable across re-run)"
|
|
||||||
'
|
|
||||||
|
|
||||||
echo "== first-boot smoke test PASSED =="
|
|
||||||
@@ -7,35 +7,51 @@
|
|||||||
# * /etc/x-ui/install-result.env exists (mode 600) with random, non-default creds
|
# * /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 reports hasDefaultCredential: false (no admin/admin remains)
|
||||||
# * the panel HTTP server actually serves on the generated port/base path
|
# * 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).
|
# 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
|
set -euo pipefail
|
||||||
|
|
||||||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||||
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
|
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
|
||||||
|
XUI_SMOKE_VERSION="${1:-}"
|
||||||
|
|
||||||
if ! command -v docker > /dev/null 2>&1; then
|
if ! command -v docker > /dev/null 2>&1; then
|
||||||
echo "ERROR: docker is required for this smoke test." >&2
|
echo "ERROR: docker is required for this smoke test." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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 \
|
docker run --rm \
|
||||||
-v "${REPO_ROOT}/install.sh:/root/install.sh:ro" \
|
-v "${REPO_ROOT}/install.sh:/root/install.sh:ro" \
|
||||||
-e XUI_NONINTERACTIVE=1 \
|
-e XUI_NONINTERACTIVE=1 \
|
||||||
-e XUI_SSL_MODE=none \
|
-e XUI_SSL_MODE=none \
|
||||||
|
-e XUI_SMOKE_VERSION="$XUI_SMOKE_VERSION" \
|
||||||
-e DEBIAN_FRONTEND=noninteractive \
|
-e DEBIAN_FRONTEND=noninteractive \
|
||||||
"$IMAGE" bash -euo pipefail -c '
|
"$IMAGE" bash -euo pipefail -c '
|
||||||
apt-get update -qq
|
apt-get update -qq
|
||||||
apt-get install -y -qq curl tar openssl ca-certificates > /dev/null
|
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.
|
# 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 ---"
|
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
|
RESULT=/etc/x-ui/install-result.env
|
||||||
test -f "$RESULT" || { echo "FAIL: $RESULT missing"; exit 1; }
|
test -f "$RESULT" || { echo "FAIL: $RESULT missing"; exit 1; }
|
||||||
|
|
||||||
|
|||||||
+11
-4
@@ -5,8 +5,8 @@ services:
|
|||||||
dockerfile: ./Dockerfile
|
dockerfile: ./Dockerfile
|
||||||
container_name: 3xui_app
|
container_name: 3xui_app
|
||||||
# hostname: yourhostname <- optional
|
# hostname: yourhostname <- optional
|
||||||
# Optional hard memory cap. When set, the panel auto-derives its Go soft
|
# Optional hard memory cap. When set, the panel derives its Go soft limit
|
||||||
# limit (GOMEMLIMIT, ~90%) from this so it GCs before the OOM killer fires.
|
# (GOMEMLIMIT, ~90% of this cap) so it GCs before the OOM killer fires.
|
||||||
# mem_limit: 512m
|
# mem_limit: 512m
|
||||||
# The bundled Fail2ban (XUI_ENABLE_FAIL2BAN below) enforces the IP limit
|
# The bundled Fail2ban (XUI_ENABLE_FAIL2BAN below) enforces the IP limit
|
||||||
# with iptables, which needs NET_ADMIN. Without these caps a ban is logged
|
# with iptables, which needs NET_ADMIN. Without these caps a ban is logged
|
||||||
@@ -18,11 +18,18 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- $PWD/db/:/etc/x-ui/
|
- $PWD/db/:/etc/x-ui/
|
||||||
- $PWD/cert/:/root/cert/
|
- $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:
|
environment:
|
||||||
XRAY_VMESS_AEAD_FORCED: "false"
|
XRAY_VMESS_AEAD_FORCED: "false"
|
||||||
XUI_ENABLE_FAIL2BAN: "true"
|
XUI_ENABLE_FAIL2BAN: "true"
|
||||||
# Go memory soft limit. If neither is set, the panel auto-detects the
|
# Memory tuning. The panel keeps RAM low via GOGC + periodic release; it no
|
||||||
# cgroup/host limit and targets ~90%. Pin it explicitly with one of:
|
# longer sets a soft limit from total host RAM (no benefit, risks GC thrash).
|
||||||
|
# XUI_GOGC: "75" # lower = less RAM, slightly more CPU; GOGC env overrides
|
||||||
|
# XUI_MEMORY_RELEASE_INTERVAL: "10" # minutes between FreeOSMemory; 0 disables
|
||||||
|
# Go memory soft limit, only applied from an explicit budget below (or a
|
||||||
|
# real cgroup/mem_limit cap). Pin it with one of:
|
||||||
# XUI_MEMORY_LIMIT: "400" # in MiB
|
# XUI_MEMORY_LIMIT: "400" # in MiB
|
||||||
# GOMEMLIMIT: "400MiB" # Go syntax, takes precedence
|
# GOMEMLIMIT: "400MiB" # Go syntax, takes precedence
|
||||||
# XUI_PPROF: "true" # expose pprof on 127.0.0.1:6060 for profiling
|
# XUI_PPROF: "true" # expose pprof on 127.0.0.1:6060 for profiling
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Auto detect text files and perform LF normalization
|
||||||
|
* text=auto
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# deps
|
||||||
|
/node_modules
|
||||||
|
|
||||||
|
# generated content
|
||||||
|
.source
|
||||||
|
|
||||||
|
# test & build
|
||||||
|
/coverage
|
||||||
|
/.next/
|
||||||
|
/out/
|
||||||
|
/build
|
||||||
|
*.tsbuildinfo
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
/.pnp
|
||||||
|
.pnp.js
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# others
|
||||||
|
.env*.local
|
||||||
|
.vercel
|
||||||
|
next-env.d.ts
|
||||||
|
# npm (this project uses pnpm)
|
||||||
|
package-lock.json
|
||||||
|
|
||||||
|
# claude code (local settings/plans; keep shared project instructions)
|
||||||
|
/.claude/*
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
node_modules
|
||||||
|
.next
|
||||||
|
.source
|
||||||
|
out
|
||||||
|
pnpm-lock.yaml
|
||||||
|
public/openapi.json
|
||||||
|
# Don't let Prettier reflow MDX prose — it merges headings into paragraphs and
|
||||||
|
# collapses lists inside JSX components (Steps/Callout). Author MDX by hand.
|
||||||
|
content/**/*.mdx
|
||||||
|
content/docs/**/reference/api
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"printWidth": 100,
|
||||||
|
"tabWidth": 2
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Contributing to 3x-ui-docs
|
||||||
|
|
||||||
|
Thanks for helping improve the 3x-ui documentation and product site!
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
This project uses **[pnpm](https://pnpm.io)** (not npm — `package-lock.json` is
|
||||||
|
gitignored). Install dependencies and start the dev server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
pnpm dev # http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scripts
|
||||||
|
|
||||||
|
| Script | Description |
|
||||||
|
| ---------------- | ----------------------------------------------------- |
|
||||||
|
| `pnpm dev` | Start the dev server |
|
||||||
|
| `pnpm build` | Production build |
|
||||||
|
| `pnpm start` | Serve the production build |
|
||||||
|
| `pnpm typecheck` | Generate MDX/route types and run `tsc --noEmit` |
|
||||||
|
| `pnpm lint` | ESLint (flat config) |
|
||||||
|
| `pnpm format` | Format with Prettier |
|
||||||
|
| `pnpm test` | Run unit tests (Vitest) for `lib/xray/*` pure logic |
|
||||||
|
| `pnpm gen:api` | Generate the API reference from `public/openapi.json` |
|
||||||
|
|
||||||
|
Before opening a pull request, please run `pnpm typecheck`, `pnpm lint`, and
|
||||||
|
`pnpm test` — these are the same checks that CI runs on every PR.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
By contributing, you agree that your contributions will be licensed under the
|
||||||
|
project's [GPL-3.0](./LICENSE) license.
|
||||||
+674
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
+133
@@ -0,0 +1,133 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="https://docs.sanaei.dev">
|
||||||
|
<picture>
|
||||||
|
<source media="(prefers-color-scheme: dark)" srcset="public/logo-dark.png" />
|
||||||
|
<img src="public/logo-light.png" alt="3x-ui" width="180" />
|
||||||
|
</picture>
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h1 align="center">3x-ui Documentation</h1>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
The official documentation and product site for
|
||||||
|
<a href="https://github.com/MHSanaei/3x-ui"><b>3x-ui</b></a> —
|
||||||
|
an advanced web panel for managing Xray-core servers.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://docs.sanaei.dev"><img src="https://img.shields.io/badge/docs-docs.sanaei.dev-22d3ee?style=flat-square" alt="Live site" /></a>
|
||||||
|
<a href="https://github.com/MHSanaei/3x-ui/actions/workflows/docs-ci.yml"><img src="https://github.com/MHSanaei/3x-ui/actions/workflows/docs-ci.yml/badge.svg" alt="CI" /></a>
|
||||||
|
<a href="LICENSE"><img src="https://img.shields.io/badge/license-GPL--3.0-blue?style=flat-square" alt="License: GPL-3.0" /></a>
|
||||||
|
<img src="https://img.shields.io/badge/Next.js-16-black?style=flat-square&logo=next.js" alt="Next.js 16" />
|
||||||
|
<img src="https://img.shields.io/badge/Fumadocs-16-0ea5e9?style=flat-square" alt="Fumadocs 16" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://docs.sanaei.dev"><b>Read the docs →</b></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
This directory (`docs/` in the [3x-ui](https://github.com/MHSanaei/3x-ui) monorepo) contains
|
||||||
|
the source for [docs.sanaei.dev](https://docs.sanaei.dev) — a static-first documentation and
|
||||||
|
marketing site built with [Fumadocs](https://fumadocs.dev) on Next.js. It has **no backend,
|
||||||
|
no database, and no auth**: every page is prerendered and every tool runs entirely in the
|
||||||
|
browser.
|
||||||
|
|
||||||
|
## What's inside
|
||||||
|
|
||||||
|
The documentation walks you through 3x-ui from first install to day-to-day operation:
|
||||||
|
|
||||||
|
- **Getting Started** — installation, first login, and updating or uninstalling the panel.
|
||||||
|
- **Configuration** — the panel, inbounds, REALITY, transports, clients, subscriptions, and share links.
|
||||||
|
- **Operations** — reverse proxy, multi-node setups, outbounds & routing, backup/restore, the Telegram bot, and security.
|
||||||
|
- **Reference** — environment variables, the database, ports & firewall, and the HTTP API.
|
||||||
|
- **Help** — troubleshooting, FAQ, migration, and how to contribute.
|
||||||
|
|
||||||
|
## Interactive tools
|
||||||
|
|
||||||
|
The site ships with in-browser helpers that generate configuration for you — **no data
|
||||||
|
ever leaves your browser**:
|
||||||
|
|
||||||
|
| Tool | What it does |
|
||||||
|
| ---------------------------- | ------------------------------------------------------- |
|
||||||
|
| **REALITY Config Generator** | Build a valid REALITY inbound configuration. |
|
||||||
|
| **Share Link Inspector** | Decode and inspect `vless://` / `vmess://` share links. |
|
||||||
|
| **Install Command Builder** | Assemble the right install command for your setup. |
|
||||||
|
| **Reverse Proxy Generator** | Generate reverse-proxy configs (Nginx / Caddy). |
|
||||||
|
| **Protocol Wizard** | Pick and configure the right protocol for your needs. |
|
||||||
|
| **Firewall Rules Generator** | Produce firewall rules for your ports. |
|
||||||
|
|
||||||
|
## Tech stack
|
||||||
|
|
||||||
|
| Layer | Technology |
|
||||||
|
| ---------- | ---------------------------------------------------------- |
|
||||||
|
| Framework | [Next.js 16](https://nextjs.org) (App Router) · React 19 |
|
||||||
|
| Docs | [Fumadocs](https://fumadocs.dev) (`-ui` / `-core` / `-mdx`) |
|
||||||
|
| Styling | [Tailwind CSS v4](https://tailwindcss.com) |
|
||||||
|
| Search | [Orama](https://orama.com) static index |
|
||||||
|
| Language | TypeScript (strict) |
|
||||||
|
| Tests | [Vitest](https://vitest.dev) for the pure `lib/xray` logic |
|
||||||
|
| Tooling | pnpm · ESLint 9 · Prettier |
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
This project uses **[pnpm](https://pnpm.io)** (npm lockfiles are gitignored). Run everything
|
||||||
|
from the `docs/` directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd docs
|
||||||
|
pnpm install
|
||||||
|
pnpm dev # http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
Useful scripts:
|
||||||
|
|
||||||
|
| Script | Description |
|
||||||
|
| ---------------- | -------------------------------------------- |
|
||||||
|
| `pnpm dev` | Start the dev server |
|
||||||
|
| `pnpm build` | Production build (also typechecks) |
|
||||||
|
| `pnpm typecheck` | Generate MDX/route types and `tsc --noEmit` |
|
||||||
|
| `pnpm lint` | Run ESLint |
|
||||||
|
| `pnpm test` | Run unit tests (Vitest) |
|
||||||
|
|
||||||
|
See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full list and project conventions.
|
||||||
|
|
||||||
|
## Project structure
|
||||||
|
|
||||||
|
```
|
||||||
|
app/ # Next.js App Router — layouts, home, docs, OG images, search, llms.txt
|
||||||
|
components/ # React components — interactive tools, home sections, MDX bindings
|
||||||
|
content/docs/ # MDX documentation, one folder per locale (en · fa · ru · zh)
|
||||||
|
lib/ # source config, i18n, GitHub stats, and the unit-tested lib/xray logic
|
||||||
|
public/ # static assets — logos, favicon, openapi.json, CNAME
|
||||||
|
scripts/ # build-time scripts (API reference generation)
|
||||||
|
source.config.ts # Fumadocs MDX schema & collection config
|
||||||
|
next.config.mjs # Next.js config (static-export gating)
|
||||||
|
proxy.ts # i18n middleware
|
||||||
|
```
|
||||||
|
|
||||||
|
## Internationalization
|
||||||
|
|
||||||
|
Documentation is authored in **English**. Persian (`fa`, RTL), Russian (`ru`), and
|
||||||
|
Chinese (`zh`) locales are wired up; untranslated pages fall back to English so they
|
||||||
|
never 404. English URLs are unprefixed; other locales live under `/fa`, `/ru`, `/zh`.
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
The site builds for two targets:
|
||||||
|
|
||||||
|
- **Vercel / Node** — `pnpm build` (static search index + prerendered OG images).
|
||||||
|
- **GitHub Pages (static export)** — `DEPLOY_TARGET=static pnpm build` → `out/`.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Contributions are welcome! Setup, scripts, and project conventions live in
|
||||||
|
[`CONTRIBUTING.md`](./CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Licensed under [GPL-3.0](./LICENSE).
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { HomeLayout } from 'fumadocs-ui/layouts/home';
|
||||||
|
import { baseOptions } from '@/lib/layout.shared';
|
||||||
|
import { HomeLanguageSwitcher } from '@/components/home/language-switcher';
|
||||||
|
|
||||||
|
export default async function Layout({ params, children }: LayoutProps<'/[lang]'>) {
|
||||||
|
const { lang } = await params;
|
||||||
|
const options = baseOptions(lang);
|
||||||
|
return (
|
||||||
|
<HomeLayout
|
||||||
|
{...options}
|
||||||
|
// Disable fumadocs' built-in popover language switcher here: nested in the
|
||||||
|
// home navbar's Radix NavigationMenu its item clicks don't fire. We inject
|
||||||
|
// an anchor-based one instead (see HomeLanguageSwitcher). Docs keep the
|
||||||
|
// built-in switcher (its sidebar isn't a NavigationMenu, so it works).
|
||||||
|
i18n={false}
|
||||||
|
links={[
|
||||||
|
...(options.links ?? []),
|
||||||
|
{
|
||||||
|
type: 'custom',
|
||||||
|
secondary: true,
|
||||||
|
children: <HomeLanguageSwitcher current={lang} />,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</HomeLayout>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
import { ArrowRight, BookOpen, Heart } from 'lucide-react';
|
||||||
|
import { GitHubIcon, TelegramIcon } from '@/components/icons';
|
||||||
|
import { Logo } from '@/components/logo';
|
||||||
|
import { Features } from '@/components/home/features';
|
||||||
|
import { GitHubStatsRow } from '@/components/home/github-stats';
|
||||||
|
import { InstallCommand } from '@/components/home/install-command';
|
||||||
|
import { getGitHubStats } from '@/lib/github-stats';
|
||||||
|
import { i18n } from '@/lib/i18n';
|
||||||
|
import { appName, productRepoUrl, deepWikiUrl, telegramChannelUrl, donateUrl } from '@/lib/shared';
|
||||||
|
import { getSiteMessages, type SiteMessages } from '@/lib/site-i18n';
|
||||||
|
|
||||||
|
export function generateStaticParams() {
|
||||||
|
return i18n.languages.map((lang) => ({ lang }));
|
||||||
|
}
|
||||||
|
|
||||||
|
const INSTALL_COMMAND =
|
||||||
|
'bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)';
|
||||||
|
|
||||||
|
export default async function HomePage({ params }: PageProps<'/[lang]'>) {
|
||||||
|
const { lang } = await params;
|
||||||
|
const prefix = lang === 'en' ? '' : `/${lang}`;
|
||||||
|
const m = getSiteMessages(lang);
|
||||||
|
const stats = await getGitHubStats();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="flex flex-1 flex-col">
|
||||||
|
{/* Hero */}
|
||||||
|
<section className="relative overflow-hidden border-b">
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute inset-x-0 -top-40 h-80 bg-gradient-to-b from-brand/15 to-transparent blur-3xl"
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<div className="mx-auto flex w-full max-w-5xl flex-col items-center px-4 py-20 text-center sm:py-28">
|
||||||
|
<Logo className="h-20 drop-shadow-sm" />
|
||||||
|
<h1 className="mt-6 text-4xl font-bold tracking-tight sm:text-6xl">
|
||||||
|
<span className="bg-gradient-to-r from-cyan-500 to-sky-600 bg-clip-text text-transparent dark:from-cyan-300 dark:to-sky-400">
|
||||||
|
{appName}
|
||||||
|
</span>
|
||||||
|
</h1>
|
||||||
|
<p className="mt-4 max-w-2xl text-lg text-fd-muted-foreground sm:text-xl">{m.tagline}</p>
|
||||||
|
|
||||||
|
<div className="mt-8 flex flex-col items-center gap-3 sm:flex-row">
|
||||||
|
<Link
|
||||||
|
href={`${prefix}/docs`}
|
||||||
|
className="inline-flex items-center gap-2 rounded-xl bg-fd-primary px-5 py-3 font-medium text-fd-primary-foreground transition-opacity hover:opacity-90"
|
||||||
|
>
|
||||||
|
{m.getStarted}
|
||||||
|
<ArrowRight className="size-4 rtl:rotate-180" aria-hidden />
|
||||||
|
</Link>
|
||||||
|
<a
|
||||||
|
href={productRepoUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer noopener"
|
||||||
|
className="inline-flex items-center gap-2 rounded-xl border px-5 py-3 font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
|
||||||
|
>
|
||||||
|
<GitHubIcon className="size-4" />
|
||||||
|
{m.viewOnGitHub}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<InstallCommand
|
||||||
|
command={INSTALL_COMMAND}
|
||||||
|
copyLabel={m.copyCommand}
|
||||||
|
copiedLabel={m.copied}
|
||||||
|
className="mt-8 w-full max-w-2xl"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Build-time stats as the initial render; refreshed live on the client. */}
|
||||||
|
<GitHubStatsRow
|
||||||
|
initial={stats}
|
||||||
|
labels={{ stars: m.stars, forks: m.forks, latest: m.latest }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<Features heading={m.featuresHeading} subtitle={m.featuresSubtitle} items={m.features} />
|
||||||
|
|
||||||
|
<Footer prefix={prefix} m={m} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Footer({ prefix, m }: { prefix: string; m: SiteMessages }) {
|
||||||
|
return (
|
||||||
|
<footer className="border-t">
|
||||||
|
<div className="mx-auto flex w-full max-w-6xl flex-col items-center justify-between gap-4 px-4 py-8 text-sm text-fd-muted-foreground sm:flex-row">
|
||||||
|
<div className="inline-flex items-center gap-2">
|
||||||
|
<Logo className="h-6" />
|
||||||
|
<span>
|
||||||
|
{appName} — {m.licenseBefore}
|
||||||
|
<a
|
||||||
|
href={`${productRepoUrl}/blob/main/LICENSE`}
|
||||||
|
className="underline hover:text-fd-foreground"
|
||||||
|
>
|
||||||
|
GPL-3.0
|
||||||
|
</a>
|
||||||
|
{m.licenseAfter}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<nav className="flex items-center gap-4">
|
||||||
|
<Link href={`${prefix}/docs`} className="hover:text-fd-foreground">
|
||||||
|
{m.docs}
|
||||||
|
</Link>
|
||||||
|
<a
|
||||||
|
href={productRepoUrl}
|
||||||
|
className="inline-flex items-center gap-1.5 hover:text-fd-foreground"
|
||||||
|
>
|
||||||
|
<GitHubIcon className="size-4" />
|
||||||
|
GitHub
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={deepWikiUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer noopener"
|
||||||
|
className="inline-flex items-center gap-1.5 hover:text-fd-foreground"
|
||||||
|
>
|
||||||
|
<BookOpen className="size-4" />
|
||||||
|
DeepWiki
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={telegramChannelUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer noopener"
|
||||||
|
className="inline-flex items-center gap-1.5 hover:text-fd-foreground"
|
||||||
|
>
|
||||||
|
<TelegramIcon className="size-4" />
|
||||||
|
Telegram
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={donateUrl}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer noopener"
|
||||||
|
className="inline-flex items-center gap-1.5 hover:text-fd-foreground"
|
||||||
|
>
|
||||||
|
<Heart className="size-4" />
|
||||||
|
{m.donate}
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { getPageImage, getPageMarkdownUrl, source } from '@/lib/source';
|
||||||
|
import {
|
||||||
|
DocsBody,
|
||||||
|
DocsDescription,
|
||||||
|
DocsPage,
|
||||||
|
DocsTitle,
|
||||||
|
MarkdownCopyButton,
|
||||||
|
ViewOptionsPopover,
|
||||||
|
} from 'fumadocs-ui/layouts/docs/page';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
import { getMDXComponents } from '@/components/mdx';
|
||||||
|
import { OpenAPIPage as BaseOpenAPIPage } from '@/components/openapi-page';
|
||||||
|
import { openapi } from '@/lib/openapi';
|
||||||
|
import type { Metadata } from 'next';
|
||||||
|
import type { ComponentProps } from 'react';
|
||||||
|
import { createRelativeLink } from 'fumadocs-ui/mdx';
|
||||||
|
import { gitConfig } from '@/lib/shared';
|
||||||
|
|
||||||
|
export default async function Page(props: PageProps<'/[lang]/docs/[[...slug]]'>) {
|
||||||
|
const { lang, slug } = await props.params;
|
||||||
|
const page = source.getPage(slug, lang);
|
||||||
|
if (!page) notFound();
|
||||||
|
|
||||||
|
const MDX = page.data.body;
|
||||||
|
const markdownUrl = getPageMarkdownUrl(page).url;
|
||||||
|
const editUrl = `https://github.com/${gitConfig.user}/${gitConfig.repo}/blob/${gitConfig.branch}/${gitConfig.docsDir}/${page.path}`;
|
||||||
|
|
||||||
|
// Generated API reference pages carry `_openapi` metadata. Preload the spec
|
||||||
|
// on the server (highlighting included) so the client OpenAPIPage doesn't have
|
||||||
|
// to load it at render time.
|
||||||
|
const isOpenAPI = Boolean((page.data as { _openapi?: unknown })._openapi);
|
||||||
|
const extraComponents: Record<string, unknown> = {};
|
||||||
|
if (isOpenAPI) {
|
||||||
|
const preloaded = await openapi.preloadOpenAPIPage(page);
|
||||||
|
function PreloadedOpenAPIPage(p: ComponentProps<typeof BaseOpenAPIPage>) {
|
||||||
|
return <BaseOpenAPIPage {...p} {...preloaded} />;
|
||||||
|
}
|
||||||
|
extraComponents.OpenAPIPage = PreloadedOpenAPIPage;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DocsPage toc={page.data.toc} full={page.data.full}>
|
||||||
|
<DocsTitle>{page.data.title}</DocsTitle>
|
||||||
|
<DocsDescription className="mb-0">{page.data.description}</DocsDescription>
|
||||||
|
<div className="flex flex-row items-center gap-2 border-b pb-6">
|
||||||
|
<MarkdownCopyButton markdownUrl={markdownUrl} />
|
||||||
|
<ViewOptionsPopover markdownUrl={markdownUrl} githubUrl={editUrl} />
|
||||||
|
</div>
|
||||||
|
<DocsBody>
|
||||||
|
<MDX
|
||||||
|
components={getMDXComponents({
|
||||||
|
// allows linking to other pages with relative file paths
|
||||||
|
a: createRelativeLink(source, page),
|
||||||
|
...extraComponents,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
</DocsBody>
|
||||||
|
</DocsPage>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateStaticParams() {
|
||||||
|
return source.generateParams();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata(
|
||||||
|
props: PageProps<'/[lang]/docs/[[...slug]]'>,
|
||||||
|
): Promise<Metadata> {
|
||||||
|
const { lang, slug } = await props.params;
|
||||||
|
const page = source.getPage(slug, lang);
|
||||||
|
if (!page) notFound();
|
||||||
|
|
||||||
|
return {
|
||||||
|
title: page.data.title,
|
||||||
|
description: page.data.description,
|
||||||
|
openGraph: {
|
||||||
|
images: getPageImage(page).url,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { source } from '@/lib/source';
|
||||||
|
import { DocsLayout } from 'fumadocs-ui/layouts/docs';
|
||||||
|
import { baseOptions } from '@/lib/layout.shared';
|
||||||
|
|
||||||
|
export default async function Layout({ params, children }: LayoutProps<'/[lang]/docs'>) {
|
||||||
|
const { lang } = await params;
|
||||||
|
return (
|
||||||
|
<DocsLayout tree={source.getPageTree(lang)} {...baseOptions(lang)}>
|
||||||
|
{children}
|
||||||
|
</DocsLayout>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import '../global.css';
|
||||||
|
import { RootProvider } from 'fumadocs-ui/provider/next';
|
||||||
|
import { Inter, Vazirmatn } from 'next/font/google';
|
||||||
|
import { i18n, localeDirection } from '@/lib/i18n';
|
||||||
|
import { provider } from '@/lib/i18n-ui';
|
||||||
|
import SearchDialog from '@/components/search-dialog';
|
||||||
|
|
||||||
|
const inter = Inter({ subsets: ['latin'], display: 'swap' });
|
||||||
|
// Persian UI font; covers Arabic + Latin glyphs so mixed content renders well.
|
||||||
|
const vazirmatn = Vazirmatn({ subsets: ['arabic'], display: 'swap' });
|
||||||
|
|
||||||
|
export function generateStaticParams() {
|
||||||
|
return i18n.languages.map((lang) => ({ lang }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function LangLayout({ params, children }: LayoutProps<'/[lang]'>) {
|
||||||
|
const { lang } = await params;
|
||||||
|
const dir = localeDirection(lang);
|
||||||
|
const fontClassName = lang === 'fa' ? vazirmatn.className : inter.className;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<html lang={lang} dir={dir} className={fontClassName} suppressHydrationWarning>
|
||||||
|
<body className="flex min-h-screen flex-col" suppressHydrationWarning>
|
||||||
|
<RootProvider i18n={provider(lang)} search={{ SearchDialog }}>
|
||||||
|
{children}
|
||||||
|
</RootProvider>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { source } from '@/lib/source';
|
||||||
|
import { createFromSource } from 'fumadocs-core/search/server';
|
||||||
|
|
||||||
|
// Required for `output: 'export'` — the search index is fully static.
|
||||||
|
export const revalidate = false;
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
|
||||||
|
// Static search index: works under both SSR/Vercel and static export
|
||||||
|
// (`output: 'export'`). The client loads this prebuilt index and searches
|
||||||
|
// in-browser (see the `type: 'static'` search option in app/[lang]/layout.tsx).
|
||||||
|
// All locales currently hold English (fallback) content, and Orama has no
|
||||||
|
// Persian tokenizer, so map every locale to the English tokenizer. When real
|
||||||
|
// translations land, switch ru -> 'russian', zh -> 'mandarin' (with
|
||||||
|
// @orama/tokenizers), etc. See https://docs.orama.com/open-source/supported-languages
|
||||||
|
export const { staticGET: GET } = createFromSource(source, {
|
||||||
|
localeMap: {
|
||||||
|
en: 'english',
|
||||||
|
fa: 'english',
|
||||||
|
ru: 'english',
|
||||||
|
zh: 'english',
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
@import 'tailwindcss';
|
||||||
|
@import 'fumadocs-ui/css/neutral.css';
|
||||||
|
@import 'fumadocs-ui/css/preset.css';
|
||||||
|
|
||||||
|
/* 3x-ui brand: cyan / turquoise accent (matches the panel logo). */
|
||||||
|
:root {
|
||||||
|
--color-fd-primary: hsl(190, 95%, 39%);
|
||||||
|
--color-fd-primary-foreground: hsl(0, 0%, 100%);
|
||||||
|
--color-fd-ring: hsl(190, 95%, 39%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark {
|
||||||
|
--color-fd-primary: hsl(187, 90%, 55%);
|
||||||
|
--color-fd-primary-foreground: hsl(190, 80%, 8%);
|
||||||
|
--color-fd-ring: hsl(187, 90%, 55%);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Expose the brand color as Tailwind utilities (bg-brand, text-brand, ...). */
|
||||||
|
@theme {
|
||||||
|
--color-brand: hsl(190, 95%, 39%);
|
||||||
|
--color-brand-foreground: hsl(0, 0%, 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
scrollbar-gutter: stable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* In RTL the scroll-lock padding must be applied to the logical inline-end. */
|
||||||
|
html > body[data-scroll-locked] {
|
||||||
|
margin-inline-end: 0px !important;
|
||||||
|
--removed-body-scroll-bar-size: 0px !important;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { appName, appTagline, siteUrl } from '@/lib/shared';
|
||||||
|
|
||||||
|
// Global SEO defaults. The real <html>/<body> live in `app/[lang]/layout.tsx`
|
||||||
|
// so we can set `lang`/`dir` per locale (RTL for fa); this root layout is a
|
||||||
|
// pass-through that only carries site-wide metadata.
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
metadataBase: new URL(siteUrl),
|
||||||
|
title: {
|
||||||
|
default: `${appName} — ${appTagline}`,
|
||||||
|
template: `%s — ${appName}`,
|
||||||
|
},
|
||||||
|
description: appTagline,
|
||||||
|
applicationName: appName,
|
||||||
|
openGraph: {
|
||||||
|
siteName: appName,
|
||||||
|
type: 'website',
|
||||||
|
},
|
||||||
|
twitter: {
|
||||||
|
card: 'summary_large_image',
|
||||||
|
},
|
||||||
|
icons: {
|
||||||
|
icon: '/favicon.png',
|
||||||
|
apple: '/icon.png',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||||
|
return children;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { getLLMText, source } from '@/lib/source';
|
||||||
|
|
||||||
|
export const revalidate = false;
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
const scan = source.getPages().map(getLLMText);
|
||||||
|
const scanned = await Promise.all(scan);
|
||||||
|
|
||||||
|
return new Response(scanned.join('\n\n'));
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { getLLMText, getPageMarkdownUrl, source } from '@/lib/source';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
|
export const revalidate = false;
|
||||||
|
|
||||||
|
export async function GET(_req: Request, { params }: RouteContext<'/llms.mdx/docs/[[...slug]]'>) {
|
||||||
|
const { slug } = await params;
|
||||||
|
const page = source.getPage(slug?.slice(0, -1));
|
||||||
|
if (!page) notFound();
|
||||||
|
|
||||||
|
return new Response(await getLLMText(page), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'text/markdown',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateStaticParams() {
|
||||||
|
return source.getPages().map((page) => ({
|
||||||
|
lang: page.locale,
|
||||||
|
slug: getPageMarkdownUrl(page).segments,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { source } from '@/lib/source';
|
||||||
|
import { llms } from 'fumadocs-core/source';
|
||||||
|
|
||||||
|
export const revalidate = false;
|
||||||
|
|
||||||
|
export function GET() {
|
||||||
|
return new Response(llms(source).index());
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { getPageImage, source } from '@/lib/source';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
import { ImageResponse } from 'next/og';
|
||||||
|
import { generate as DefaultImage } from 'fumadocs-ui/og';
|
||||||
|
import { appName } from '@/lib/shared';
|
||||||
|
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
export const revalidate = false;
|
||||||
|
|
||||||
|
export async function GET(_req: Request, { params }: RouteContext<'/og/docs/[...slug]'>) {
|
||||||
|
const { slug } = await params;
|
||||||
|
const page = source.getPage(slug.slice(0, -1));
|
||||||
|
if (!page) notFound();
|
||||||
|
|
||||||
|
return new ImageResponse(
|
||||||
|
<DefaultImage title={page.data.title} description={page.data.description} site={appName} />,
|
||||||
|
{
|
||||||
|
width: 1200,
|
||||||
|
height: 630,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateStaticParams() {
|
||||||
|
return source.getPages().map((page) => ({
|
||||||
|
lang: page.locale,
|
||||||
|
slug: getPageImage(page).segments,
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import type { MetadataRoute } from 'next';
|
||||||
|
import { siteUrl } from '@/lib/shared';
|
||||||
|
|
||||||
|
// Required for `output: 'export'`.
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
|
||||||
|
export default function robots(): MetadataRoute.Robots {
|
||||||
|
return {
|
||||||
|
rules: { userAgent: '*', allow: '/' },
|
||||||
|
sitemap: `${siteUrl}/sitemap.xml`,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { MetadataRoute } from 'next';
|
||||||
|
import { source } from '@/lib/source';
|
||||||
|
import { i18n } from '@/lib/i18n';
|
||||||
|
import { siteUrl } from '@/lib/shared';
|
||||||
|
|
||||||
|
// Required for `output: 'export'`.
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
|
||||||
|
// Locale home pages + the canonical (English) docs pages. Other locales
|
||||||
|
// currently fall back to English content, so we don't list them separately
|
||||||
|
// to avoid duplicate-content entries until real translations exist.
|
||||||
|
export default function sitemap(): MetadataRoute.Sitemap {
|
||||||
|
const entries: MetadataRoute.Sitemap = [];
|
||||||
|
|
||||||
|
for (const lang of i18n.languages) {
|
||||||
|
const prefix = lang === 'en' ? '' : `/${lang}`;
|
||||||
|
entries.push({
|
||||||
|
url: `${siteUrl}${prefix}` || siteUrl,
|
||||||
|
changeFrequency: 'weekly',
|
||||||
|
priority: 1,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const page of source.getPages('en')) {
|
||||||
|
entries.push({
|
||||||
|
url: `${siteUrl}${page.url}`,
|
||||||
|
changeFrequency: 'weekly',
|
||||||
|
priority: 0.8,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
@@ -0,0 +1,587 @@
|
|||||||
|
# 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-multi` Telegram-proxy binary (`github.com/mhsanaei/mtg-multi`, a
|
||||||
|
multi-secret fork built from source; `internal/mtproto/`). One process per inbound serves
|
||||||
|
every attached client's FakeTLS secret through the fork's `[secrets]` section, plus optional
|
||||||
|
per-client sponsored-channel ad-tags via `[secret-ad-tags]`. A client or ad-tag edit is
|
||||||
|
hot-applied via the fork's management API (`PUT /secrets`, guarded by a per-process bearer
|
||||||
|
token), with a process restart as the fallback on older binaries.
|
||||||
|
|
||||||
|
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-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | 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 the native **Fetch API**; **Zod 4** schemas.
|
||||||
|
- Router: **react-router-dom 7**. Charts: **uPlot** (`frontend/src/components/viz/Sparkline.tsx`). 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, fetch)
|
||||||
|
→ 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: http-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 |
|
||||||
|
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
|
||||||
|
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
|
||||||
|
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")` | IP-limit and Xray access/error log cleanup; traffic 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.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import {
|
||||||
|
Boxes,
|
||||||
|
Network,
|
||||||
|
Send,
|
||||||
|
ShieldCheck,
|
||||||
|
TerminalSquare,
|
||||||
|
Users,
|
||||||
|
type LucideIcon,
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
// Icons map by position to the localized feature items in lib/site-i18n.ts
|
||||||
|
// (Every major protocol, REALITY, Clients, Multi-node, Telegram, Self-hosted).
|
||||||
|
const ICONS: LucideIcon[] = [Boxes, ShieldCheck, Users, Network, Send, TerminalSquare];
|
||||||
|
|
||||||
|
export function Features({
|
||||||
|
heading,
|
||||||
|
subtitle,
|
||||||
|
items,
|
||||||
|
}: {
|
||||||
|
heading: string;
|
||||||
|
subtitle: string;
|
||||||
|
items: { title: string; description: string }[];
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section className="mx-auto w-full max-w-6xl px-4 py-16 sm:py-24">
|
||||||
|
<div className="mx-auto max-w-2xl text-center">
|
||||||
|
<h2 className="text-2xl font-bold tracking-tight sm:text-3xl">{heading}</h2>
|
||||||
|
<p className="mt-3 text-fd-muted-foreground">{subtitle}</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-12 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{items.map(({ title, description }, i) => {
|
||||||
|
const Icon = ICONS[i] ?? Boxes;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={title}
|
||||||
|
className="rounded-2xl border bg-fd-card p-6 transition-colors hover:border-fd-primary/40"
|
||||||
|
>
|
||||||
|
<div className="inline-flex size-11 items-center justify-center rounded-xl bg-brand/10 text-brand">
|
||||||
|
<Icon className="size-6" aria-hidden />
|
||||||
|
</div>
|
||||||
|
<h3 className="mt-4 font-semibold">{title}</h3>
|
||||||
|
<p className="mt-2 text-sm text-fd-muted-foreground">{description}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { GitFork, Star, Tag } from 'lucide-react';
|
||||||
|
import { fetchGitHubStats, formatCount, type GitHubStats } from '@/lib/github-stats';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stars / forks / latest-release row. Renders the build-time numbers
|
||||||
|
* immediately (no layout shift, works without JS), then swaps in live ones
|
||||||
|
* from the GitHub API after hydration.
|
||||||
|
*/
|
||||||
|
export function GitHubStatsRow({
|
||||||
|
initial,
|
||||||
|
labels,
|
||||||
|
}: {
|
||||||
|
initial: GitHubStats;
|
||||||
|
labels: { stars: string; forks: string; latest: string };
|
||||||
|
}) {
|
||||||
|
const [stats, setStats] = useState(initial);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
// Plain fetch, no custom headers — keeps the request preflight-free.
|
||||||
|
void fetchGitHubStats().then((live) => {
|
||||||
|
if (cancelled || !live) return;
|
||||||
|
setStats((prev) => ({ ...live, latestVersion: live.latestVersion || prev.latestVersion }));
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<dl className="mt-8 flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-sm">
|
||||||
|
<Stat icon={<Star className="size-4" aria-hidden />} label={labels.stars}>
|
||||||
|
{formatCount(stats.stars)}
|
||||||
|
</Stat>
|
||||||
|
<Stat icon={<GitFork className="size-4" aria-hidden />} label={labels.forks}>
|
||||||
|
{formatCount(stats.forks)}
|
||||||
|
</Stat>
|
||||||
|
<Stat icon={<Tag className="size-4" aria-hidden />} label={labels.latest}>
|
||||||
|
{stats.latestVersion}
|
||||||
|
</Stat>
|
||||||
|
</dl>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stat({
|
||||||
|
icon,
|
||||||
|
label,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
icon: React.ReactNode;
|
||||||
|
label: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="inline-flex items-center gap-2">
|
||||||
|
<span className="text-brand">{icon}</span>
|
||||||
|
<dt className="sr-only">{label}</dt>
|
||||||
|
<dd>
|
||||||
|
<span className="font-semibold">{children}</span>{' '}
|
||||||
|
<span className="text-fd-muted-foreground">{label}</span>
|
||||||
|
</dd>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Check, Copy } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/cn';
|
||||||
|
|
||||||
|
export function InstallCommand({
|
||||||
|
command,
|
||||||
|
className,
|
||||||
|
copyLabel = 'Copy install command',
|
||||||
|
copiedLabel = 'Copied',
|
||||||
|
}: {
|
||||||
|
command: string;
|
||||||
|
className?: string;
|
||||||
|
copyLabel?: string;
|
||||||
|
copiedLabel?: string;
|
||||||
|
}) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(command);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
} catch {
|
||||||
|
// Clipboard unavailable (insecure context) — silently ignore.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'flex items-center gap-3 rounded-xl border bg-fd-card py-2.5 pe-2 ps-4 text-sm shadow-sm',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className="select-none font-mono text-fd-muted-foreground">$</span>
|
||||||
|
{/* Commands are always LTR, even on RTL pages. */}
|
||||||
|
<code dir="ltr" className="flex-1 overflow-x-auto whitespace-nowrap text-start font-mono">
|
||||||
|
{command}
|
||||||
|
</code>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={copy}
|
||||||
|
aria-label={copied ? copiedLabel : copyLabel}
|
||||||
|
className="inline-flex size-8 shrink-0 items-center justify-center rounded-lg text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground focus-visible:outline-2 focus-visible:outline-fd-ring"
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="size-4 text-brand" aria-hidden />
|
||||||
|
) : (
|
||||||
|
<Copy className="size-4" aria-hidden />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
|
import { Languages } from 'lucide-react';
|
||||||
|
import { i18n, locales } from '@/lib/i18n';
|
||||||
|
import { cn } from '@/lib/cn';
|
||||||
|
|
||||||
|
// Home-navbar language switcher.
|
||||||
|
//
|
||||||
|
// fumadocs' built-in popover switcher (`LanguageSelect`) has its item clicks
|
||||||
|
// swallowed when it is nested inside HomeLayout's Radix `NavigationMenu` — the
|
||||||
|
// dropdown opens but selecting a locale never fires `onChange`/`router.push`.
|
||||||
|
// The docs sidebar isn't wrapped in a NavigationMenu, so the built-in one works
|
||||||
|
// there and is kept. Here we use a native `<details>` toggle + real `<Link>`
|
||||||
|
// anchors, which navigate reliably inside the navbar (like the other nav links).
|
||||||
|
//
|
||||||
|
// The home navbar only renders on the landing page, so the targets are simply
|
||||||
|
// each locale's home (`/`, `/fa`, `/ru`, `/zh`).
|
||||||
|
export function HomeLanguageSwitcher({ current }: { current: string }) {
|
||||||
|
return (
|
||||||
|
<details className="group relative [&>summary::-webkit-details-marker]:hidden">
|
||||||
|
<summary
|
||||||
|
aria-label="Choose a language"
|
||||||
|
className="flex cursor-pointer list-none items-center rounded-lg p-1.5 text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground group-open:bg-fd-accent"
|
||||||
|
>
|
||||||
|
<Languages className="size-5" />
|
||||||
|
</summary>
|
||||||
|
<div className="absolute end-0 z-50 mt-1.5 flex min-w-40 flex-col gap-0.5 rounded-lg border bg-fd-popover p-1 text-fd-popover-foreground shadow-lg">
|
||||||
|
<p className="p-2 text-xs font-medium text-fd-muted-foreground">Choose a language</p>
|
||||||
|
{locales.map(({ locale, name }) => (
|
||||||
|
<Link
|
||||||
|
key={locale}
|
||||||
|
href={locale === i18n.defaultLanguage ? '/' : `/${locale}`}
|
||||||
|
className={cn(
|
||||||
|
'rounded-md px-2 py-1.5 text-start text-sm transition-colors',
|
||||||
|
locale === current
|
||||||
|
? 'bg-fd-primary/10 text-fd-primary'
|
||||||
|
: 'text-fd-muted-foreground hover:bg-fd-accent hover:text-fd-accent-foreground',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{name}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Brand icons that are not part of lucide-react.
|
||||||
|
|
||||||
|
export function GitHubIcon({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden>
|
||||||
|
<path d="M12 .5C5.73.5.5 5.74.5 12.02c0 5.08 3.29 9.39 7.86 10.91.58.11.79-.25.79-.56 0-.27-.01-1.16-.02-2.1-3.2.7-3.88-1.36-3.88-1.36-.52-1.33-1.28-1.69-1.28-1.69-1.05-.72.08-.7.08-.7 1.16.08 1.77 1.19 1.77 1.19 1.03 1.77 2.7 1.26 3.36.96.1-.75.4-1.26.73-1.55-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.46.11-3.05 0 0 .97-.31 3.18 1.18a11.03 11.03 0 0 1 5.8 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.59.23 2.76.11 3.05.74.81 1.18 1.84 1.18 3.1 0 4.42-2.69 5.39-5.25 5.68.41.36.78 1.06.78 2.14 0 1.55-.01 2.8-.01 3.18 0 .31.21.68.8.56A10.53 10.53 0 0 0 23.5 12.02C23.5 5.74 18.27.5 12 .5Z" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TelegramIcon({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" className={className} fill="currentColor" aria-hidden>
|
||||||
|
<path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.139-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { cn } from '@/lib/cn';
|
||||||
|
|
||||||
|
// Official 3x-ui logo (media/3x-ui-{light,dark}.png from the upstream repo).
|
||||||
|
// Theme-aware via Tailwind's `dark:` variant. Pass a height class (e.g. `h-6`);
|
||||||
|
// width scales automatically (the artwork is 2:1).
|
||||||
|
export function Logo({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src="/logo-light.png" alt="3x-ui" className={cn('w-auto dark:hidden', className)} />
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img src="/logo-dark.png" alt="3x-ui" className={cn('hidden w-auto dark:block', className)} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import defaultMdxComponents from 'fumadocs-ui/mdx';
|
||||||
|
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
|
||||||
|
import { Step, Steps } from 'fumadocs-ui/components/steps';
|
||||||
|
import { Mermaid } from '@/components/mdx/mermaid';
|
||||||
|
import { RealityConfigGenerator } from '@/components/tools/reality-config-generator';
|
||||||
|
import { ShareLinkInspector } from '@/components/tools/share-link-inspector';
|
||||||
|
import { InstallCommandBuilder } from '@/components/tools/install-command-builder';
|
||||||
|
import { ReverseProxyGenerator } from '@/components/tools/reverse-proxy-generator';
|
||||||
|
import { ProtocolWizard } from '@/components/tools/protocol-wizard';
|
||||||
|
import { FirewallRulesGenerator } from '@/components/tools/firewall-rules-generator';
|
||||||
|
import { OutboundGenerator } from '@/components/tools/outbound-generator';
|
||||||
|
import { RoutingBuilder } from '@/components/tools/routing-builder';
|
||||||
|
import { SubscriptionBuilder } from '@/components/tools/subscription-builder';
|
||||||
|
import { TelegramSetupHelper } from '@/components/tools/telegram-setup-helper';
|
||||||
|
import { ApiRequestBuilder } from '@/components/tools/api-request-builder';
|
||||||
|
import { OpenAPIPage } from '@/components/openapi-page';
|
||||||
|
import type { MDXComponents } from 'mdx/types';
|
||||||
|
|
||||||
|
export function getMDXComponents(components?: MDXComponents) {
|
||||||
|
return {
|
||||||
|
...defaultMdxComponents,
|
||||||
|
Tab,
|
||||||
|
Tabs,
|
||||||
|
Step,
|
||||||
|
Steps,
|
||||||
|
Mermaid,
|
||||||
|
RealityConfigGenerator,
|
||||||
|
ShareLinkInspector,
|
||||||
|
InstallCommandBuilder,
|
||||||
|
ReverseProxyGenerator,
|
||||||
|
ProtocolWizard,
|
||||||
|
FirewallRulesGenerator,
|
||||||
|
OutboundGenerator,
|
||||||
|
RoutingBuilder,
|
||||||
|
SubscriptionBuilder,
|
||||||
|
TelegramSetupHelper,
|
||||||
|
ApiRequestBuilder,
|
||||||
|
OpenAPIPage,
|
||||||
|
...components,
|
||||||
|
} satisfies MDXComponents;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useMDXComponents = getMDXComponents;
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
type MDXProvidedComponents = ReturnType<typeof getMDXComponents>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useId, useState } from 'react';
|
||||||
|
import { useTheme } from 'next-themes';
|
||||||
|
|
||||||
|
// Client-side, theme-aware Mermaid renderer. Mermaid is imported dynamically so
|
||||||
|
// it stays out of the initial bundle and only loads on pages that use a diagram.
|
||||||
|
export function Mermaid({ chart }: { chart: string }) {
|
||||||
|
const rawId = useId();
|
||||||
|
const id = `mmd-${rawId.replace(/[^a-zA-Z0-9]/g, '')}`;
|
||||||
|
const { resolvedTheme } = useTheme();
|
||||||
|
const [svg, setSvg] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
void (async () => {
|
||||||
|
const mermaid = (await import('mermaid')).default;
|
||||||
|
mermaid.initialize({
|
||||||
|
startOnLoad: false,
|
||||||
|
securityLevel: 'strict',
|
||||||
|
theme: resolvedTheme === 'dark' ? 'dark' : 'default',
|
||||||
|
fontFamily: 'inherit',
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const { svg } = await mermaid.render(id, chart.trim());
|
||||||
|
if (active) setSvg(svg);
|
||||||
|
} catch {
|
||||||
|
if (active) setSvg('');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [chart, resolvedTheme, id]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="my-6 flex justify-center overflow-x-auto rounded-xl border bg-fd-card p-4 [&_svg]:max-w-full"
|
||||||
|
role="img"
|
||||||
|
aria-label="Architecture diagram"
|
||||||
|
dangerouslySetInnerHTML={{ __html: svg }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { createOpenAPIPage } from 'fumadocs-openapi/ui';
|
||||||
|
|
||||||
|
// The component used by the generated API reference MDX pages.
|
||||||
|
export const OpenAPIPage = createOpenAPIPage();
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { create } from '@orama/orama';
|
||||||
|
import { useDocsSearch } from 'fumadocs-core/search/client';
|
||||||
|
import { oramaStaticClient } from 'fumadocs-core/search/client/orama-static';
|
||||||
|
import {
|
||||||
|
SearchDialog,
|
||||||
|
SearchDialogClose,
|
||||||
|
SearchDialogContent,
|
||||||
|
SearchDialogHeader,
|
||||||
|
SearchDialogIcon,
|
||||||
|
SearchDialogInput,
|
||||||
|
SearchDialogList,
|
||||||
|
SearchDialogOverlay,
|
||||||
|
} from 'fumadocs-ui/components/dialog/search';
|
||||||
|
import { useI18n } from 'fumadocs-ui/contexts/i18n';
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
|
||||||
|
interface SharedProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The static search index is keyed by locale code (en/fa/ru/zh). Fumadocs'
|
||||||
|
// default static dialog feeds those codes to Orama as a tokenizer language, but
|
||||||
|
// Orama only accepts full names ("english") and throws on "en" — which silently
|
||||||
|
// breaks search entirely. All docs content is English (other locales fall back
|
||||||
|
// to it), so re-create the dialog — the documented escape hatch for custom Orama
|
||||||
|
// setups — with an initOrama that always builds an English index.
|
||||||
|
export default function SearchDialogClient(props: SharedProps) {
|
||||||
|
const { locale } = useI18n();
|
||||||
|
const client = useMemo(
|
||||||
|
() =>
|
||||||
|
oramaStaticClient({
|
||||||
|
from: '/api/search',
|
||||||
|
locale,
|
||||||
|
initOrama: () => create({ schema: { _: 'string' }, language: 'english' }),
|
||||||
|
}),
|
||||||
|
[locale],
|
||||||
|
);
|
||||||
|
const { search, setSearch, query } = useDocsSearch({ client });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SearchDialog search={search} onSearchChange={setSearch} isLoading={query.isLoading} {...props}>
|
||||||
|
<SearchDialogOverlay />
|
||||||
|
<SearchDialogContent>
|
||||||
|
<SearchDialogHeader>
|
||||||
|
<SearchDialogIcon />
|
||||||
|
<SearchDialogInput />
|
||||||
|
<SearchDialogClose />
|
||||||
|
</SearchDialogHeader>
|
||||||
|
<SearchDialogList items={query.data !== 'empty' ? query.data : null} />
|
||||||
|
</SearchDialogContent>
|
||||||
|
</SearchDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useId, useState } from 'react';
|
||||||
|
import { buildCurl, buildFetchSnippet, type ApiRequestInput, type HttpMethod } from '@/lib/xray/api-client';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
const METHODS: readonly HttpMethod[] = ['GET', 'POST', 'PUT', 'DELETE'];
|
||||||
|
|
||||||
|
export function ApiRequestBuilder() {
|
||||||
|
const [baseUrl, setBaseUrl] = useState('https://panel.example.com:2053');
|
||||||
|
const [token, setToken] = useState('');
|
||||||
|
const [path, setPath] = useState('/panel/api/inbounds/list');
|
||||||
|
const [method, setMethod] = useState<HttpMethod>('GET');
|
||||||
|
const [body, setBody] = useState('');
|
||||||
|
const bodyId = useId();
|
||||||
|
|
||||||
|
const showBody = method === 'POST' || method === 'PUT';
|
||||||
|
const input: ApiRequestInput = { baseUrl, token: token || '<token>', path, method, body };
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setBaseUrl('https://panel.example.com:2053');
|
||||||
|
setToken('');
|
||||||
|
setPath('/panel/api/inbounds/list');
|
||||||
|
setMethod('GET');
|
||||||
|
setBody('');
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="API request builder"
|
||||||
|
description="Build an authenticated cURL command or fetch() snippet for any 3x-ui panel API endpoint under /panel/api/*."
|
||||||
|
onReset={reset}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<TextField label="Panel base URL" value={baseUrl} onChange={setBaseUrl} />
|
||||||
|
<TextField
|
||||||
|
label="API token (Bearer)"
|
||||||
|
value={token}
|
||||||
|
onChange={setToken}
|
||||||
|
placeholder="Settings → Security → API Token"
|
||||||
|
/>
|
||||||
|
<TextField label="Endpoint path" value={path} onChange={setPath} />
|
||||||
|
<SelectField
|
||||||
|
label="Method"
|
||||||
|
value={method}
|
||||||
|
onChange={(v) => setMethod(v as HttpMethod)}
|
||||||
|
options={METHODS}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showBody ? (
|
||||||
|
<div className="mt-4 flex flex-col gap-1.5">
|
||||||
|
<label htmlFor={bodyId} className="text-sm font-medium">
|
||||||
|
Request body (JSON)
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
id={bodyId}
|
||||||
|
dir="ltr"
|
||||||
|
value={body}
|
||||||
|
onChange={(e) => setBody(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
placeholder='{"id": 1}'
|
||||||
|
className="rounded-lg border bg-fd-background px-3 py-2 font-mono text-sm outline-none transition-colors focus-visible:border-fd-primary focus-visible:ring-2 focus-visible:ring-fd-ring/30"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="cURL" value={buildCurl(input)} />
|
||||||
|
<OutputBlock label="fetch()" value={buildFetchSnippet(input)} />
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildUfwCommands,
|
||||||
|
buildNftablesRuleset,
|
||||||
|
type FirewallOptions,
|
||||||
|
type PortProtocol,
|
||||||
|
type PortRule,
|
||||||
|
} from '@/lib/xray/firewall';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { CheckboxField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
interface Row {
|
||||||
|
label: string;
|
||||||
|
port: string;
|
||||||
|
protocol: PortProtocol;
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_ROWS: Row[] = [
|
||||||
|
{ label: 'panel', port: '2053', protocol: 'tcp', enabled: true },
|
||||||
|
{ label: 'subscription', port: '2096', protocol: 'tcp', enabled: false },
|
||||||
|
{ label: 'inbound (HTTPS)', port: '443', protocol: 'tcp', enabled: true },
|
||||||
|
{ label: 'inbound (UDP)', port: '443', protocol: 'udp', enabled: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function FirewallRulesGenerator() {
|
||||||
|
const [allowSsh, setAllowSsh] = useState(true);
|
||||||
|
const [sshPort] = useState('22');
|
||||||
|
const [rows, setRows] = useState<Row[]>(DEFAULT_ROWS);
|
||||||
|
|
||||||
|
function toggle(index: number, enabled: boolean) {
|
||||||
|
setRows((prev) => prev.map((r, i) => (i === index ? { ...r, enabled } : r)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const ports: PortRule[] = rows
|
||||||
|
.filter((r) => r.enabled && Number(r.port) > 0)
|
||||||
|
.map((r) => ({ port: Number(r.port), protocol: r.protocol, label: r.label }));
|
||||||
|
|
||||||
|
const options: FirewallOptions = { ports, allowSsh, sshPort: Number(sshPort) || 22 };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Firewall rules generator"
|
||||||
|
description="Pick the ports to open and copy ready-made ufw and nftables rules."
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<CheckboxField
|
||||||
|
label={`Allow SSH (port ${sshPort})`}
|
||||||
|
checked={allowSsh}
|
||||||
|
onChange={setAllowSsh}
|
||||||
|
/>
|
||||||
|
{rows.map((row, i) => (
|
||||||
|
<CheckboxField
|
||||||
|
key={`${row.label}-${row.protocol}`}
|
||||||
|
label={`${row.label} — ${row.port}/${row.protocol}`}
|
||||||
|
checked={row.enabled}
|
||||||
|
onChange={(c) => toggle(i, c)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="ufw" value={buildUfwCommands(options)} />
|
||||||
|
<OutputBlock label="nftables (/etc/nftables.conf)" value={buildNftablesRuleset(options)} />
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildScriptCommand,
|
||||||
|
buildDockerRun,
|
||||||
|
buildDockerCompose,
|
||||||
|
type InstallMethod,
|
||||||
|
type InstallOptions,
|
||||||
|
} from '@/lib/xray/install';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField, CheckboxField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
export function InstallCommandBuilder() {
|
||||||
|
const [method, setMethod] = useState<InstallMethod>('script');
|
||||||
|
const [version, setVersion] = useState('');
|
||||||
|
const [enableFail2ban, setEnableFail2ban] = useState(true);
|
||||||
|
const [panelPort, setPanelPort] = useState('');
|
||||||
|
const [webBasePath, setWebBasePath] = useState('');
|
||||||
|
|
||||||
|
const options: InstallOptions = {
|
||||||
|
method,
|
||||||
|
version,
|
||||||
|
enableFail2ban,
|
||||||
|
panelPort,
|
||||||
|
webBasePath,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Install command builder"
|
||||||
|
description="Build the exact install command for your setup. It is assembled in your browser."
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Method"
|
||||||
|
value={method}
|
||||||
|
onChange={(v) => setMethod(v as InstallMethod)}
|
||||||
|
options={['script', 'docker']}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Version"
|
||||||
|
value={version}
|
||||||
|
onChange={setVersion}
|
||||||
|
placeholder="latest"
|
||||||
|
hint="blank = latest stable · a tag like v3.4.0 · or dev-latest for the rolling dev build"
|
||||||
|
/>
|
||||||
|
{method === 'docker' ? (
|
||||||
|
<>
|
||||||
|
<TextField
|
||||||
|
label="Panel port"
|
||||||
|
value={panelPort}
|
||||||
|
onChange={setPanelPort}
|
||||||
|
placeholder="2053"
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Web base path"
|
||||||
|
value={webBasePath}
|
||||||
|
onChange={setWebBasePath}
|
||||||
|
placeholder="/panel"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3">
|
||||||
|
<CheckboxField
|
||||||
|
label="Enable Fail2ban"
|
||||||
|
checked={enableFail2ban}
|
||||||
|
onChange={setEnableFail2ban}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
{method === 'script' ? (
|
||||||
|
<OutputBlock label="Run on your server" value={buildScriptCommand(options)} />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<OutputBlock label="docker run" value={buildDockerRun(options)} />
|
||||||
|
<OutputBlock label="docker-compose.yml" value={buildDockerCompose(options)} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildOutboundJson,
|
||||||
|
type OutboundInput,
|
||||||
|
type OutboundKind,
|
||||||
|
type Network,
|
||||||
|
type Security,
|
||||||
|
type ProxyServerInput,
|
||||||
|
type StreamInput,
|
||||||
|
type WireguardInput,
|
||||||
|
} from '@/lib/xray/outbounds';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
const KINDS: readonly OutboundKind[] = [
|
||||||
|
'freedom',
|
||||||
|
'blackhole',
|
||||||
|
'vless',
|
||||||
|
'vmess',
|
||||||
|
'trojan',
|
||||||
|
'shadowsocks',
|
||||||
|
'socks',
|
||||||
|
'http',
|
||||||
|
'wireguard',
|
||||||
|
'warp',
|
||||||
|
];
|
||||||
|
const NETWORKS: readonly Network[] = ['tcp', 'kcp', 'ws', 'grpc', 'httpupgrade', 'xhttp'];
|
||||||
|
const SECURITIES: readonly Security[] = ['none', 'tls', 'reality'];
|
||||||
|
const FINGERPRINTS = ['chrome', 'firefox', 'safari', 'ios', 'android', 'edge', 'random'];
|
||||||
|
const DOMAIN_STRATEGIES = ['AsIs', 'UseIP', 'UseIPv4', 'UseIPv6', 'ForceIP'];
|
||||||
|
|
||||||
|
const PROXY_KINDS = new Set<OutboundKind>([
|
||||||
|
'vless',
|
||||||
|
'vmess',
|
||||||
|
'trojan',
|
||||||
|
'shadowsocks',
|
||||||
|
'socks',
|
||||||
|
'http',
|
||||||
|
]);
|
||||||
|
const STREAM_KINDS = new Set<OutboundKind>(['vless', 'vmess', 'trojan', 'shadowsocks']);
|
||||||
|
const WG_KINDS = new Set<OutboundKind>(['wireguard', 'warp']);
|
||||||
|
|
||||||
|
export function OutboundGenerator() {
|
||||||
|
const [kind, setKind] = useState<OutboundKind>('vless');
|
||||||
|
const [tag, setTag] = useState('proxy');
|
||||||
|
|
||||||
|
// proxy server
|
||||||
|
const [address, setAddress] = useState('example.com');
|
||||||
|
const [port, setPort] = useState('443');
|
||||||
|
const [id, setId] = useState('');
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [method, setMethod] = useState('2022-blake3-aes-128-gcm');
|
||||||
|
const [flow, setFlow] = useState('');
|
||||||
|
const [username, setUsername] = useState('');
|
||||||
|
|
||||||
|
// stream
|
||||||
|
const [network, setNetwork] = useState<Network>('tcp');
|
||||||
|
const [security, setSecurity] = useState<Security>('reality');
|
||||||
|
const [host, setHost] = useState('');
|
||||||
|
const [path, setPath] = useState('/');
|
||||||
|
const [serviceName, setServiceName] = useState('');
|
||||||
|
const [sni, setSni] = useState('www.microsoft.com');
|
||||||
|
const [fingerprint, setFingerprint] = useState('chrome');
|
||||||
|
const [publicKey, setPublicKey] = useState('');
|
||||||
|
const [shortId, setShortId] = useState('');
|
||||||
|
|
||||||
|
// freedom
|
||||||
|
const [domainStrategy, setDomainStrategy] = useState('AsIs');
|
||||||
|
|
||||||
|
// wireguard
|
||||||
|
const [wgSecretKey, setWgSecretKey] = useState('');
|
||||||
|
const [wgAddress, setWgAddress] = useState('172.16.0.2/32');
|
||||||
|
const [wgPublicKey, setWgPublicKey] = useState('');
|
||||||
|
const [wgEndpoint, setWgEndpoint] = useState('');
|
||||||
|
|
||||||
|
const isProxy = PROXY_KINDS.has(kind);
|
||||||
|
const hasStream = STREAM_KINDS.has(kind);
|
||||||
|
const isWg = WG_KINDS.has(kind);
|
||||||
|
const hasPath = network === 'ws' || network === 'httpupgrade' || network === 'xhttp';
|
||||||
|
|
||||||
|
const server: ProxyServerInput = {
|
||||||
|
address,
|
||||||
|
port: Number(port),
|
||||||
|
id,
|
||||||
|
password,
|
||||||
|
method,
|
||||||
|
flow,
|
||||||
|
username,
|
||||||
|
};
|
||||||
|
|
||||||
|
const stream: StreamInput = {
|
||||||
|
network,
|
||||||
|
security,
|
||||||
|
host,
|
||||||
|
path,
|
||||||
|
serviceName,
|
||||||
|
sni,
|
||||||
|
fingerprint,
|
||||||
|
publicKey,
|
||||||
|
shortId,
|
||||||
|
};
|
||||||
|
|
||||||
|
const wireguard: WireguardInput = {
|
||||||
|
secretKey: wgSecretKey,
|
||||||
|
address: wgAddress
|
||||||
|
.split(',')
|
||||||
|
.map((a) => a.trim())
|
||||||
|
.filter(Boolean),
|
||||||
|
publicKey: wgPublicKey,
|
||||||
|
endpoint: wgEndpoint,
|
||||||
|
};
|
||||||
|
|
||||||
|
const input: OutboundInput = {
|
||||||
|
kind,
|
||||||
|
tag,
|
||||||
|
server: isProxy ? server : undefined,
|
||||||
|
wireguard: isWg ? wireguard : undefined,
|
||||||
|
stream: hasStream ? stream : undefined,
|
||||||
|
domainStrategy: kind === 'freedom' ? domainStrategy : undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setKind('vless');
|
||||||
|
setTag('proxy');
|
||||||
|
setAddress('example.com');
|
||||||
|
setPort('443');
|
||||||
|
setId('');
|
||||||
|
setPassword('');
|
||||||
|
setMethod('2022-blake3-aes-128-gcm');
|
||||||
|
setFlow('');
|
||||||
|
setUsername('');
|
||||||
|
setNetwork('tcp');
|
||||||
|
setSecurity('reality');
|
||||||
|
setHost('');
|
||||||
|
setPath('/');
|
||||||
|
setServiceName('');
|
||||||
|
setSni('www.microsoft.com');
|
||||||
|
setFingerprint('chrome');
|
||||||
|
setPublicKey('');
|
||||||
|
setShortId('');
|
||||||
|
setDomainStrategy('AsIs');
|
||||||
|
setWgSecretKey('');
|
||||||
|
setWgAddress('172.16.0.2/32');
|
||||||
|
setWgPublicKey('');
|
||||||
|
setWgEndpoint('');
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Outbound config generator"
|
||||||
|
description="Build an Xray outbound object — freedom, blackhole, a proxy protocol, WireGuard, or WARP — to paste into your Xray configuration."
|
||||||
|
onReset={reset}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Kind"
|
||||||
|
value={kind}
|
||||||
|
onChange={(v) => setKind(v as OutboundKind)}
|
||||||
|
options={KINDS}
|
||||||
|
/>
|
||||||
|
<TextField label="Tag" value={kind === 'warp' ? 'warp' : tag} onChange={setTag} />
|
||||||
|
|
||||||
|
{kind === 'freedom' ? (
|
||||||
|
<SelectField
|
||||||
|
label="Domain strategy"
|
||||||
|
value={domainStrategy}
|
||||||
|
onChange={setDomainStrategy}
|
||||||
|
options={DOMAIN_STRATEGIES}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isProxy ? (
|
||||||
|
<>
|
||||||
|
<TextField label="Address" value={address} onChange={setAddress} />
|
||||||
|
<TextField label="Port" value={port} onChange={setPort} inputMode="numeric" />
|
||||||
|
{(kind === 'vless' || kind === 'vmess') && (
|
||||||
|
<TextField label="UUID (id)" value={id} onChange={setId} />
|
||||||
|
)}
|
||||||
|
{kind === 'vless' && (
|
||||||
|
<TextField
|
||||||
|
label="Flow"
|
||||||
|
value={flow}
|
||||||
|
onChange={setFlow}
|
||||||
|
placeholder="xtls-rprx-vision (optional)"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{(kind === 'trojan' || kind === 'shadowsocks') && (
|
||||||
|
<TextField label="Password" value={password} onChange={setPassword} />
|
||||||
|
)}
|
||||||
|
{kind === 'shadowsocks' && (
|
||||||
|
<TextField label="Method (cipher)" value={method} onChange={setMethod} />
|
||||||
|
)}
|
||||||
|
{(kind === 'socks' || kind === 'http') && (
|
||||||
|
<>
|
||||||
|
<TextField
|
||||||
|
label="Username"
|
||||||
|
value={username}
|
||||||
|
onChange={setUsername}
|
||||||
|
placeholder="optional"
|
||||||
|
/>
|
||||||
|
<TextField label="Password" value={password} onChange={setPassword} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isWg ? (
|
||||||
|
<>
|
||||||
|
<TextField
|
||||||
|
label="Private key (secretKey)"
|
||||||
|
value={wgSecretKey}
|
||||||
|
onChange={setWgSecretKey}
|
||||||
|
/>
|
||||||
|
<TextField label="Local address" value={wgAddress} onChange={setWgAddress} />
|
||||||
|
<TextField label="Peer public key" value={wgPublicKey} onChange={setWgPublicKey} />
|
||||||
|
<TextField
|
||||||
|
label="Peer endpoint"
|
||||||
|
value={wgEndpoint}
|
||||||
|
onChange={setWgEndpoint}
|
||||||
|
placeholder={kind === 'warp' ? 'engage.cloudflareclient.com:2408' : 'host:51820'}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasStream ? (
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Transport"
|
||||||
|
value={network}
|
||||||
|
onChange={(v) => setNetwork(v as Network)}
|
||||||
|
options={NETWORKS}
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="Security"
|
||||||
|
value={security}
|
||||||
|
onChange={(v) => setSecurity(v as Security)}
|
||||||
|
options={SECURITIES}
|
||||||
|
/>
|
||||||
|
{hasPath ? (
|
||||||
|
<>
|
||||||
|
<TextField label="Path" value={path} onChange={setPath} />
|
||||||
|
<TextField label="Host" value={host} onChange={setHost} placeholder="optional" />
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{network === 'grpc' ? (
|
||||||
|
<TextField label="serviceName" value={serviceName} onChange={setServiceName} />
|
||||||
|
) : null}
|
||||||
|
{security !== 'none' ? (
|
||||||
|
<>
|
||||||
|
<TextField label="SNI (serverName)" value={sni} onChange={setSni} />
|
||||||
|
<SelectField
|
||||||
|
label="Fingerprint"
|
||||||
|
value={fingerprint}
|
||||||
|
onChange={setFingerprint}
|
||||||
|
options={FINGERPRINTS}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{security === 'reality' ? (
|
||||||
|
<>
|
||||||
|
<TextField label="Public key (pbk)" value={publicKey} onChange={setPublicKey} />
|
||||||
|
<TextField label="Short ID (sid)" value={shortId} onChange={setShortId} />
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<OutputBlock label="Outbound (Xray JSON)" value={buildOutboundJson(input)} />
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { Sparkles } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
recommend,
|
||||||
|
type UseCase,
|
||||||
|
type CensorshipLevel,
|
||||||
|
type ClientSupport,
|
||||||
|
} from '@/lib/xray/protocols';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { SelectField } from './shared/fields';
|
||||||
|
|
||||||
|
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
|
|
||||||
|
export function ProtocolWizard() {
|
||||||
|
const [useCase, setUseCase] = useState<UseCase>('general');
|
||||||
|
const [censorship, setCensorship] = useState<CensorshipLevel>('medium');
|
||||||
|
const [clientSupport, setClientSupport] = useState<ClientSupport>('modern');
|
||||||
|
|
||||||
|
const result = recommend({ useCase, censorship, clientSupport });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Protocol wizard"
|
||||||
|
description="Answer a few questions to get a recommended protocol and transport."
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||||
|
<SelectField
|
||||||
|
label="Primary goal"
|
||||||
|
value={cap(useCase)}
|
||||||
|
onChange={(v) => setUseCase(v.toLowerCase() as UseCase)}
|
||||||
|
options={['Censorship', 'General', 'Speed']}
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="Censorship level"
|
||||||
|
value={cap(censorship)}
|
||||||
|
onChange={(v) => setCensorship(v.toLowerCase() as CensorshipLevel)}
|
||||||
|
options={['High', 'Medium', 'Low']}
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="Client support"
|
||||||
|
value={cap(clientSupport)}
|
||||||
|
onChange={(v) => setClientSupport(v.toLowerCase() as ClientSupport)}
|
||||||
|
options={['Modern', 'Broad']}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 rounded-xl border bg-fd-background p-4">
|
||||||
|
<div className="flex items-center gap-2 text-brand">
|
||||||
|
<Sparkles className="size-4" aria-hidden />
|
||||||
|
<span className="text-sm font-medium">Recommended</span>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-wrap gap-2">
|
||||||
|
<Badge>{result.protocol}</Badge>
|
||||||
|
<Badge>{result.transport}</Badge>
|
||||||
|
<Badge>{result.security}</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="mt-3 text-sm text-fd-muted-foreground">{result.rationale}</p>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-3 text-sm">
|
||||||
|
{result.links.map((link) => (
|
||||||
|
<Link key={link.href} href={link.href} className="text-fd-primary hover:underline">
|
||||||
|
{link.title} →
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Badge({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<span className="rounded-lg bg-brand/10 px-2.5 py-1 text-sm font-medium text-brand">
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { RefreshCw } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
generateX25519KeyPair,
|
||||||
|
isX25519Available,
|
||||||
|
randomShortId,
|
||||||
|
randomUuid,
|
||||||
|
realityClientLink,
|
||||||
|
realityServerInbound,
|
||||||
|
type RealityConfig,
|
||||||
|
type X25519KeyPair,
|
||||||
|
} from '@/lib/xray/reality';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
import { CopyButton } from './shared/copy-button';
|
||||||
|
|
||||||
|
const FINGERPRINTS = ['chrome', 'firefox', 'safari', 'ios', 'android', 'edge', 'random'] as const;
|
||||||
|
|
||||||
|
export function RealityConfigGenerator() {
|
||||||
|
const [address, setAddress] = useState('your-server.com');
|
||||||
|
const [port, setPort] = useState('443');
|
||||||
|
const [dest, setDest] = useState('www.microsoft.com:443');
|
||||||
|
const [sni, setSni] = useState('www.microsoft.com');
|
||||||
|
const [fingerprint, setFingerprint] = useState<string>('chrome');
|
||||||
|
const [uuid, setUuid] = useState('');
|
||||||
|
const [shortId, setShortId] = useState('');
|
||||||
|
const [keys, setKeys] = useState<X25519KeyPair | null>(null);
|
||||||
|
const [unavailable, setUnavailable] = useState(false);
|
||||||
|
|
||||||
|
const regenerate = useCallback(async () => {
|
||||||
|
setUuid(randomUuid());
|
||||||
|
setShortId(randomShortId(4));
|
||||||
|
if (!isX25519Available()) {
|
||||||
|
setUnavailable(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
setKeys(await generateX25519KeyPair());
|
||||||
|
setUnavailable(false);
|
||||||
|
} catch {
|
||||||
|
setUnavailable(true);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Generate keys/identifiers on the client after hydration. This is a genuine
|
||||||
|
// client-only side effect (WebCrypto + randomness), not derived render state.
|
||||||
|
useEffect(() => {
|
||||||
|
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||||
|
void regenerate();
|
||||||
|
}, [regenerate]);
|
||||||
|
|
||||||
|
const config: RealityConfig | null =
|
||||||
|
keys && uuid
|
||||||
|
? {
|
||||||
|
address,
|
||||||
|
port: Number(port) || 443,
|
||||||
|
uuid,
|
||||||
|
dest,
|
||||||
|
serverNames: [sni],
|
||||||
|
shortIds: [shortId],
|
||||||
|
privateKey: keys.privateKey,
|
||||||
|
publicKey: keys.publicKey,
|
||||||
|
fingerprint,
|
||||||
|
spiderX: '/',
|
||||||
|
flow: 'xtls-rprx-vision',
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const serverJson = config ? JSON.stringify(realityServerInbound(config), null, 2) : '';
|
||||||
|
const clientLink = config ? realityClientLink(config) : '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="REALITY config generator"
|
||||||
|
description="Generate a VLESS + REALITY inbound and client link. Keys are created in your browser — nothing is sent anywhere."
|
||||||
|
onReset={() => void regenerate()}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<TextField
|
||||||
|
label="Server address"
|
||||||
|
value={address}
|
||||||
|
onChange={setAddress}
|
||||||
|
hint="Your domain or IP"
|
||||||
|
/>
|
||||||
|
<TextField label="Port" value={port} onChange={setPort} inputMode="numeric" />
|
||||||
|
<TextField
|
||||||
|
label="Dest (camouflage target)"
|
||||||
|
value={dest}
|
||||||
|
onChange={setDest}
|
||||||
|
hint="A real TLS 1.3 site, e.g. www.microsoft.com:443"
|
||||||
|
/>
|
||||||
|
<TextField label="SNI / Server name" value={sni} onChange={setSni} />
|
||||||
|
<SelectField
|
||||||
|
label="Fingerprint"
|
||||||
|
value={fingerprint}
|
||||||
|
onChange={setFingerprint}
|
||||||
|
options={FINGERPRINTS}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{unavailable ? (
|
||||||
|
<div className="mt-4 rounded-xl border border-amber-500/40 bg-amber-500/10 p-3 text-sm">
|
||||||
|
Your browser can't generate X25519 keys here. Generate them on the server instead:
|
||||||
|
<div className="mt-2">
|
||||||
|
<OutputBlock label="run on the server" value="xray x25519" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-sm font-medium">Generated keys & identifiers</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void regenerate()}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
|
||||||
|
>
|
||||||
|
<RefreshCw className="size-3.5" aria-hidden />
|
||||||
|
Regenerate
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||||
|
<KeyRow label="Public key" value={keys?.publicKey ?? ''} />
|
||||||
|
<KeyRow label="Private key" value={keys?.privateKey ?? ''} />
|
||||||
|
<KeyRow label="UUID" value={uuid} />
|
||||||
|
<KeyRow label="Short ID" value={shortId} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="Server inbound (Xray JSON)" value={serverJson} />
|
||||||
|
<OutputBlock label="Client share link" value={clientLink} qr />
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function KeyRow({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2 rounded-lg border bg-fd-background px-3 py-2">
|
||||||
|
<span className="shrink-0 text-xs font-medium text-fd-muted-foreground">{label}</span>
|
||||||
|
<code dir="ltr" className="flex-1 truncate text-start text-xs">
|
||||||
|
{value}
|
||||||
|
</code>
|
||||||
|
<CopyButton value={value} label="" className="px-1.5" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildProxyConfig,
|
||||||
|
buildCertCommand,
|
||||||
|
type ProxyServer,
|
||||||
|
type CertTool,
|
||||||
|
type ReverseProxyOptions,
|
||||||
|
} from '@/lib/xray/reverse-proxy';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
export function ReverseProxyGenerator() {
|
||||||
|
const [server, setServer] = useState<ProxyServer>('nginx');
|
||||||
|
const [domain, setDomain] = useState('panel.example.com');
|
||||||
|
const [panelPort, setPanelPort] = useState('2053');
|
||||||
|
const [panelPath, setPanelPath] = useState('/panel');
|
||||||
|
const [certTool, setCertTool] = useState<CertTool>('certbot');
|
||||||
|
|
||||||
|
const options: ReverseProxyOptions = { server, domain, panelPort, panelPath, certTool };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Reverse-proxy config generator"
|
||||||
|
description="Generate an Nginx or Caddy reverse-proxy config (with WebSocket support) and a matching certificate command."
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Server"
|
||||||
|
value={server}
|
||||||
|
onChange={(v) => setServer(v as ProxyServer)}
|
||||||
|
options={['nginx', 'caddy']}
|
||||||
|
/>
|
||||||
|
<TextField label="Domain" value={domain} onChange={setDomain} />
|
||||||
|
<TextField
|
||||||
|
label="Panel port"
|
||||||
|
value={panelPort}
|
||||||
|
onChange={setPanelPort}
|
||||||
|
inputMode="numeric"
|
||||||
|
/>
|
||||||
|
<TextField label="Panel web base path" value={panelPath} onChange={setPanelPath} />
|
||||||
|
{server === 'nginx' ? (
|
||||||
|
<SelectField
|
||||||
|
label="Certificate tool"
|
||||||
|
value={certTool}
|
||||||
|
onChange={(v) => setCertTool(v as CertTool)}
|
||||||
|
options={['certbot', 'acme.sh']}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock
|
||||||
|
label={server === 'nginx' ? 'nginx server block' : 'Caddyfile'}
|
||||||
|
value={buildProxyConfig(options)}
|
||||||
|
/>
|
||||||
|
{server === 'nginx' ? (
|
||||||
|
<OutputBlock label="Obtain a certificate" value={buildCertCommand(options)} />
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-fd-muted-foreground">
|
||||||
|
Caddy obtains and renews TLS certificates automatically — no extra command needed.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildRoutingJson,
|
||||||
|
type DomainStrategy,
|
||||||
|
type RoutingInput,
|
||||||
|
type RuleNetwork,
|
||||||
|
type Strategy,
|
||||||
|
} from '@/lib/xray/routing';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
interface BalancerRow {
|
||||||
|
tag: string;
|
||||||
|
selector: string;
|
||||||
|
strategy: Strategy;
|
||||||
|
fallbackTag: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RuleRow {
|
||||||
|
domain: string;
|
||||||
|
ip: string;
|
||||||
|
port: string;
|
||||||
|
network: string;
|
||||||
|
inboundTag: string;
|
||||||
|
targetKind: 'outbound' | 'balancer';
|
||||||
|
targetTag: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const STRATEGIES: readonly Strategy[] = ['random', 'roundRobin', 'leastPing', 'leastLoad'];
|
||||||
|
const NETWORKS = ['any', 'tcp', 'udp', 'tcp,udp'];
|
||||||
|
const TARGET_KINDS = ['outbound', 'balancer'];
|
||||||
|
const DOMAIN_STRATEGIES: readonly DomainStrategy[] = ['AsIs', 'IPIfNonMatch', 'IPOnDemand'];
|
||||||
|
|
||||||
|
const DEFAULT_BALANCERS: BalancerRow[] = [
|
||||||
|
{ tag: 'balancer', selector: 'proxy', strategy: 'leastPing', fallbackTag: '' },
|
||||||
|
];
|
||||||
|
const DEFAULT_RULES: RuleRow[] = [
|
||||||
|
{ domain: 'geosite:category-ads-all', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'block' },
|
||||||
|
{ domain: '', ip: 'geoip:private', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'direct' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function list(s: string): string[] {
|
||||||
|
return s
|
||||||
|
.split(',')
|
||||||
|
.map((x) => x.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
const addBtn =
|
||||||
|
'inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground';
|
||||||
|
|
||||||
|
export function RoutingBuilder() {
|
||||||
|
const [domainStrategy, setDomainStrategy] = useState<DomainStrategy>('IPIfNonMatch');
|
||||||
|
const [balancers, setBalancers] = useState<BalancerRow[]>(DEFAULT_BALANCERS);
|
||||||
|
const [rules, setRules] = useState<RuleRow[]>(DEFAULT_RULES);
|
||||||
|
|
||||||
|
function patchBalancer(i: number, patch: Partial<BalancerRow>) {
|
||||||
|
setBalancers((prev) => prev.map((b, j) => (i === j ? { ...b, ...patch } : b)));
|
||||||
|
}
|
||||||
|
function patchRule(i: number, patch: Partial<RuleRow>) {
|
||||||
|
setRules((prev) => prev.map((r, j) => (i === j ? { ...r, ...patch } : r)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const input: RoutingInput = {
|
||||||
|
domainStrategy,
|
||||||
|
balancers: balancers
|
||||||
|
.filter((b) => b.tag.trim())
|
||||||
|
.map((b) => ({
|
||||||
|
tag: b.tag.trim(),
|
||||||
|
selector: list(b.selector),
|
||||||
|
strategy: b.strategy,
|
||||||
|
fallbackTag: b.fallbackTag.trim() || undefined,
|
||||||
|
})),
|
||||||
|
rules: rules
|
||||||
|
.filter((r) => r.targetTag.trim())
|
||||||
|
.map((r) => ({
|
||||||
|
domain: list(r.domain),
|
||||||
|
ip: list(r.ip),
|
||||||
|
port: r.port.trim() || undefined,
|
||||||
|
network: r.network === 'any' ? undefined : (r.network as RuleNetwork),
|
||||||
|
inboundTag: list(r.inboundTag),
|
||||||
|
target: { kind: r.targetKind, tag: r.targetTag.trim() },
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setDomainStrategy('IPIfNonMatch');
|
||||||
|
setBalancers(DEFAULT_BALANCERS);
|
||||||
|
setRules(DEFAULT_RULES);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Balancer & routing builder"
|
||||||
|
description="Compose Xray balancers and routing rules, then copy the routing block (with a matching observatory for leastPing/leastLoad)."
|
||||||
|
onReset={reset}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Domain strategy"
|
||||||
|
value={domainStrategy}
|
||||||
|
onChange={(v) => setDomainStrategy(v as DomainStrategy)}
|
||||||
|
options={DOMAIN_STRATEGIES}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5 flex items-center justify-between">
|
||||||
|
<h4 className="text-sm font-semibold">Balancers</h4>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() =>
|
||||||
|
setBalancers((p) => [...p, { tag: '', selector: '', strategy: 'random', fallbackTag: '' }])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Add balancer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-col gap-3">
|
||||||
|
{balancers.map((b, i) => (
|
||||||
|
<div key={i} className="rounded-xl border p-3">
|
||||||
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
|
<TextField label="Tag" value={b.tag} onChange={(v) => patchBalancer(i, { tag: v })} />
|
||||||
|
<TextField
|
||||||
|
label="Selector (comma-separated prefixes)"
|
||||||
|
value={b.selector}
|
||||||
|
onChange={(v) => patchBalancer(i, { selector: v })}
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="Strategy"
|
||||||
|
value={b.strategy}
|
||||||
|
onChange={(v) => patchBalancer(i, { strategy: v as Strategy })}
|
||||||
|
options={STRATEGIES}
|
||||||
|
/>
|
||||||
|
<TextField
|
||||||
|
label="Fallback tag"
|
||||||
|
value={b.fallbackTag}
|
||||||
|
onChange={(v) => patchBalancer(i, { fallbackTag: v })}
|
||||||
|
placeholder="optional"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex justify-end">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() => setBalancers((p) => p.filter((_, j) => j !== i))}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5 flex items-center justify-between">
|
||||||
|
<h4 className="text-sm font-semibold">Rules</h4>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() =>
|
||||||
|
setRules((p) => [
|
||||||
|
...p,
|
||||||
|
{ domain: '', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: '' },
|
||||||
|
])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Add rule
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-col gap-3">
|
||||||
|
{rules.map((r, i) => (
|
||||||
|
<div key={i} className="rounded-xl border p-3">
|
||||||
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
|
<TextField label="Domain (comma)" value={r.domain} onChange={(v) => patchRule(i, { domain: v })} placeholder="geosite:google, example.com" />
|
||||||
|
<TextField label="IP (comma)" value={r.ip} onChange={(v) => patchRule(i, { ip: v })} placeholder="geoip:cn, 1.1.1.1" />
|
||||||
|
<TextField label="Port" value={r.port} onChange={(v) => patchRule(i, { port: v })} placeholder="443 or 1000-2000" />
|
||||||
|
<SelectField label="Network" value={r.network} onChange={(v) => patchRule(i, { network: v })} options={NETWORKS} />
|
||||||
|
<TextField label="Inbound tag (comma)" value={r.inboundTag} onChange={(v) => patchRule(i, { inboundTag: v })} placeholder="optional" />
|
||||||
|
<SelectField label="Target kind" value={r.targetKind} onChange={(v) => patchRule(i, { targetKind: v as 'outbound' | 'balancer' })} options={TARGET_KINDS} />
|
||||||
|
<TextField label="Target tag" value={r.targetTag} onChange={(v) => patchRule(i, { targetTag: v })} />
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex justify-end">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() => setRules((p) => p.filter((_, j) => j !== i))}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<OutputBlock label="Routing block (Xray JSON)" value={buildRoutingJson(input)} />
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { AlertCircle } from 'lucide-react';
|
||||||
|
import { parseLink, type ParsedLink } from '@/lib/xray/links';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
|
||||||
|
type Result = { ok: true; data: ParsedLink } | { ok: false; error: string } | null;
|
||||||
|
|
||||||
|
export function ShareLinkInspector() {
|
||||||
|
const [input, setInput] = useState('');
|
||||||
|
|
||||||
|
const result: Result = useMemo(() => {
|
||||||
|
const value = input.trim();
|
||||||
|
if (!value) return null;
|
||||||
|
try {
|
||||||
|
return { ok: true, data: parseLink(value) };
|
||||||
|
} catch (e) {
|
||||||
|
return { ok: false, error: (e as Error).message };
|
||||||
|
}
|
||||||
|
}, [input]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Share-link inspector"
|
||||||
|
description="Paste a vless / vmess / trojan / ss link to decode every parameter. It is parsed entirely in your browser — nothing is sent over the network."
|
||||||
|
onReset={input ? () => setInput('') : undefined}
|
||||||
|
>
|
||||||
|
<textarea
|
||||||
|
value={input}
|
||||||
|
onChange={(e) => setInput(e.target.value)}
|
||||||
|
placeholder="vless://uuid@host:443?security=reality&pbk=...#name"
|
||||||
|
dir="ltr"
|
||||||
|
rows={3}
|
||||||
|
spellCheck={false}
|
||||||
|
className="w-full resize-y rounded-lg border bg-fd-background px-3 py-2 font-mono text-sm outline-none transition-colors focus-visible:border-fd-primary focus-visible:ring-2 focus-visible:ring-fd-ring/30"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{result && !result.ok ? (
|
||||||
|
<div className="mt-3 flex items-center gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
|
||||||
|
<AlertCircle className="size-4 shrink-0" aria-hidden />
|
||||||
|
<span>{result.error}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{result && result.ok ? <ResultTable data={result.data} /> : null}
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ResultTable({ data }: { data: ParsedLink }) {
|
||||||
|
const rows: [string, string][] = [
|
||||||
|
['Protocol', data.protocol],
|
||||||
|
['Name', data.name],
|
||||||
|
['Address', data.address],
|
||||||
|
['Port', String(data.port)],
|
||||||
|
[data.protocol === 'trojan' ? 'Password' : 'ID / credential', data.credential],
|
||||||
|
...Object.entries(data.params),
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-3 overflow-hidden rounded-xl border">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<tbody>
|
||||||
|
{rows.map(([key, value], i) => (
|
||||||
|
<tr key={`${key}-${i}`} className="border-b last:border-b-0">
|
||||||
|
<th
|
||||||
|
scope="row"
|
||||||
|
className="w-1/3 bg-fd-muted/40 px-3 py-2 text-start align-top font-medium text-fd-muted-foreground"
|
||||||
|
>
|
||||||
|
{key}
|
||||||
|
</th>
|
||||||
|
<td dir="ltr" className="break-all px-3 py-2 text-start font-mono">
|
||||||
|
{value || <span className="text-fd-muted-foreground">—</span>}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { Check, Copy } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/cn';
|
||||||
|
|
||||||
|
export function CopyButton({
|
||||||
|
value,
|
||||||
|
label = 'Copy',
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
value: string;
|
||||||
|
label?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
async function copy() {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
} catch {
|
||||||
|
// Clipboard unavailable (insecure context) — ignore.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={copy}
|
||||||
|
aria-label={copied ? 'Copied' : label}
|
||||||
|
className={cn(
|
||||||
|
'inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground focus-visible:outline-2 focus-visible:outline-fd-ring',
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<Check className="size-3.5 text-brand" aria-hidden />
|
||||||
|
) : (
|
||||||
|
<Copy className="size-3.5" aria-hidden />
|
||||||
|
)}
|
||||||
|
<span>{copied ? 'Copied' : label}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useId } from 'react';
|
||||||
|
|
||||||
|
const inputClass =
|
||||||
|
'rounded-lg border bg-fd-background px-3 py-2 text-sm outline-none transition-colors focus-visible:border-fd-primary focus-visible:ring-2 focus-visible:ring-fd-ring/30';
|
||||||
|
|
||||||
|
export function TextField({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder,
|
||||||
|
hint,
|
||||||
|
inputMode,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
hint?: string;
|
||||||
|
inputMode?: 'numeric' | 'text';
|
||||||
|
}) {
|
||||||
|
const id = useId();
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label htmlFor={id} className="text-sm font-medium">
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
{/* Values are technical (hosts, links) and stay LTR even on RTL pages. */}
|
||||||
|
<input
|
||||||
|
id={id}
|
||||||
|
dir="ltr"
|
||||||
|
inputMode={inputMode}
|
||||||
|
value={value}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
{hint ? <span className="text-xs text-fd-muted-foreground">{hint}</span> : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckboxField({
|
||||||
|
label,
|
||||||
|
checked,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
checked: boolean;
|
||||||
|
onChange: (checked: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const id = useId();
|
||||||
|
return (
|
||||||
|
<label htmlFor={id} className="inline-flex cursor-pointer items-center gap-2 text-sm">
|
||||||
|
<input
|
||||||
|
id={id}
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
onChange={(e) => onChange(e.target.checked)}
|
||||||
|
className="size-4 accent-fd-primary"
|
||||||
|
/>
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SelectField({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
options,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
options: readonly string[];
|
||||||
|
}) {
|
||||||
|
const id = useId();
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label htmlFor={id} className="text-sm font-medium">
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id={id}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
className={inputClass}
|
||||||
|
>
|
||||||
|
{options.map((opt) => (
|
||||||
|
<option key={opt} value={opt}>
|
||||||
|
{opt}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import QRCode from 'react-qr-code';
|
||||||
|
import { CopyButton } from './copy-button';
|
||||||
|
|
||||||
|
export function OutputBlock({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
qr = false,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
qr?: boolean;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="overflow-hidden rounded-xl border">
|
||||||
|
<div className="flex items-center justify-between gap-2 border-b bg-fd-muted/40 px-3 py-2">
|
||||||
|
<span className="text-xs font-medium text-fd-muted-foreground">{label}</span>
|
||||||
|
<CopyButton value={value} />
|
||||||
|
</div>
|
||||||
|
<pre dir="ltr" className="max-h-80 overflow-auto p-3 text-start text-xs leading-relaxed">
|
||||||
|
<code>{value}</code>
|
||||||
|
</pre>
|
||||||
|
{qr && value ? (
|
||||||
|
<div className="flex justify-center border-t bg-white p-4">
|
||||||
|
<QRCode value={value} size={180} />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
buildSubscriptionUrls,
|
||||||
|
buildShareLinks,
|
||||||
|
buildBase64Subscription,
|
||||||
|
buildJsonSubscription,
|
||||||
|
type SubClient,
|
||||||
|
type SubUrlInput,
|
||||||
|
} from '@/lib/xray/subscription';
|
||||||
|
import type { Network, Security } from '@/lib/xray/outbounds';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField, SelectField, CheckboxField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
type ClientProtocol = 'vless' | 'vmess' | 'trojan' | 'ss';
|
||||||
|
|
||||||
|
interface ClientRow {
|
||||||
|
protocol: ClientProtocol;
|
||||||
|
remark: string;
|
||||||
|
address: string;
|
||||||
|
port: string;
|
||||||
|
credential: string; // id (vless/vmess) or password (trojan/ss)
|
||||||
|
method: string; // ss
|
||||||
|
network: Network;
|
||||||
|
security: Security;
|
||||||
|
sni: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PROTOCOLS: readonly ClientProtocol[] = ['vless', 'vmess', 'trojan', 'ss'];
|
||||||
|
const NETWORKS: readonly Network[] = ['tcp', 'kcp', 'ws', 'grpc', 'httpupgrade', 'xhttp'];
|
||||||
|
const SECURITIES: readonly Security[] = ['none', 'tls', 'reality'];
|
||||||
|
|
||||||
|
const addBtn =
|
||||||
|
'inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground';
|
||||||
|
|
||||||
|
const DEFAULT_CLIENTS: ClientRow[] = [
|
||||||
|
{
|
||||||
|
protocol: 'vless',
|
||||||
|
remark: 'HK-01',
|
||||||
|
address: 'a.example.com',
|
||||||
|
port: '443',
|
||||||
|
credential: '11111111-2222-3333-4444-555555555555',
|
||||||
|
method: '',
|
||||||
|
network: 'tcp',
|
||||||
|
security: 'reality',
|
||||||
|
sni: 'www.microsoft.com',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function toClient(r: ClientRow): SubClient {
|
||||||
|
const isUuid = r.protocol === 'vless' || r.protocol === 'vmess';
|
||||||
|
return {
|
||||||
|
protocol: r.protocol,
|
||||||
|
remark: r.remark,
|
||||||
|
address: r.address,
|
||||||
|
port: Number(r.port),
|
||||||
|
id: isUuid ? r.credential : undefined,
|
||||||
|
password: isUuid ? undefined : r.credential,
|
||||||
|
method: r.protocol === 'ss' ? r.method : undefined,
|
||||||
|
network: r.network,
|
||||||
|
security: r.security,
|
||||||
|
sni: r.sni || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SubscriptionBuilder() {
|
||||||
|
const [scheme, setScheme] = useState<'http' | 'https'>('https');
|
||||||
|
const [host, setHost] = useState('sub.example.com');
|
||||||
|
const [port, setPort] = useState('2096');
|
||||||
|
const [subPath, setSubPath] = useState('/sub/');
|
||||||
|
const [jsonPath, setJsonPath] = useState('/json/');
|
||||||
|
const [subId, setSubId] = useState('user-1');
|
||||||
|
const [behindProxy, setBehindProxy] = useState(false);
|
||||||
|
const [clients, setClients] = useState<ClientRow[]>(DEFAULT_CLIENTS);
|
||||||
|
|
||||||
|
function patch(i: number, p: Partial<ClientRow>) {
|
||||||
|
setClients((prev) => prev.map((c, j) => (i === j ? { ...c, ...p } : c)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const urlInput: SubUrlInput = { scheme, host, port: Number(port), subPath, jsonPath, subId, behindProxy };
|
||||||
|
const urls = buildSubscriptionUrls(urlInput);
|
||||||
|
const subClients = clients.filter((c) => c.address.trim()).map(toClient);
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setScheme('https');
|
||||||
|
setHost('sub.example.com');
|
||||||
|
setPort('2096');
|
||||||
|
setSubPath('/sub/');
|
||||||
|
setJsonPath('/json/');
|
||||||
|
setSubId('user-1');
|
||||||
|
setBehindProxy(false);
|
||||||
|
setClients(DEFAULT_CLIENTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Subscription & sub-JSON builder"
|
||||||
|
description="Build the subscription URLs and preview both body formats — the Base64 link list and the JSON (Xray-json) config."
|
||||||
|
onReset={reset}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Scheme"
|
||||||
|
value={scheme}
|
||||||
|
onChange={(v) => setScheme(v as 'http' | 'https')}
|
||||||
|
options={['https', 'http']}
|
||||||
|
/>
|
||||||
|
<TextField label="Host" value={host} onChange={setHost} />
|
||||||
|
<TextField label="Port" value={port} onChange={setPort} inputMode="numeric" />
|
||||||
|
<TextField label="Sub ID" value={subId} onChange={setSubId} />
|
||||||
|
<TextField label="Sub path" value={subPath} onChange={setSubPath} />
|
||||||
|
<TextField label="JSON path" value={jsonPath} onChange={setJsonPath} />
|
||||||
|
<CheckboxField
|
||||||
|
label="Behind a reverse proxy (omit the port)"
|
||||||
|
checked={behindProxy}
|
||||||
|
onChange={setBehindProxy}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="Base64 subscription URL" value={urls.base64} qr />
|
||||||
|
<OutputBlock label="JSON subscription URL" value={urls.json} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-5 flex items-center justify-between">
|
||||||
|
<h4 className="text-sm font-semibold">Clients in this subscription</h4>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() =>
|
||||||
|
setClients((p) => [
|
||||||
|
...p,
|
||||||
|
{
|
||||||
|
protocol: 'vless',
|
||||||
|
remark: '',
|
||||||
|
address: '',
|
||||||
|
port: '443',
|
||||||
|
credential: '',
|
||||||
|
method: '',
|
||||||
|
network: 'tcp',
|
||||||
|
security: 'reality',
|
||||||
|
sni: '',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Add client
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex flex-col gap-3">
|
||||||
|
{clients.map((c, i) => (
|
||||||
|
<div key={i} className="rounded-xl border p-3">
|
||||||
|
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||||
|
<SelectField
|
||||||
|
label="Protocol"
|
||||||
|
value={c.protocol}
|
||||||
|
onChange={(v) => patch(i, { protocol: v as ClientProtocol })}
|
||||||
|
options={PROTOCOLS}
|
||||||
|
/>
|
||||||
|
<TextField label="Remark" value={c.remark} onChange={(v) => patch(i, { remark: v })} />
|
||||||
|
<TextField label="Address" value={c.address} onChange={(v) => patch(i, { address: v })} />
|
||||||
|
<TextField label="Port" value={c.port} onChange={(v) => patch(i, { port: v })} inputMode="numeric" />
|
||||||
|
<TextField
|
||||||
|
label={c.protocol === 'vless' || c.protocol === 'vmess' ? 'UUID (id)' : 'Password'}
|
||||||
|
value={c.credential}
|
||||||
|
onChange={(v) => patch(i, { credential: v })}
|
||||||
|
/>
|
||||||
|
{c.protocol === 'ss' ? (
|
||||||
|
<TextField label="Method" value={c.method} onChange={(v) => patch(i, { method: v })} />
|
||||||
|
) : null}
|
||||||
|
<SelectField
|
||||||
|
label="Transport"
|
||||||
|
value={c.network}
|
||||||
|
onChange={(v) => patch(i, { network: v as Network })}
|
||||||
|
options={NETWORKS}
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="Security"
|
||||||
|
value={c.security}
|
||||||
|
onChange={(v) => patch(i, { security: v as Security })}
|
||||||
|
options={SECURITIES}
|
||||||
|
/>
|
||||||
|
{c.security !== 'none' ? (
|
||||||
|
<TextField label="SNI" value={c.sni} onChange={(v) => patch(i, { sni: v })} />
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 flex justify-end">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={addBtn}
|
||||||
|
onClick={() => setClients((p) => p.filter((_, j) => j !== i))}
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="Subscription links (decoded body)" value={buildShareLinks(subClients).join('\n')} />
|
||||||
|
<OutputBlock label="Base64 body" value={buildBase64Subscription(subClients)} />
|
||||||
|
<OutputBlock label="JSON subscription (preview)" value={buildJsonSubscription(subClients)} />
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import {
|
||||||
|
validateBotToken,
|
||||||
|
parseAdminIds,
|
||||||
|
validateRunTime,
|
||||||
|
telegramApiBase,
|
||||||
|
buildBotConfigSummary,
|
||||||
|
} from '@/lib/xray/telegram';
|
||||||
|
import { ToolFrame } from './tool-frame';
|
||||||
|
import { TextField } from './shared/fields';
|
||||||
|
import { OutputBlock } from './shared/output-block';
|
||||||
|
|
||||||
|
function Status({ ok, children }: { ok: boolean; children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
className={`text-xs ${ok ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-600 dark:text-red-400'}`}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TelegramSetupHelper() {
|
||||||
|
const [token, setToken] = useState('');
|
||||||
|
const [adminIds, setAdminIds] = useState('');
|
||||||
|
const [runTime, setRunTime] = useState('@daily');
|
||||||
|
|
||||||
|
const tokenV = validateBotToken(token);
|
||||||
|
const idsV = parseAdminIds(adminIds);
|
||||||
|
const cronV = validateRunTime(runTime);
|
||||||
|
const summary = buildBotConfigSummary({ token, adminIds, runTime });
|
||||||
|
|
||||||
|
const settingsText = [
|
||||||
|
`tgBotEnable = true`,
|
||||||
|
`tgBotToken = ${summary.tgBotToken || '<token>'}`,
|
||||||
|
`tgBotChatId = ${summary.tgBotChatId || '<admin ids>'}`,
|
||||||
|
`tgRunTime = ${summary.tgRunTime || '@daily'}`,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
function reset() {
|
||||||
|
setToken('');
|
||||||
|
setAdminIds('');
|
||||||
|
setRunTime('@daily');
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolFrame
|
||||||
|
title="Telegram bot setup helper"
|
||||||
|
description="Validate your bot token, admin IDs, and report schedule, then copy the panel settings."
|
||||||
|
onReset={reset}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-1 gap-4">
|
||||||
|
<div>
|
||||||
|
<TextField
|
||||||
|
label="Bot token (from @BotFather)"
|
||||||
|
value={token}
|
||||||
|
onChange={setToken}
|
||||||
|
placeholder="123456789:AA..."
|
||||||
|
/>
|
||||||
|
{token ? (
|
||||||
|
tokenV.valid ? (
|
||||||
|
<Status ok>Valid — bot id {tokenV.botId}</Status>
|
||||||
|
) : (
|
||||||
|
<Status ok={false}>{tokenV.error}</Status>
|
||||||
|
)
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<TextField
|
||||||
|
label="Admin chat IDs (comma-separated)"
|
||||||
|
value={adminIds}
|
||||||
|
onChange={setAdminIds}
|
||||||
|
placeholder="111111111, 222222222"
|
||||||
|
/>
|
||||||
|
{adminIds ? (
|
||||||
|
idsV.invalid.length > 0 ? (
|
||||||
|
<Status ok={false}>Not numeric: {idsV.invalid.join(', ')}</Status>
|
||||||
|
) : (
|
||||||
|
<Status ok>
|
||||||
|
{idsV.ids.length} admin id{idsV.ids.length === 1 ? '' : 's'}
|
||||||
|
</Status>
|
||||||
|
)
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<TextField
|
||||||
|
label="Report schedule (tgRunTime)"
|
||||||
|
value={runTime}
|
||||||
|
onChange={setRunTime}
|
||||||
|
placeholder="@daily, @every 8h, or a cron expression"
|
||||||
|
/>
|
||||||
|
{runTime ? (
|
||||||
|
cronV.valid ? (
|
||||||
|
<Status ok>Valid ({cronV.kind})</Status>
|
||||||
|
) : (
|
||||||
|
<Status ok={false}>{cronV.error}</Status>
|
||||||
|
)
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid grid-cols-1 gap-4">
|
||||||
|
<OutputBlock label="Panel settings" value={settingsText} />
|
||||||
|
<OutputBlock
|
||||||
|
label="Bot API base (keep secret)"
|
||||||
|
value={tokenV.valid ? telegramApiBase(token) : 'https://api.telegram.org/bot<token>'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</ToolFrame>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { RotateCcw } from 'lucide-react';
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
|
||||||
|
export function ToolFrame({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
onReset,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
onReset?: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
role="group"
|
||||||
|
aria-label={title}
|
||||||
|
className="not-prose my-6 overflow-hidden rounded-2xl border bg-fd-card text-fd-foreground"
|
||||||
|
>
|
||||||
|
<header className="flex items-start justify-between gap-3 border-b px-4 py-3">
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold">{title}</h3>
|
||||||
|
{description ? (
|
||||||
|
<p className="mt-0.5 text-sm text-fd-muted-foreground">{description}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{onReset ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onReset}
|
||||||
|
className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-3.5" aria-hidden />
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</header>
|
||||||
|
<div className="p-4">{children}</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
title: Clients
|
||||||
|
description: Manage 3x-ui clients — credentials, traffic and expiry limits, IP limits, groups, bulk actions, external links, and online status.
|
||||||
|
icon: Users
|
||||||
|
---
|
||||||
|
|
||||||
|
A **client** is a single user, identified by a unique **email**. In the current
|
||||||
|
panel, clients are first-class records that can be attached to **multiple
|
||||||
|
inbounds** at once, with per-client traffic accounting.
|
||||||
|
|
||||||
|
## Client fields
|
||||||
|
|
||||||
|
| Field | Applies to | Meaning |
|
||||||
|
| -------------- | --------------------- | ------------------------------------------------------------------ |
|
||||||
|
| **Email** | all | Unique identifier used for accounting and lookups. |
|
||||||
|
| **ID (UUID)** | VLESS, VMess | The client credential. |
|
||||||
|
| **Password** | Trojan, Shadowsocks | The client credential. |
|
||||||
|
| **Auth** | Hysteria2 | The client credential. |
|
||||||
|
| **Flow** | VLESS | XTLS flow, e.g. `xtls-rprx-vision`. |
|
||||||
|
| **Limit IP** | all | Max simultaneous source IPs (enforced via Fail2ban). |
|
||||||
|
| **Total (GB)** | all | Traffic quota; the client is disabled when exhausted. |
|
||||||
|
| **Expiry** | all | Date after which the client stops working. |
|
||||||
|
| **Reset** | all | Auto-renew period in **days** (rolls the quota over). |
|
||||||
|
| **Telegram ID**| all | Links the client to a Telegram user for self-service/notifications.|
|
||||||
|
| **Sub ID** | all | Subscription identifier grouping this client's links. |
|
||||||
|
| **Group** | all | Optional client group for organization and bulk filtering. |
|
||||||
|
| **Comment** | all | Free-text note. |
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Reaching the **traffic** or **expiry** limit disables the client; the panel can
|
||||||
|
restart Xray automatically when clients are auto-disabled
|
||||||
|
(`restartXrayOnClientDisable`, on by default).
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Limits and IP control
|
||||||
|
|
||||||
|
- **Traffic / expiry** caps disable the client when hit; a **Reset** period
|
||||||
|
auto-renews the quota.
|
||||||
|
- **Limit IP** caps simultaneous source IPs. Enforcement relies on Fail2ban —
|
||||||
|
see [Security](/docs/operations/security). You can view a client's recent IPs
|
||||||
|
and clear them from the client's actions.
|
||||||
|
- **Online status** and **last-online** times are tracked per client (and per
|
||||||
|
node in multi-node setups).
|
||||||
|
|
||||||
|
## Share links and external links
|
||||||
|
|
||||||
|
Every client has share links and a QR code for its inbounds, plus a combined
|
||||||
|
[subscription](/docs/config/subscription). You can also attach **external
|
||||||
|
links** to a client — extra `vless://`, `vmess://`, `trojan://`, `ss://`,
|
||||||
|
`hysteria2://`, or `wireguard://` links, or a remote subscription URL — so they
|
||||||
|
appear alongside the panel-generated ones in the client's subscription.
|
||||||
|
|
||||||
|
To inspect exactly what a link contains, paste it into the
|
||||||
|
[share-link inspector](/docs/config/share-links).
|
||||||
|
|
||||||
|
## Bulk actions
|
||||||
|
|
||||||
|
For managing many clients at once, the panel supports bulk **create, enable,
|
||||||
|
disable, delete, attach/detach** (to inbounds), **reset traffic**, and
|
||||||
|
**adjust** (add days / add bytes / set flow). Maintenance actions also let you
|
||||||
|
delete **depleted** clients (quota/expiry exhausted) and **orphaned** clients
|
||||||
|
(not attached to any inbound).
|
||||||
|
|
||||||
|
<Callout type="warn">
|
||||||
|
A client's share link contains its credential. Treat links and QR codes like
|
||||||
|
passwords, and rotate the credential if one leaks.
|
||||||
|
</Callout>
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
---
|
||||||
|
title: Inbounds & Protocols
|
||||||
|
description: Create inbounds in 3x-ui — protocols, transports, traffic reset and expiry, and fallbacks that serve multiple protocols on one port.
|
||||||
|
icon: ArrowDownToLine
|
||||||
|
---
|
||||||
|
|
||||||
|
An **inbound** is a listener that accepts client connections on a port using a
|
||||||
|
particular protocol and transport. Most of your day-to-day work is creating and
|
||||||
|
managing inbounds and the clients inside them.
|
||||||
|
|
||||||
|
## Create an inbound
|
||||||
|
|
||||||
|
<Steps>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Add an inbound
|
||||||
|
|
||||||
|
Open **Inbounds → Add**, give it a remark, pick a **protocol**, and choose a
|
||||||
|
**port** and listen address.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Choose a transport and security
|
||||||
|
|
||||||
|
Pick the transport (TCP, WebSocket, gRPC, HTTPUpgrade, XHTTP, …) and the security
|
||||||
|
layer (none, TLS, or REALITY). See [Transports](/docs/config/transports) and
|
||||||
|
[REALITY](/docs/config/reality).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Add clients
|
||||||
|
|
||||||
|
Add one or more clients, each with its own credential, limits, and share link.
|
||||||
|
See [Clients](/docs/config/clients).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Set traffic limit, expiry, and reset
|
||||||
|
|
||||||
|
Optionally cap total traffic and set an expiry date for the inbound, and choose a
|
||||||
|
periodic **traffic reset** schedule: `never` (default), `hourly`, `daily`,
|
||||||
|
`weekly`, or `monthly`.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
</Steps>
|
||||||
|
|
||||||
|
## Supported protocols
|
||||||
|
|
||||||
|
The inbound editor accepts these protocols:
|
||||||
|
|
||||||
|
| Protocol | Notes |
|
||||||
|
| ---------------------- | ------------------------------------------------------------------------ |
|
||||||
|
| **VLESS** | Lightweight; the basis for REALITY + XTLS-Vision. Recommended. |
|
||||||
|
| **VMess** | Older but very widely supported by clients. |
|
||||||
|
| **Trojan** | TLS-based; supports XTLS and fallbacks. |
|
||||||
|
| **Shadowsocks** | Includes Shadowsocks-2022 (`2022-blake3-*`) ciphers. |
|
||||||
|
| **WireGuard** | Modern tunnel. |
|
||||||
|
| **Hysteria2** | Selected as `hysteria`; the panel emits `hysteria2://` links. |
|
||||||
|
| **HTTP** | HTTP proxy. |
|
||||||
|
| **Mixed (SOCKS/HTTP)** | A combined SOCKS + HTTP listener. |
|
||||||
|
| **Dokodemo-door / Tunnel** | Port forwarding / traffic redirect. |
|
||||||
|
| **MTProto** | Telegram MTProto proxy, served by a bundled `mtg` process (not Xray). |
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Hysteria2 isn't a separate protocol internally — it's the `hysteria` protocol
|
||||||
|
with the transport version set to 2, and the panel generates `hysteria2://`
|
||||||
|
share links for it.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Fallbacks — multiple protocols on one port
|
||||||
|
|
||||||
|
Fallbacks let a single TLS port (e.g. `443`) serve more than one protocol — for
|
||||||
|
example VLESS **and** Trojan — by routing unmatched handshakes to a child
|
||||||
|
inbound. In 3x-ui, fallbacks are managed in the panel (a master inbound's
|
||||||
|
**Fallbacks** list) rather than hand-written into JSON.
|
||||||
|
|
||||||
|
Fallbacks are available only when the master inbound is:
|
||||||
|
|
||||||
|
- **VLESS** or **Trojan**,
|
||||||
|
- on the raw **TCP** transport,
|
||||||
|
- with **TLS** or **REALITY** security.
|
||||||
|
|
||||||
|
Each fallback rule targets a child inbound and can match on `path`, `alpn`, and
|
||||||
|
`dest`. Client share links for a fallback child are automatically rewritten to
|
||||||
|
advertise the master's address, port, and TLS.
|
||||||
|
|
||||||
|
## Not sure which to pick?
|
||||||
|
|
||||||
|
Use the wizard to get a recommendation based on your goals and clients:
|
||||||
|
|
||||||
|
<ProtocolWizard />
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
For censorship resistance with modern clients, **VLESS + REALITY +
|
||||||
|
XTLS-Vision** is the usual best choice — continue to
|
||||||
|
[REALITY](/docs/config/reality).
|
||||||
|
</Callout>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"title": "Configuration",
|
||||||
|
"icon": "Settings",
|
||||||
|
"pages": [
|
||||||
|
"panel",
|
||||||
|
"ssl-certificates",
|
||||||
|
"inbounds",
|
||||||
|
"reality",
|
||||||
|
"transports",
|
||||||
|
"clients",
|
||||||
|
"subscription",
|
||||||
|
"share-links"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
---
|
||||||
|
title: Panel Settings
|
||||||
|
description: Every 3x-ui panel setting — web server, TLS, display, security, and notifications — with defaults from the source.
|
||||||
|
icon: SlidersHorizontal
|
||||||
|
---
|
||||||
|
|
||||||
|
**Panel Settings** controls how the panel itself is served and secured (separate
|
||||||
|
from your inbounds and clients). Settings are stored as key/value pairs; the
|
||||||
|
defaults below come straight from the panel source. Secrets (tokens, passwords)
|
||||||
|
are shown only as a "set / not set" indicator and are never returned to the
|
||||||
|
browser in full.
|
||||||
|
|
||||||
|
## Web server
|
||||||
|
|
||||||
|
| Setting | Default | Meaning |
|
||||||
|
| ------------------- | ----------------------- | ----------------------------------------------------------------------- |
|
||||||
|
| `webPort` | `2053` | Panel port (1–65535). The `XUI_PORT` env var overrides it at runtime. |
|
||||||
|
| `webListen` | _(all interfaces)_ | Bind the panel to a specific IP. |
|
||||||
|
| `webBasePath` | `/` | URL path the panel is served under (always normalized to `/…/`). |
|
||||||
|
| `webCertFile` / `webKeyFile` | _(none)_ | TLS certificate + key. When both are set, the panel serves **HTTPS**. |
|
||||||
|
| `sessionMaxAge` | `360` | Session lifetime in **minutes** (default 6 hours). |
|
||||||
|
| `trustedProxyCIDRs` | `127.0.0.1/32,::1/128` | IPs/CIDRs whose forwarded headers (real client IP) are trusted. |
|
||||||
|
| `panelOutbound` | _(none)_ | Route the panel's own egress (update checks, Telegram, geo/sub fetches) through a named Xray outbound. |
|
||||||
|
|
||||||
|
After changing the port or base path, the panel URL becomes
|
||||||
|
`http(s)://<server>:<port><web-base-path>`. You can preset the base path on first
|
||||||
|
launch with [`XUI_INIT_WEB_BASE_PATH`](/docs/reference/env-vars).
|
||||||
|
|
||||||
|
### TLS
|
||||||
|
|
||||||
|
Serving the panel over HTTPS protects your credentials in transit. Either set
|
||||||
|
`webCertFile` + `webKeyFile` — the [`x-ui` SSL menu](/docs/config/ssl-certificates)
|
||||||
|
can obtain a Let's Encrypt certificate for you — or terminate TLS at a
|
||||||
|
[reverse proxy](/docs/operations/reverse-proxy).
|
||||||
|
|
||||||
|
<Callout type="warn">
|
||||||
|
Never expose the panel over plain HTTP on the public internet. Use TLS, a
|
||||||
|
non-default port, and a long random web base path.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Display
|
||||||
|
|
||||||
|
| Setting | Default | Meaning |
|
||||||
|
| ---------------- | ------------------------------------------------ | ------------------------------------------------------------- |
|
||||||
|
| `pageSize` | `25` | Rows per page in lists (`0` disables pagination). |
|
||||||
|
| `expireDiff` | `0` | Days before expiry to start warning. |
|
||||||
|
| `trafficDiff` | `0` | Percent of quota remaining at which to start warning. |
|
||||||
|
| `remarkTemplate` | `{{INBOUND}}-{{EMAIL}}\|📊{{TRAFFIC_LEFT}}\|⏳{{DAYS_LEFT}}D` | Default client remark template (see [Share links](/docs/config/share-links#remark-template-variables)). |
|
||||||
|
| `timeLocation` | `Local` | Time zone for stats and expiry. |
|
||||||
|
| `datepicker` | `gregorian` | Calendar for date inputs (Gregorian or Jalali/Persian). |
|
||||||
|
|
||||||
|
## Security & authentication
|
||||||
|
|
||||||
|
Credentials, two-factor auth, the brute-force limiter, sessions, and LDAP are
|
||||||
|
covered in [First login](/docs/guide/first-login) and
|
||||||
|
[Security](/docs/operations/security). In short:
|
||||||
|
|
||||||
|
- Passwords are stored as **bcrypt** hashes; changing them logs out all sessions.
|
||||||
|
- **2FA (TOTP)** can be required at login.
|
||||||
|
- An **LDAP** fallback can authenticate users when the local password check fails.
|
||||||
|
- API access uses **API tokens** managed under Panel Settings (see the
|
||||||
|
[API reference](/docs/reference/api/api-tokens)).
|
||||||
|
|
||||||
|
## Notifications & subscription
|
||||||
|
|
||||||
|
These have their own settings groups and pages:
|
||||||
|
|
||||||
|
<Cards>
|
||||||
|
<Card title="Telegram bot" href="/docs/operations/telegram-bot" description="Token, chat IDs, alerts, and reports." />
|
||||||
|
<Card title="Subscription" href="/docs/config/subscription" description="Subscription server, formats, and paths." />
|
||||||
|
<Card title="Security" href="/docs/operations/security" description="2FA, IP limits, and hardening." />
|
||||||
|
</Cards>
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Email (SMTP) notifications are also configurable (host, port, encryption,
|
||||||
|
recipients) with the same event types as the Telegram bot.
|
||||||
|
</Callout>
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
---
|
||||||
|
title: REALITY
|
||||||
|
description: Set up a VLESS + REALITY inbound with XTLS-Vision in 3x-ui — keys, short IDs, SNI, fingerprints, and common pitfalls.
|
||||||
|
icon: ShieldCheck
|
||||||
|
---
|
||||||
|
|
||||||
|
**REALITY** is an Xray transport security that disguises your proxy as ordinary
|
||||||
|
traffic to a real, popular website. Unlike classic TLS, your server needs **no
|
||||||
|
certificate of its own** — it borrows the TLS handshake of the target site
|
||||||
|
(`dest`). Combined with the **XTLS-Vision** flow, it is fast and resistant to
|
||||||
|
deep-packet inspection.
|
||||||
|
|
||||||
|
REALITY is used with **VLESS** (and Trojan). The recommended flow is
|
||||||
|
`xtls-rprx-vision`.
|
||||||
|
|
||||||
|
## Key settings
|
||||||
|
|
||||||
|
When you choose **REALITY** as the security mode on a VLESS inbound, 3x-ui
|
||||||
|
exposes these fields:
|
||||||
|
|
||||||
|
| Field | What it is |
|
||||||
|
| ------------------------ | ------------------------------------------------------------------ |
|
||||||
|
| **Dest (target)** | A real TLS site to impersonate, e.g. `www.microsoft.com:443`. |
|
||||||
|
| **SNI / Server Names** | The hostname(s) clients send; must match the target's certificate. |
|
||||||
|
| **Public / Private key** | An **x25519** keypair. The private key stays on the server. |
|
||||||
|
| **Short IDs** | Hex strings used to authenticate clients (you can have several). |
|
||||||
|
| **Flow** | Set to `xtls-rprx-vision`. |
|
||||||
|
| **Fingerprint (uTLS)** | The client TLS fingerprint to mimic, e.g. `chrome`. |
|
||||||
|
|
||||||
|
The private key is generated with Xray's `x25519` utility (the panel can
|
||||||
|
generate the pair for you):
|
||||||
|
|
||||||
|
```bash title="generate an x25519 keypair"
|
||||||
|
xray x25519
|
||||||
|
```
|
||||||
|
|
||||||
|
## Set it up in the panel
|
||||||
|
|
||||||
|
<Steps>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Create a VLESS inbound
|
||||||
|
|
||||||
|
Add a new inbound, choose protocol **VLESS**, and set **Security** to
|
||||||
|
**reality**.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Choose a target (dest) and SNI
|
||||||
|
|
||||||
|
Pick a reputable site that supports TLS 1.3 and HTTP/2 and is reachable from your
|
||||||
|
server and your clients (for example `www.microsoft.com:443`). Set the server
|
||||||
|
names / SNI to match that site's certificate.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Generate keys and short IDs
|
||||||
|
|
||||||
|
Generate the x25519 keypair and one or more short IDs. Keep the **private key**
|
||||||
|
secret; clients only ever receive the **public key**.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Set the flow and fingerprint
|
||||||
|
|
||||||
|
Use the `xtls-rprx-vision` flow and a common uTLS fingerprint such as `chrome`.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Add a client and share the link
|
||||||
|
|
||||||
|
Create a client, then use its share link or QR code in a compatible app
|
||||||
|
(v2rayNG, Hiddify, Mihomo, and others).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
</Steps>
|
||||||
|
|
||||||
|
## What the configuration looks like
|
||||||
|
|
||||||
|
On the server, a REALITY inbound's `streamSettings` looks roughly like this:
|
||||||
|
|
||||||
|
```json title="server inbound (excerpt)"
|
||||||
|
{
|
||||||
|
"network": "tcp",
|
||||||
|
"security": "reality",
|
||||||
|
"realitySettings": {
|
||||||
|
"dest": "www.microsoft.com:443",
|
||||||
|
"serverNames": ["www.microsoft.com"],
|
||||||
|
"privateKey": "<x25519 private key>",
|
||||||
|
"shortIds": ["<hex short id>"],
|
||||||
|
"fingerprint": "chrome"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The matching client share link carries the **public** parameters:
|
||||||
|
|
||||||
|
```text title="vless:// (excerpt)"
|
||||||
|
vless://<uuid>@<server>:443?security=reality&pbk=<public-key>&sid=<short-id>&sni=www.microsoft.com&fp=chrome&spx=%2F&flow=xtls-rprx-vision#my-reality
|
||||||
|
```
|
||||||
|
|
||||||
|
- `pbk` — REALITY **public** key
|
||||||
|
- `sid` — short ID (matches one on the server)
|
||||||
|
- `sni` — server name (matches the target's certificate)
|
||||||
|
- `fp` — client fingerprint
|
||||||
|
- `spx` — spiderX path
|
||||||
|
- `flow` — `xtls-rprx-vision`
|
||||||
|
|
||||||
|
## Common pitfalls
|
||||||
|
|
||||||
|
<Callout type="warn">
|
||||||
|
|
||||||
|
- **Bad target.** The `dest` must be a real site that supports **TLS 1.3** and
|
||||||
|
**HTTP/2**, is reachable, and isn't blocked in your region. Pick a site you do
|
||||||
|
not own and that sees lots of traffic.
|
||||||
|
- **SNI mismatch.** The SNI / server names must match the target's real
|
||||||
|
certificate, or the handshake gives the disguise away.
|
||||||
|
- **Leaked private key.** Only ever distribute the **public** key to clients.
|
||||||
|
- **Wrong flow.** REALITY + XTLS-Vision needs `flow = xtls-rprx-vision` on both
|
||||||
|
the inbound client entry and the share link.
|
||||||
|
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Generate a config
|
||||||
|
|
||||||
|
Use the generator below to create a fresh X25519 keypair, UUID, and short ID,
|
||||||
|
then copy the server inbound JSON and the client share link. Everything is
|
||||||
|
computed **in your browser** — no keys or links are sent anywhere.
|
||||||
|
|
||||||
|
<RealityConfigGenerator />
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
The **private key** belongs only on your server. Share the generated
|
||||||
|
`vless://` link (which contains the **public** key) with clients.
|
||||||
|
</Callout>
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
---
|
||||||
|
title: Share Links
|
||||||
|
description: 3x-ui share-link formats (vless, vmess, trojan, ss, hysteria2, mtproto), the remark template variables, and an in-browser link inspector.
|
||||||
|
icon: Link
|
||||||
|
---
|
||||||
|
|
||||||
|
3x-ui generates a **share link** (and QR code) for each client. Client apps such
|
||||||
|
as v2rayNG, Hiddify, and Mihomo import these links to configure themselves.
|
||||||
|
|
||||||
|
## Link formats
|
||||||
|
|
||||||
|
| Scheme | Shape |
|
||||||
|
| -------------- | --------------------------------------------------------------- |
|
||||||
|
| `vless://` | `vless://<uuid>@<host>:<port>?<params>#<remark>` |
|
||||||
|
| `vmess://` | `vmess://<base64-json>` (a base64-encoded JSON object) |
|
||||||
|
| `trojan://` | `trojan://<password>@<host>:<port>?<params>#<remark>` |
|
||||||
|
| `ss://` | `ss://<userinfo>@<host>:<port>?<params>#<remark>` (SIP002; Shadowsocks-2022 uses percent-encoded userinfo) |
|
||||||
|
| `hysteria2://` | `hysteria2://<auth>@<host>:<port>?<params>#<remark>` |
|
||||||
|
| `tg://proxy` | `tg://proxy?server=…&port=…&secret=…` (MTProto) |
|
||||||
|
|
||||||
|
The query parameters carry the transport and security settings — `security`,
|
||||||
|
`sni`, `fp`, `pbk`, `sid`, `spx`, `flow`, `type`, `path`, `host`, `alpn`, and
|
||||||
|
more.
|
||||||
|
|
||||||
|
## Inspect a link
|
||||||
|
|
||||||
|
Paste any share link to decode every field. Parsing happens **entirely in your
|
||||||
|
browser** — the link is never sent over the network.
|
||||||
|
|
||||||
|
<ShareLinkInspector />
|
||||||
|
|
||||||
|
<Callout type="warn">
|
||||||
|
Share links contain everything needed to connect as a client, including the
|
||||||
|
client's credential. Treat them like passwords.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Remark template variables
|
||||||
|
|
||||||
|
The text after `#` in each link (the **remark**) is generated from a template
|
||||||
|
you control in Panel Settings (`remarkTemplate`). The default is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D
|
||||||
|
```
|
||||||
|
|
||||||
|
Tokens use `{{UPPER_CASE}}` syntax. The template is split on `|` into segments;
|
||||||
|
a segment whose only value is the unlimited marker `∞` (for `TRAFFIC_LEFT`,
|
||||||
|
`TRAFFIC_TOTAL`, `DAYS_LEFT`, or `TIME_LEFT`) is dropped, so unlimited clients
|
||||||
|
don't show empty decorations.
|
||||||
|
|
||||||
|
### Available tokens
|
||||||
|
|
||||||
|
| Token | Value |
|
||||||
|
| ----- | ----- |
|
||||||
|
| `{{EMAIL}}` / `{{USERNAME}}` | Client email (identifier) |
|
||||||
|
| `{{INBOUND}}` | Inbound remark |
|
||||||
|
| `{{HOST}}` | Host-row remark (managed hosts) |
|
||||||
|
| `{{ID}}` / `{{SHORT_ID}}` | Client UUID / its first 8 chars |
|
||||||
|
| `{{TELEGRAM_ID}}` · `{{SUB_ID}}` · `{{COMMENT}}` | Telegram ID, subscription ID, comment |
|
||||||
|
| `{{STATUS}}` / `{{STATUS_EMOJI}}` | `active`/`expired`/`depleted`/`disabled` (or ✅⏳🚫) |
|
||||||
|
| `{{DAYS_LEFT}}` / `{{TIME_LEFT}}` | Days, or `Xd Xh Xm`, remaining (`∞` if unlimited) |
|
||||||
|
| `{{EXPIRE_DATE}}` / `{{JALALI_EXPIRE_DATE}}` / `{{EXPIRE_UNIX}}` | Expiry as Gregorian / Jalali date / Unix seconds |
|
||||||
|
| `{{CREATED_UNIX}}` | Creation time (Unix seconds) |
|
||||||
|
| `{{TRAFFIC_USED}}` / `{{TRAFFIC_LEFT}}` / `{{TRAFFIC_TOTAL}}` | Human-readable usage (`∞` if unlimited) |
|
||||||
|
| `{{TRAFFIC_USED_BYTES}}` / `{{TRAFFIC_LEFT_BYTES}}` / `{{TRAFFIC_TOTAL_BYTES}}` | Same, in bytes |
|
||||||
|
| `{{UP}}` / `{{DOWN}}` | Upload / download (human-readable) |
|
||||||
|
| `{{RESET_DAYS}}` · `{{USAGE_PERCENTAGE}}` | Reset period (days) · used percent |
|
||||||
|
| `{{PROTOCOL}}` / `{{TRANSPORT}}` / `{{SECURITY}}` | e.g. `VLESS` / `ws` / `REALITY` |
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Usage tokens (traffic, days, status) appear in the subscription **body** but
|
||||||
|
are stripped from the display/QR view, so a shared QR doesn't leak a client's
|
||||||
|
remaining quota. Date tokens follow the `datepicker` setting (Gregorian or
|
||||||
|
Jalali).
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Related
|
||||||
|
|
||||||
|
<Cards>
|
||||||
|
<Card title="REALITY" href="/docs/config/reality" description="Generate a VLESS + REALITY config and link." />
|
||||||
|
<Card title="Subscription" href="/docs/config/subscription" description="Serve all of a client's links from one URL." />
|
||||||
|
</Cards>
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
---
|
||||||
|
title: SSL Certificates
|
||||||
|
description: Get and renew TLS certificates for the 3x-ui panel and inbounds — with the x-ui ACME menu (domain or bare IP), a Cloudflare DNS-01 wildcard, or manual Certbot.
|
||||||
|
icon: ShieldCheck
|
||||||
|
---
|
||||||
|
|
||||||
|
A TLS certificate lets you serve the **panel** over HTTPS (so your login and API
|
||||||
|
traffic are encrypted) and terminate TLS on **inbounds** (VLESS-TLS, Trojan,
|
||||||
|
Shadowsocks-TLS, and friends). There are three ways to obtain one:
|
||||||
|
|
||||||
|
- **The `x-ui` menu** — built-in [ACME](https://en.wikipedia.org/wiki/Automatic_Certificate_Management_Environment)
|
||||||
|
client. Easiest for a single domain or a bare IP.
|
||||||
|
- **Cloudflare DNS-01** — also from the menu; needed for **wildcard** certs or
|
||||||
|
when port 80 is blocked / the server sits behind Cloudflare's proxy.
|
||||||
|
- **Manual Certbot** — if you'd rather manage `acme.sh`/Certbot yourself.
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
If you put the panel behind Nginx or Caddy, let the proxy handle the
|
||||||
|
certificate instead — see [Reverse proxy](/docs/operations/reverse-proxy).
|
||||||
|
[REALITY](/docs/config/reality) inbounds need **no** certificate at all; they
|
||||||
|
borrow a real site's TLS. This page is for the panel and for classic TLS
|
||||||
|
inbounds.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## The `x-ui` SSL menu (Let's Encrypt)
|
||||||
|
|
||||||
|
Run `x-ui` and choose **`20` — SSL Certificate Management**. It drives
|
||||||
|
[acme.sh](https://github.com/acmesh-official/acme.sh) and offers:
|
||||||
|
|
||||||
|
| Option | What it does |
|
||||||
|
| ------------------------------ | ------------------------------------------------------------------- |
|
||||||
|
| Get SSL (Domain) | Issue a certificate for a domain via HTTP validation. |
|
||||||
|
| Get SSL for IP Address | Issue a short-lived (6-day, auto-renewing) cert for a **bare IP**. |
|
||||||
|
| Revoke | Revoke an existing certificate. |
|
||||||
|
| Force Renew | Renew now, before expiry. |
|
||||||
|
| Show Existing Domains | List certificates already on the server. |
|
||||||
|
| Set Cert paths for the panel | Point the panel's TLS at an issued cert (sets the fields for you). |
|
||||||
|
|
||||||
|
### Issue a certificate for a domain
|
||||||
|
|
||||||
|
<Steps>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Point the domain at the server
|
||||||
|
|
||||||
|
Create an `A` (and/or `AAAA`) record for your domain that resolves to this
|
||||||
|
server's public IP. Validation fails until DNS has propagated.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Free up port 80
|
||||||
|
|
||||||
|
HTTP validation needs **port 80** reachable from the internet and not already in
|
||||||
|
use. Stop anything bound to it for the duration, and allow it through the
|
||||||
|
[firewall](/docs/reference/ports-firewall).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Run the issuer
|
||||||
|
|
||||||
|
`x-ui` → `20` → **Get SSL (Domain)**, then enter the domain. acme.sh requests
|
||||||
|
the certificate and saves it under `/root/cert/<domain>/` as `fullchain.pem`
|
||||||
|
(the certificate chain) and `privkey.pem` (the private key).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Wire it into the panel
|
||||||
|
|
||||||
|
Choose **Set Cert paths for the panel** to fill in `webCertFile` and
|
||||||
|
`webKeyFile` and restart the panel, or set them yourself in
|
||||||
|
[Panel Settings](/docs/config/panel#tls). The panel serves HTTPS as soon as both
|
||||||
|
are set.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
</Steps>
|
||||||
|
|
||||||
|
### Issue a certificate for a bare IP
|
||||||
|
|
||||||
|
No domain? Choose **Get SSL for IP Address** to obtain a short-lived
|
||||||
|
certificate (valid ~6 days, renewed automatically) bound to the server's IP.
|
||||||
|
Useful for reaching the panel over HTTPS before you've set up a domain.
|
||||||
|
|
||||||
|
## Cloudflare (DNS-01 wildcard)
|
||||||
|
|
||||||
|
DNS validation proves you control the domain by creating a TXT record instead of
|
||||||
|
answering on port 80 — so it works **behind Cloudflare's proxy**, on servers
|
||||||
|
where port 80 is blocked, and for **wildcard** certificates (`*.example.com`).
|
||||||
|
|
||||||
|
Your domain's DNS must be managed by Cloudflare, and you need one of:
|
||||||
|
|
||||||
|
- a **scoped API token** with the `Zone:DNS:Edit` permission (recommended), or
|
||||||
|
- your account **email + Global API Key**.
|
||||||
|
|
||||||
|
<Steps>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Create a scoped API token
|
||||||
|
|
||||||
|
In the Cloudflare dashboard go to **My Profile → API Tokens →
|
||||||
|
[Create Token](https://dash.cloudflare.com/profile/api-tokens)**, pick the
|
||||||
|
**Edit zone DNS** template, scope it to the zone you're issuing for, and create
|
||||||
|
it. Copy the token — it's shown only once.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Run the Cloudflare issuer
|
||||||
|
|
||||||
|
`x-ui` → **`21` — Cloudflare SSL Certificate**. When asked, choose **`t`** for an
|
||||||
|
API token (the default) or **`g`** for the Global API Key, then enter your
|
||||||
|
domain (and, for the Global API Key, your account email and key). acme.sh creates
|
||||||
|
the TXT record, validates, and cleans it up.
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
<Step>
|
||||||
|
### Point the panel at it
|
||||||
|
|
||||||
|
As with the domain flow, use **Set Cert paths for the panel** (menu `20`) or set
|
||||||
|
`webCertFile` / `webKeyFile` in [Panel Settings](/docs/config/panel#tls).
|
||||||
|
</Step>
|
||||||
|
|
||||||
|
</Steps>
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Prefer a scoped token over the Global API Key — it only grants DNS edits on the
|
||||||
|
zone you choose, so a leak can't touch the rest of your Cloudflare account.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Manual (Certbot)
|
||||||
|
|
||||||
|
If you'd rather not use the menu, issue a certificate with Certbot's standalone
|
||||||
|
plugin (again, this needs port 80 free and the domain resolving to the server):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
apt-get install certbot -y
|
||||||
|
certbot certonly --standalone --agree-tos --register-unsafely-without-email -d yourdomain.com
|
||||||
|
certbot renew --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
Certbot writes the certificate to `/etc/letsencrypt/live/yourdomain.com/`
|
||||||
|
(`fullchain.pem` and `privkey.pem`). Point the panel at those two files in
|
||||||
|
[Panel Settings](/docs/config/panel#tls), and set up renewal — `certbot renew`
|
||||||
|
runs on a systemd timer by default.
|
||||||
|
|
||||||
|
## Using the certificate
|
||||||
|
|
||||||
|
- **Panel** — set `webCertFile` (the full chain) and `webKeyFile` (the private
|
||||||
|
key) in [Panel Settings](/docs/config/panel#tls). Both must be set for the
|
||||||
|
panel to switch to HTTPS. Menu option **`11` — View Current Settings** prints
|
||||||
|
the paths currently in use.
|
||||||
|
- **Inbounds** — when you enable TLS on an inbound, reference the same
|
||||||
|
certificate and key files (or paste their contents) in the inbound's TLS
|
||||||
|
settings. See [Inbounds](/docs/config/inbounds) and
|
||||||
|
[Transports](/docs/config/transports).
|
||||||
|
|
||||||
|
<Callout type="warn">
|
||||||
|
Certificates expire (Let's Encrypt: 90 days; IP certs: ~6 days). The menu and
|
||||||
|
Certbot both renew automatically, but the panel keeps reading the **files** at
|
||||||
|
their fixed paths — so renew **in place** rather than moving the files, and the
|
||||||
|
panel picks up the new cert on its next restart. **Force Renew** (menu `20`)
|
||||||
|
triggers a renewal on demand.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
## Next steps
|
||||||
|
|
||||||
|
<Cards>
|
||||||
|
<Card
|
||||||
|
title="Panel Settings"
|
||||||
|
href="/docs/config/panel#tls"
|
||||||
|
description="webCertFile / webKeyFile and the rest of the web-server settings."
|
||||||
|
/>
|
||||||
|
<Card
|
||||||
|
title="Reverse proxy"
|
||||||
|
href="/docs/operations/reverse-proxy"
|
||||||
|
description="Let Nginx or Caddy terminate TLS for you instead."
|
||||||
|
/>
|
||||||
|
<Card
|
||||||
|
title="REALITY"
|
||||||
|
href="/docs/config/reality"
|
||||||
|
description="Stealth TLS for inbounds — no certificate required."
|
||||||
|
/>
|
||||||
|
</Cards>
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
title: Subscription
|
||||||
|
description: Run the 3x-ui subscription server — base64/JSON/Clash formats, ports and paths, TLS, response headers, and custom templates.
|
||||||
|
icon: Rss
|
||||||
|
---
|
||||||
|
|
||||||
|
A **subscription** is a single URL that returns all of a client's
|
||||||
|
configurations. Client apps refresh it periodically, so when you change an
|
||||||
|
inbound, clients pick up the change automatically. The subscription server runs
|
||||||
|
as a **separate** server from the panel.
|
||||||
|
|
||||||
|
## Enable and configure
|
||||||
|
|
||||||
|
The subscription server is **on by default** (`subEnable`). Configure it in the
|
||||||
|
panel's subscription settings:
|
||||||
|
|
||||||
|
| Setting | Default | Meaning |
|
||||||
|
| ------------- | ------- | --------------------------------------------------------------- |
|
||||||
|
| `subPort` | `2096` | Listen port (separate from the panel). |
|
||||||
|
| `subListen` | _(all)_ | Bind address. |
|
||||||
|
| `subPath` | `/sub/` | Base path for raw subscription URLs. |
|
||||||
|
| `subDomain` | _(none)_| Public host; if set, the server only answers for that Host. |
|
||||||
|
| `subCertFile` / `subKeyFile` | _(none)_ | TLS cert + key — when set, the server serves **HTTPS**. |
|
||||||
|
| `subEncrypt` | `true` | Base64-encode the raw subscription body. |
|
||||||
|
| `subUpdates` | `12` | Suggested refresh interval (hours) sent to clients. |
|
||||||
|
|
||||||
|
A subscription URL looks like:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://<sub-host>:<sub-port>/sub/<sub-id>
|
||||||
|
```
|
||||||
|
|
||||||
|
where `<sub-id>` is the client's **Sub ID**.
|
||||||
|
|
||||||
|
The same Sub ID is served in several formats on different paths — the **Base64**
|
||||||
|
list at `subPath` and the **JSON** (Xray-json) config at the JSON path. Build the
|
||||||
|
URLs and preview both bodies here:
|
||||||
|
|
||||||
|
<SubscriptionBuilder />
|
||||||
|
|
||||||
|
## Output formats
|
||||||
|
|
||||||
|
The **format is chosen by path**, each with its own enable toggle:
|
||||||
|
|
||||||
|
| Format | Path | Enabled by | Output |
|
||||||
|
| --------------------- | --------- | ---------------- | --------------------------------------------------- |
|
||||||
|
| **Raw links** | `/sub/` | always (if on) | A list of `vless://`, `vmess://`, … links (base64-encoded when `subEncrypt` is on). |
|
||||||
|
| **JSON** | `/json/` | `subJsonEnable` | Full Xray client config(s). |
|
||||||
|
| **Clash / Mihomo** | `/clash/` | `subClashEnable` | YAML profile. |
|
||||||
|
|
||||||
|
Only enabled inbounds using **VLESS, VMess, Trojan, Shadowsocks, or Hysteria2**
|
||||||
|
appear in a subscription, ordered by their sub-sort index. Requesting `/sub/`
|
||||||
|
with an `Accept: text/html` header (or `?html=1`) returns a human-readable info
|
||||||
|
page instead of the raw body.
|
||||||
|
|
||||||
|
### Base64 vs JSON
|
||||||
|
|
||||||
|
The **Base64** body is just the newline-joined share links, standard-base64
|
||||||
|
encoded (toggle with `subEncrypt`). The **JSON** body wraps each client in a
|
||||||
|
complete Xray client config — a fixed skeleton (local mixed/HTTP inbounds, DNS,
|
||||||
|
routing, policy) plus a `proxy` outbound pointing at the inbound. 3x-ui emits a
|
||||||
|
**single config object for one client and an array for several**, uses the flat
|
||||||
|
outbound `settings` form (`address`/`port`/`id`, `level: 8`), and strips
|
||||||
|
`sockopt` from `streamSettings`.
|
||||||
|
|
||||||
|
## Response headers
|
||||||
|
|
||||||
|
Subscriptions return standard headers that compatible apps read:
|
||||||
|
|
||||||
|
- **`Subscription-Userinfo`** — `upload`, `download`, `total` (bytes; `total=0`
|
||||||
|
means unlimited) and `expire` (Unix seconds).
|
||||||
|
- **`Profile-Update-Interval`** — refresh interval in hours (`subUpdates`).
|
||||||
|
- **`Profile-Title`**, **`Support-Url`**, **`Profile-Web-Page-Url`**,
|
||||||
|
**`Announce`** — optional branding shown by some clients.
|
||||||
|
|
||||||
|
## Custom page templates
|
||||||
|
|
||||||
|
Point `subThemeDir` at a folder containing a custom info-page template to brand
|
||||||
|
the HTML subscription page. The per-client remark on each link is fully
|
||||||
|
templated — see [Share links → remark variables](/docs/config/share-links#remark-template-variables).
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Put the subscription server behind TLS (set `subCertFile`/`subKeyFile`, or a
|
||||||
|
[reverse proxy](/docs/operations/reverse-proxy)) so subscription contents
|
||||||
|
aren't exposed in transit.
|
||||||
|
</Callout>
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
---
|
||||||
|
title: Transports & Security
|
||||||
|
description: Every transport 3x-ui exposes — TCP, mKCP, WebSocket, gRPC, HTTPUpgrade, XHTTP, Hysteria — with their settings, plus FinalMask obfuscation, sockopt, TLS/REALITY, XTLS-Vision, and VLESS encryption.
|
||||||
|
icon: Network
|
||||||
|
---
|
||||||
|
|
||||||
|
A **transport** decides how packets are carried between client and server, a
|
||||||
|
**security** layer decides how they're encrypted and disguised, and **FinalMask**
|
||||||
|
can obfuscate what's left. The panel only offers valid combinations; this page
|
||||||
|
lists every transport's settings and the rules the panel enforces.
|
||||||
|
|
||||||
|
## Transports
|
||||||
|
|
||||||
|
Pick the transport (the inbound's `network`) in the inbound/outbound form. Each
|
||||||
|
network writes its own settings key on the wire (`tcpSettings`, `kcpSettings`, …).
|
||||||
|
|
||||||
|
| Transport | Settings key | When to use it |
|
||||||
|
| --------------- | --------------------- | ---------------------------------------------------------------------- |
|
||||||
|
| **TCP (Raw)** | `tcpSettings` | Lowest overhead. The basis for REALITY + XTLS-Vision and fallbacks; optional HTTP/1.1 header camouflage. |
|
||||||
|
| **mKCP** | `kcpSettings` | Reliable protocol over **UDP** — trades bandwidth for lower latency on lossy links. Carries no TLS/REALITY. |
|
||||||
|
| **WebSocket** | `wsSettings` | Works through CDNs and HTTP reverse proxies; very compatible. |
|
||||||
|
| **gRPC** | `grpcSettings` | HTTP/2-based; multiplexes well and proxies cleanly through Nginx. |
|
||||||
|
| **HTTPUpgrade** | `httpupgradeSettings` | CDN-friendly HTTP/1.1 `Upgrade`; lighter than full WebSocket. |
|
||||||
|
| **XHTTP** | `xhttpSettings` | Modern stream-multiplexed HTTP transport; CDN-friendly and REALITY-capable. |
|
||||||
|
| **Hysteria** | `hysteriaSettings` | QUIC-based transport — only for the **Hysteria2** protocol. |
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
**WireGuard** and **Tunnel** (dokodemo-door) inbounds expose no transport
|
||||||
|
selector — their stream carries only security/sockopt. Earlier panels also
|
||||||
|
exposed a raw **HTTP/2 (`http`)** transport; it has been superseded by **XHTTP**
|
||||||
|
and is no longer selectable.
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
### TCP (Raw) — `tcpSettings`
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| ------------------------------ | ------- | ----------------------------------------------------------------------- |
|
||||||
|
| `acceptProxyProtocol` | `false` | Accept the PROXY protocol from an upstream proxy so the real client IP is preserved. |
|
||||||
|
| `header.type` | `none` | `none`, or `http` for HTTP/1.1 camouflage. |
|
||||||
|
| `header.request` / `response` | — | When `type: http`: method, path, version and a header map that mimic a normal HTTP exchange. |
|
||||||
|
|
||||||
|
### mKCP — `kcpSettings`
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| ------------------ | ----------- | ---------------------------------------------------------------- |
|
||||||
|
| `mtu` | `1350` | Maximum transmission unit, in bytes (576–1460). |
|
||||||
|
| `tti` | `20` | Transmission time interval, in ms (10–100). Lower = more responsive, more overhead. |
|
||||||
|
| `uplinkCapacity` | `5` | Upload bandwidth budget, in **MB/s**. |
|
||||||
|
| `downlinkCapacity` | `20` | Download bandwidth budget, in **MB/s**. |
|
||||||
|
| `cwndMultiplier` | `1` | Congestion-window multiplier; raise to push harder on good links. |
|
||||||
|
| `maxSendingWindow` | `2097152` | Upper bound on in-flight packets. |
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
mKCP can't carry TLS or REALITY. To disguise it, add a **FinalMask** UDP mask —
|
||||||
|
the `mkcp-legacy` mask reproduces the classic header obfuscation that older Xray
|
||||||
|
stored in `kcpSettings.header`/`seed` (those fields no longer exist here).
|
||||||
|
</Callout>
|
||||||
|
|
||||||
|
### WebSocket — `wsSettings`
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| --------------------- | ------- | ---------------------------------------------------------------- |
|
||||||
|
| `path` | `/` | Request path — route on it when several services share one host. |
|
||||||
|
| `host` | _(none)_| `Host` header override (useful behind a CDN). |
|
||||||
|
| `headers` | `{}` | Extra request headers. |
|
||||||
|
| `heartbeatPeriod` | `0` | Seconds between keepalive pings; `0` disables them. |
|
||||||
|
| `acceptProxyProtocol` | `false` | Accept the PROXY protocol from an upstream. |
|
||||||
|
|
||||||
|
### gRPC — `grpcSettings`
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| ------------- | ------- | --------------------------------------------------------- |
|
||||||
|
| `serviceName` | _(none)_| gRPC service path; acts like a secret route. |
|
||||||
|
| `authority` | _(none)_| `:authority` pseudo-header override. |
|
||||||
|
| `multiMode` | `false` | Multiplex several streams over one connection. |
|
||||||
|
|
||||||
|
### HTTPUpgrade — `httpupgradeSettings`
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| --------------------- | ------- | --------------------------------------------- |
|
||||||
|
| `path` | `/` | Request path. |
|
||||||
|
| `host` | _(none)_| `Host` header override. |
|
||||||
|
| `headers` | `{}` | Extra request headers. |
|
||||||
|
| `acceptProxyProtocol` | `false` | Accept the PROXY protocol from an upstream. |
|
||||||
|
|
||||||
|
HTTPUpgrade is a one-shot HTTP/1.1 `Upgrade` with no WebSocket framing — there's
|
||||||
|
no heartbeat field.
|
||||||
|
|
||||||
|
### XHTTP — `xhttpSettings`
|
||||||
|
|
||||||
|
XHTTP (SplitHTTP) has a large field set; the panel fills sensible defaults. The
|
||||||
|
ones you'll usually touch:
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| ---------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||||
|
| `path` | `/` | Request path. |
|
||||||
|
| `host` | _(none)_ | `Host` header override. |
|
||||||
|
| `mode` | `auto` | `auto`, `packet-up`, `stream-up`, or `stream-one`. `packet-up` is the most CDN-compatible; `stream-*` are lower latency. |
|
||||||
|
| `xPaddingBytes` | `100-1000` | Random padding range that blurs packet sizes. |
|
||||||
|
| `scMaxBufferedPosts` | `30` | Server-side buffer for uploaded POSTs. |
|
||||||
|
| `scStreamUpServerSecs` | `20-80` | Stream-up server window (dash range). |
|
||||||
|
| `xmux` (`enableXmux`) | _(off)_ | Connection multiplexing — `maxConcurrency` `16-32`, `maxConnections` `6`, … Turn on for high concurrency. |
|
||||||
|
|
||||||
|
Session-ID fields (`sessionIDPlacement`, `sessionIDKey`, `sessionIDTable`,
|
||||||
|
`sessionIDLength`) and the `scMin/MaxEachPostBytes` knobs are advanced; leave them
|
||||||
|
empty unless you're matching a specific upstream.
|
||||||
|
|
||||||
|
### Hysteria — `hysteriaSettings`
|
||||||
|
|
||||||
|
Only valid when the protocol is **Hysteria2**.
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| ---------------- | ------- | ----------------------------------------------------------------------- |
|
||||||
|
| `version` | `2` | Hysteria protocol version. |
|
||||||
|
| `auth` | _(none)_| Shared authentication string. |
|
||||||
|
| `udpIdleTimeout` | `60` | Seconds (2–600) before idle UDP sessions are dropped. |
|
||||||
|
| `masquerade` | — | Disguise as an HTTP/3 server: `type` `proxy`/`file`/`string` with `url`/`dir`/`content`, plus `headers` and `statusCode`. |
|
||||||
|
|
||||||
|
## FinalMask — late-layer obfuscation
|
||||||
|
|
||||||
|
**FinalMask** wraps traffic **after** the transport and security layers, so it can
|
||||||
|
disguise transports that don't carry TLS (like mKCP) or add a second skin on top of
|
||||||
|
TLS. Masks are configured per direction:
|
||||||
|
|
||||||
|
- **TCP masks** — `fragment`, `sudoku`, `header-custom`.
|
||||||
|
- **UDP masks** — `salamander`, `mkcp-legacy`, `header-custom`, `xdns`, `xicmp`,
|
||||||
|
`noise`, `sudoku`, `realm`. (`mkcp-legacy` reproduces the old mKCP header
|
||||||
|
obfuscation.)
|
||||||
|
- **QUIC params** — congestion control (`reno`, `bbr`, `brutal`, `force-brutal`),
|
||||||
|
Brutal up/down rates, `udpHop` (rotate the QUIC port across a range to dodge
|
||||||
|
port blocking), and receive-window tuning.
|
||||||
|
|
||||||
|
FinalMask replaces the per-transport `header`/`seed` obfuscation that older Xray
|
||||||
|
builds exposed.
|
||||||
|
|
||||||
|
## sockopt — low-level socket options
|
||||||
|
|
||||||
|
`sockopt` rides alongside any transport and tunes the underlying socket. The most
|
||||||
|
useful fields:
|
||||||
|
|
||||||
|
| Field | Default | Meaning |
|
||||||
|
| --------------------- | ------- | ---------------------------------------------------------------- |
|
||||||
|
| `tcpFastOpen` | `false` | Enable TCP Fast Open. |
|
||||||
|
| `tcpcongestion` | `bbr` | Congestion control: `bbr`, `cubic`, or `reno`. |
|
||||||
|
| `tproxy` | `off` | Transparent proxy mode: `off`, `redirect`, or `tproxy`. |
|
||||||
|
| `domainStrategy` | `AsIs` | How addresses resolve (`UseIP`, `ForceIPv4`, …). |
|
||||||
|
| `dialerProxy` | _(none)_| Chain this outbound's dialing through another outbound tag. |
|
||||||
|
| `interface` | _(none)_| Bind to a specific network interface. |
|
||||||
|
| `mark` | `0` | SO_MARK for policy routing (`0` = unset). |
|
||||||
|
|
||||||
|
Numeric fields left at `0` are omitted on the wire so Xray keeps OS defaults.
|
||||||
|
Advanced entries (`happyEyeballs`, `customSockopt[]`, keepalive timers) are
|
||||||
|
available for special cases.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
The security layer is one of **`none`**, **`tls`**, or **`reality`**, with these
|
||||||
|
eligibility rules:
|
||||||
|
|
||||||
|
| Security | Eligible transports | Eligible protocols |
|
||||||
|
| ----------- | -------------------------------------------- | --------------------------------------------------- |
|
||||||
|
| **TLS** | `tcp`, `ws`, `grpc`, `httpupgrade`, `xhttp` | VLESS, VMess, Trojan, Shadowsocks (Hysteria2 is always TLS) |
|
||||||
|
| **REALITY** | `tcp`, `grpc`, `xhttp` | VLESS, Trojan |
|
||||||
|
|
||||||
|
mKCP and Hysteria don't take a separate TLS/REALITY layer — mKCP runs plaintext
|
||||||
|
(obfuscate with FinalMask), and Hysteria is QUIC/TLS by design. REALITY disguises
|
||||||
|
your server as a real TLS site and needs no certificate — see
|
||||||
|
[REALITY](/docs/config/reality).
|
||||||
|
|
||||||
|
## XTLS-Vision flow
|
||||||
|
|
||||||
|
The `xtls-rprx-vision` flow is fast and DPI-resistant. It's available for
|
||||||
|
**VLESS** when either:
|
||||||
|
|
||||||
|
- the transport is raw **TCP** with **TLS** or **REALITY** security (classic
|
||||||
|
XTLS-Vision), or
|
||||||
|
- the transport is **XHTTP** with VLESS encryption enabled (see below).
|
||||||
|
|
||||||
|
Set the flow on the VLESS **client**, not the inbound. With classic Vision on
|
||||||
|
TCP, the panel can also offer a **Vision seed** once a client uses the flow.
|
||||||
|
|
||||||
|
## VLESS encryption (ML-KEM)
|
||||||
|
|
||||||
|
VLESS supports post-quantum **encryption** (ML-KEM / `mlkem768x25519`), stored in
|
||||||
|
the inbound's `decryption` (server) and clients' `encryption` (for link
|
||||||
|
generation). When enabled, it unlocks the Vision flow over XHTTP. Generate the
|
||||||
|
keys from the panel's VLESS settings.
|
||||||
|
|
||||||
|
## Shadowsocks ciphers
|
||||||
|
|
||||||
|
Shadowsocks inbounds support both classic ciphers and **Shadowsocks-2022**
|
||||||
|
(method names starting with `2022-blake3-`). Most ciphers are multi-user;
|
||||||
|
`2022-blake3-chacha20-poly1305` is single-user.
|
||||||
|
|
||||||
|
<Callout type="info">
|
||||||
|
Transports and security must match on both ends. The client's share link
|
||||||
|
encodes them (`type=ws`, `security=reality`, `flow=xtls-rprx-vision`, …) —
|
||||||
|
decode any link with the [share-link inspector](/docs/config/share-links).
|
||||||
|
</Callout>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user