2023-02-09 19:18:06 +00:00
#!/bin/bash
red = '\033[0;31m'
green = '\033[0;32m'
2024-12-20 17:33:27 +00:00
blue = '\033[0;34m'
2023-02-09 19:18:06 +00:00
yellow = '\033[0;33m'
plain = '\033[0m'
2026-05-19 11:09:35 +00:00
cur_dir = $( pwd )
2026-01-03 02:57:19 +00:00
xui_folder = " ${ XUI_MAIN_FOLDER : =/usr/local/x-ui } "
xui_service = " ${ XUI_SERVICE : =/etc/systemd/system } "
2023-02-09 19:18:06 +00:00
# check root
2026-05-19 11:09:35 +00:00
[ [ $EUID -ne 0 ] ] && echo -e " ${ red } Fatal error: ${ plain } Please run this script with root privilege \n " && exit 1
2023-02-09 19:18:06 +00:00
2023-03-11 15:05:35 +00:00
# Check OS and set release variable
if [ [ -f /etc/os-release ] ] ; then
source /etc/os-release
release = $ID
2026-05-04 11:20:24 +00:00
elif [ [ -f /usr/lib/os-release ] ] ; then
2023-03-11 15:05:35 +00:00
source /usr/lib/os-release
release = $ID
2023-02-09 19:18:06 +00:00
else
2026-05-19 11:09:35 +00:00
echo "Failed to check the system OS, please contact the author!" >& 2
exit 1
2023-02-09 19:18:06 +00:00
fi
2023-03-11 15:05:35 +00:00
echo " The OS release is: $release "
2023-02-09 19:18:06 +00:00
2024-04-01 08:42:28 +00:00
arch( ) {
2023-04-21 15:30:14 +00:00
case " $( uname -m) " in
2025-12-03 20:40:49 +00:00
x86_64 | x64 | amd64) echo 'amd64' ; ;
i*86 | x86) echo '386' ; ;
armv8* | armv8 | arm64 | aarch64) echo 'arm64' ; ;
armv7* | armv7 | arm) echo 'armv7' ; ;
armv6* | armv6) echo 'armv6' ; ;
armv5* | armv5) echo 'armv5' ; ;
s390x) echo 's390x' ; ;
2026-05-19 11:09:35 +00:00
*) echo -e " ${ green } Unsupported CPU architecture! ${ plain } " && rm -f install.sh && exit 1 ; ;
2023-04-21 15:30:14 +00:00
esac
}
2024-01-20 09:32:35 +00:00
2025-03-21 15:30:31 +00:00
echo " Arch: $( arch) "
2023-02-09 19:18:06 +00:00
2025-12-27 23:03:33 +00:00
# Simple helpers
is_ipv4( ) {
[ [ " $1 " = ~ ^( [ 0-9] { 1,3} \. ) { 3} [ 0-9] { 1,3} $ ] ] && return 0 || return 1
}
is_ipv6( ) {
[ [ " $1 " = ~ : ] ] && return 0 || return 1
}
is_ip( ) {
is_ipv4 " $1 " || is_ipv6 " $1 "
}
is_domain( ) {
2026-01-12 01:53:43 +00:00
[ [ " $1 " = ~ ^( [ A-Za-z0-9] ( -*[ A-Za-z0-9] ) *\. ) +( xn--[ a-z0-9] { 2,} | [ A-Za-z] { 2,} ) $ ] ] && return 0 || return 1
2026-01-11 14:28:43 +00:00
}
# Port helpers
is_port_in_use( ) {
local port = " $1 "
2026-05-04 11:20:24 +00:00
if command -v ss > /dev/null 2>& 1; then
ss -ltn 2> /dev/null | awk -v p = " : ${ port } $" '$4 ~ p {exit 0} END {exit 1}'
2026-01-11 14:28:43 +00:00
return
fi
2026-05-04 11:20:24 +00:00
if command -v netstat > /dev/null 2>& 1; then
netstat -lnt 2> /dev/null | awk -v p = " : ${ port } " '$4 ~ p {exit 0} END {exit 1}'
2026-01-11 14:28:43 +00:00
return
fi
2026-05-04 11:20:24 +00:00
if command -v lsof > /dev/null 2>& 1; then
lsof -nP -iTCP:${ port } -sTCP:LISTEN > /dev/null 2>& 1 && return 0
2026-01-11 14:28:43 +00:00
fi
return 1
2025-12-27 23:03:33 +00:00
}
2023-02-09 19:18:06 +00:00
install_base( ) {
2023-04-11 22:10:33 +00:00
case " ${ release } " in
2025-12-03 20:40:49 +00:00
ubuntu | debian | armbian)
2026-05-19 11:09:35 +00:00
apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
2026-05-19 11:09:35 +00:00
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
centos)
if [ [ " ${ VERSION_ID } " = ~ ^7 ] ] ; then
2026-05-19 11:09:35 +00:00
yum -y update && yum install -y cronie curl tar tzdata socat ca-certificates openssl
2025-12-03 20:40:49 +00:00
else
2026-05-19 11:09:35 +00:00
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
2025-12-03 20:40:49 +00:00
fi
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
arch | manjaro | parch)
2026-05-19 11:09:35 +00:00
pacman -Syu && pacman -Syu --noconfirm cronie curl tar tzdata socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
opensuse-tumbleweed | opensuse-leap)
2026-05-19 11:09:35 +00:00
zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
alpine)
2026-05-19 11:09:35 +00:00
apk update && apk add dcron curl tar tzdata socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2025-12-03 20:40:49 +00:00
*)
2026-05-19 11:09:35 +00:00
apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
2026-05-04 11:20:24 +00:00
; ;
2023-04-11 22:10:33 +00:00
esac
2023-02-09 19:18:06 +00:00
}
2023-04-03 15:51:37 +00:00
2026-05-19 11:09:35 +00:00
gen_random_string( ) {
local length = " $1 "
openssl rand -base64 $(( length * 2 )) \
| tr -dc 'a-zA-Z0-9' \
| head -c " $length "
}
2026-05-23 17:52:37 +00:00
install_postgres_local( ) {
2026-05-28 15:20:16 +00:00
local pg_user pg_pass
2026-05-23 17:52:37 +00:00
pg_pass = $( gen_random_string 24)
2026-05-28 15:20:16 +00:00
local pg_db = "xui"
local pg_host = "127.0.0.1"
local pg_port = "5432"
2026-05-23 17:52:37 +00:00
case " ${ release } " in
ubuntu | debian | armbian)
apt-get update >& 2 && apt-get install -y -q postgresql >& 2 || return 1
; ;
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
dnf install -y -q postgresql-server postgresql-contrib >& 2 || return 1
[ [ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ] ] || postgresql-setup --initdb >& 2 || return 1
; ;
centos)
if [ [ " ${ VERSION_ID } " = ~ ^7 ] ] ; then
yum install -y postgresql-server postgresql-contrib >& 2 || return 1
else
dnf install -y -q postgresql-server postgresql-contrib >& 2 || return 1
fi
[ [ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ] ] || postgresql-setup --initdb >& 2 || return 1
; ;
arch | manjaro | parch)
pacman -Syu --noconfirm postgresql >& 2 || return 1
if [ [ ! -f /var/lib/postgres/data/PG_VERSION ] ] ; then
sudo -u postgres initdb -D /var/lib/postgres/data >& 2 || return 1
fi
; ;
opensuse-tumbleweed | opensuse-leap)
zypper -q install -y postgresql-server postgresql-contrib >& 2 || return 1
if [ [ ! -f /var/lib/pgsql/data/PG_VERSION ] ] ; then
install -d -o postgres -g postgres -m 700 /var/lib/pgsql/data >& 2 || return 1
su - postgres -c "initdb -D /var/lib/pgsql/data" >& 2 || return 1
fi
; ;
alpine)
apk add --no-cache postgresql postgresql-contrib >& 2 || return 1
if [ [ ! -f /var/lib/postgresql/data/PG_VERSION ] ] ; then
/etc/init.d/postgresql setup >& 2 || return 1
fi
rc-update add postgresql default >& 2 2> /dev/null || true
rc-service postgresql start >& 2 || return 1
; ;
*)
echo -e " ${ red } Unsupported distro for automatic PostgreSQL install: ${ release } ${ plain } " >& 2
return 1
; ;
esac
if [ [ " ${ release } " != "alpine" ] ] ; then
systemctl enable --now postgresql >& 2 || return 1
fi
# Wait briefly for the server to accept connections.
local i
for i in 1 2 3 4 5; do
sudo -u postgres psql -tAc 'SELECT 1' > /dev/null 2>& 1 && break
sleep 1
done
2026-05-28 15:20:16 +00:00
local existing_owner = ""
existing_owner = $( sudo -u postgres psql -tAc \
" SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname=' ${ pg_db } ' " 2> /dev/null \
| tr -d '[:space:]' )
if [ [ -n " ${ existing_owner } " && " ${ existing_owner } " != "postgres" ] ] ; then
pg_user = " ${ existing_owner } "
else
pg_user = $( gen_random_string 8)
fi
# Idempotent role/db creation. Identifiers are double-quoted because a
# random username may start with a digit, which Postgres rejects unquoted.
2026-05-23 17:52:37 +00:00
sudo -u postgres psql -tAc " SELECT 1 FROM pg_roles WHERE rolname=' ${ pg_user } ' " 2> /dev/null \
| grep -q 1 \
2026-05-28 15:20:16 +00:00
|| sudo -u postgres psql -c " CREATE USER \" ${ pg_user } \" WITH PASSWORD ' ${ pg_pass } '; " >& 2 || return 1
2026-05-23 17:52:37 +00:00
sudo -u postgres psql -tAc " SELECT 1 FROM pg_database WHERE datname=' ${ pg_db } ' " 2> /dev/null \
| grep -q 1 \
2026-05-28 15:20:16 +00:00
|| sudo -u postgres psql -c " CREATE DATABASE \" ${ pg_db } \" OWNER \" ${ pg_user } \"; " >& 2 || return 1
2026-05-23 17:52:37 +00:00
2026-05-28 15:20:16 +00:00
sudo -u postgres psql -c " ALTER USER \" ${ pg_user } \" WITH PASSWORD ' ${ pg_pass } '; " >& 2 || return 1
2026-05-23 17:52:37 +00:00
local pg_pass_enc
pg_pass_enc = $( printf '%s' " ${ pg_pass } " | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g' )
2026-05-28 15:20:16 +00:00
if [ [ -n " ${ PG_CRED_FILE :- } " ] ] ; then
local prev_umask
prev_umask = $( umask )
umask 077
if ! cat > " ${ PG_CRED_FILE } " << EOF; then
PG_USER = ${ pg_user }
PG_PASS = ${ pg_pass }
PG_HOST = ${ pg_host }
PG_PORT = ${ pg_port }
PG_DB = ${ pg_db }
EOF
umask " ${ prev_umask } "
echo -e " ${ red } Failed to write PostgreSQL credentials to ${ PG_CRED_FILE } ${ plain } " >& 2
return 1
fi
umask " ${ prev_umask } "
fi
echo " postgres:// ${ pg_user } : ${ pg_pass_enc } @ ${ pg_host } : ${ pg_port } / ${ pg_db } ?sslmode=disable "
2026-05-23 17:52:37 +00:00
return 0
}
2026-05-31 15:53:34 +00:00
ensure_pg_client( ) {
if command -v pg_dump > /dev/null 2>& 1 && command -v pg_restore > /dev/null 2>& 1; then
return 0
fi
echo -e " ${ yellow } Installing PostgreSQL client tools (pg_dump/pg_restore) for in-panel backup... ${ plain } " >& 2
case " ${ release } " in
ubuntu | debian | armbian)
apt-get update >& 2 && apt-get install -y -q postgresql-client >& 2 || return 1
; ;
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
dnf install -y -q postgresql >& 2 || return 1
; ;
centos)
if [ [ " ${ VERSION_ID } " = ~ ^7 ] ] ; then
yum install -y postgresql >& 2 || return 1
else
dnf install -y -q postgresql >& 2 || return 1
fi
; ;
arch | manjaro | parch)
pacman -Sy --noconfirm postgresql >& 2 || return 1
; ;
opensuse-tumbleweed | opensuse-leap)
zypper -q install -y postgresql >& 2 || return 1
; ;
alpine)
apk add --no-cache postgresql-client >& 2 || return 1
; ;
*)
return 1
; ;
esac
command -v pg_dump > /dev/null 2>& 1 && command -v pg_restore > /dev/null 2>& 1
}
2025-12-27 23:03:33 +00:00
install_acme( ) {
echo -e " ${ green } Installing acme.sh for SSL certificate management... ${ plain } "
cd ~ || return 1
2026-05-04 11:20:24 +00:00
curl -s https://get.acme.sh | sh > /dev/null 2>& 1
2025-12-27 23:03:33 +00:00
if [ $? -ne 0 ] ; then
echo -e " ${ red } Failed to install acme.sh ${ plain } "
return 1
else
echo -e " ${ green } acme.sh installed successfully ${ plain } "
fi
return 0
}
setup_ssl_certificate( ) {
local domain = " $1 "
local server_ip = " $2 "
local existing_port = " $3 "
local existing_webBasePath = " $4 "
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
echo -e " ${ green } Setting up SSL certificate... ${ plain } "
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# Check if acme.sh is installed
2026-05-04 11:20:24 +00:00
if ! command -v ~/.acme.sh/acme.sh & > /dev/null; then
2025-12-27 23:03:33 +00:00
install_acme
if [ $? -ne 0 ] ; then
echo -e " ${ yellow } Failed to install acme.sh, skipping SSL setup ${ plain } "
return 1
fi
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# Create certificate directory
local certPath = " /root/cert/ ${ domain } "
mkdir -p " $certPath "
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# Issue certificate
echo -e " ${ green } Issuing SSL certificate for ${ domain } ... ${ plain } "
echo -e " ${ yellow } Note: Port 80 must be open and accessible from the internet ${ plain } "
2026-05-04 11:20:24 +00:00
~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>& 1
2025-12-27 23:03:33 +00:00
~/.acme.sh/acme.sh --issue -d ${ domain } --listen-v6 --standalone --httpport 80 --force
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
if [ $? -ne 0 ] ; then
echo -e " ${ yellow } Failed to issue certificate for ${ domain } ${ plain } "
echo -e " ${ yellow } Please ensure port 80 is open and try again later with: x-ui ${ plain } "
2026-05-04 11:20:24 +00:00
rm -rf ~/.acme.sh/${ domain } 2> /dev/null
rm -rf " $certPath " 2> /dev/null
2025-12-27 23:03:33 +00:00
return 1
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# Install certificate
~/.acme.sh/acme.sh --installcert -d ${ domain } \
--key-file /root/cert/${ domain } /privkey.pem \
--fullchain-file /root/cert/${ domain } /fullchain.pem \
2026-05-04 11:20:24 +00:00
--reloadcmd "systemctl restart x-ui" > /dev/null 2>& 1
2025-12-27 23:03:33 +00:00
if [ $? -ne 0 ] ; then
echo -e " ${ yellow } Failed to install certificate ${ plain } "
return 1
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# Enable auto-renew
2026-05-04 11:20:24 +00:00
~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>& 1
2026-05-19 11:09:35 +00:00
# Secure permissions: private key readable only by owner
2026-05-04 11:20:24 +00:00
chmod 600 $certPath /privkey.pem 2> /dev/null
chmod 644 $certPath /fullchain.pem 2> /dev/null
2025-12-27 23:03:33 +00:00
# Set certificate for panel
local webCertFile = " /root/cert/ ${ domain } /fullchain.pem "
local webKeyFile = " /root/cert/ ${ domain } /privkey.pem "
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
if [ [ -f " $webCertFile " && -f " $webKeyFile " ] ] ; then
2026-05-04 11:20:24 +00:00
${ xui_folder } /x-ui cert -webCert " $webCertFile " -webCertKey " $webKeyFile " > /dev/null 2>& 1
2025-12-27 23:03:33 +00:00
echo -e " ${ green } SSL certificate installed and configured successfully! ${ plain } "
return 0
else
echo -e " ${ yellow } Certificate files not found ${ plain } "
return 1
fi
}
2026-01-05 04:28:02 +00:00
# Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
# Requires acme.sh and port 80 open for HTTP-01 challenge
setup_ip_certificate( ) {
local ipv4 = " $1 "
2026-05-04 11:20:24 +00:00
local ipv6 = " $2 " # optional
2025-12-27 23:03:33 +00:00
2026-01-05 04:28:02 +00:00
echo -e " ${ green } Setting up Let's Encrypt IP certificate (shortlived profile)... ${ plain } "
echo -e " ${ yellow } Note: IP certificates are valid for ~6 days and will auto-renew. ${ plain } "
2026-01-11 14:28:43 +00:00
echo -e " ${ yellow } Default listener is port 80. If you choose another port, ensure external port 80 forwards to it. ${ plain } "
2025-12-27 23:03:33 +00:00
2026-01-05 04:28:02 +00:00
# Check for acme.sh
2026-05-04 11:20:24 +00:00
if ! command -v ~/.acme.sh/acme.sh & > /dev/null; then
2026-01-05 04:28:02 +00:00
install_acme
if [ $? -ne 0 ] ; then
echo -e " ${ red } Failed to install acme.sh ${ plain } "
return 1
fi
fi
# Validate IP address
if [ [ -z " $ipv4 " ] ] ; then
echo -e " ${ red } IPv4 address is required ${ plain } "
return 1
fi
if ! is_ipv4 " $ipv4 " ; then
echo -e " ${ red } Invalid IPv4 address: $ipv4 ${ plain } "
return 1
fi
# Create certificate directory
local certDir = "/root/cert/ip"
2025-12-27 23:03:33 +00:00
mkdir -p " $certDir "
2026-01-05 04:28:02 +00:00
# Build domain arguments
local domain_args = " -d ${ ipv4 } "
if [ [ -n " $ipv6 " ] ] && is_ipv6 " $ipv6 " ; then
domain_args = " ${ domain_args } -d ${ ipv6 } "
echo -e " ${ green } Including IPv6 address: ${ ipv6 } ${ plain } "
2025-12-27 23:03:33 +00:00
fi
2026-05-19 11:09:35 +00:00
# Set reload command for auto-renewal (add || true so it doesn't fail during first install)
2026-01-05 04:28:02 +00:00
local reloadCmd = "systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
2025-12-27 23:03:33 +00:00
2026-01-11 14:28:43 +00:00
# Choose port for HTTP-01 listener (default 80, prompt override)
local WebPort = ""
read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
WebPort = " ${ WebPort :- 80 } "
if ! [ [ " ${ WebPort } " = ~ ^[ 0-9] +$ ] ] || ( ( WebPort < 1 || WebPort > 65535) ) ; then
echo -e " ${ red } Invalid port provided. Falling back to 80. ${ plain } "
WebPort = 80
fi
echo -e " ${ green } Using port ${ WebPort } for standalone validation. ${ plain } "
if [ [ " ${ WebPort } " -ne 80 ] ] ; then
echo -e " ${ yellow } Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${ WebPort } . ${ plain } "
fi
# Ensure chosen port is available
while true; do
if is_port_in_use " ${ WebPort } " ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ yellow } Port ${ WebPort } is in use. ${ plain } "
2026-01-11 14:28:43 +00:00
local alt_port = ""
read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
alt_port = " ${ alt_port // / } "
if [ [ -z " ${ alt_port } " ] ] ; then
echo -e " ${ red } Port ${ WebPort } is busy; cannot proceed. ${ plain } "
return 1
fi
if ! [ [ " ${ alt_port } " = ~ ^[ 0-9] +$ ] ] || ( ( alt_port < 1 || alt_port > 65535) ) ; then
echo -e " ${ red } Invalid port provided. ${ plain } "
return 1
fi
WebPort = " ${ alt_port } "
continue
else
echo -e " ${ green } Port ${ WebPort } is free and ready for standalone validation. ${ plain } "
break
fi
done
2026-01-05 04:28:02 +00:00
# Issue certificate with shortlived profile
echo -e " ${ green } Issuing IP certificate for ${ ipv4 } ... ${ plain } "
2026-05-04 11:20:24 +00:00
~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force > /dev/null 2>& 1
2026-01-05 04:28:02 +00:00
~/.acme.sh/acme.sh --issue \
${ domain_args } \
--standalone \
--server letsencrypt \
--certificate-profile shortlived \
--days 6 \
2026-01-11 14:28:43 +00:00
--httpport ${ WebPort } \
2026-01-05 04:28:02 +00:00
--force
if [ $? -ne 0 ] ; then
echo -e " ${ red } Failed to issue IP certificate ${ plain } "
2026-01-11 14:28:43 +00:00
echo -e " ${ yellow } Please ensure port ${ WebPort } is reachable (or forwarded from external port 80) ${ plain } "
2026-01-05 04:28:02 +00:00
# Cleanup acme.sh data for both IPv4 and IPv6 if specified
2026-05-04 11:20:24 +00:00
rm -rf ~/.acme.sh/${ ipv4 } 2> /dev/null
[ [ -n " $ipv6 " ] ] && rm -rf ~/.acme.sh/${ ipv6 } 2> /dev/null
rm -rf ${ certDir } 2> /dev/null
2026-01-05 04:28:02 +00:00
return 1
2025-12-27 23:03:33 +00:00
fi
2026-01-05 04:28:02 +00:00
echo -e " ${ green } Certificate issued successfully, installing... ${ plain } "
# Install certificate
# Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
# but the cert files are still installed. We check for files instead of exit code.
~/.acme.sh/acme.sh --installcert -d ${ ipv4 } \
--key-file " ${ certDir } /privkey.pem " \
--fullchain-file " ${ certDir } /fullchain.pem " \
--reloadcmd " ${ reloadCmd } " 2>& 1 || true
# Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
2025-12-27 23:03:33 +00:00
if [ [ ! -f " ${ certDir } /fullchain.pem " || ! -f " ${ certDir } /privkey.pem " ] ] ; then
2026-01-05 04:28:02 +00:00
echo -e " ${ red } Certificate files not found after installation ${ plain } "
# Cleanup acme.sh data for both IPv4 and IPv6 if specified
2026-05-04 11:20:24 +00:00
rm -rf ~/.acme.sh/${ ipv4 } 2> /dev/null
[ [ -n " $ipv6 " ] ] && rm -rf ~/.acme.sh/${ ipv6 } 2> /dev/null
rm -rf ${ certDir } 2> /dev/null
2025-12-27 23:03:33 +00:00
return 1
fi
2026-05-04 11:20:24 +00:00
2026-01-05 04:28:02 +00:00
echo -e " ${ green } Certificate files installed successfully ${ plain } "
# Enable auto-upgrade for acme.sh (ensures cron job runs)
2026-05-04 11:20:24 +00:00
~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>& 1
2026-01-05 04:28:02 +00:00
2026-05-19 11:09:35 +00:00
# Secure permissions: private key readable only by owner
2026-05-04 11:20:24 +00:00
chmod 600 ${ certDir } /privkey.pem 2> /dev/null
chmod 644 ${ certDir } /fullchain.pem 2> /dev/null
2026-01-05 04:28:02 +00:00
# Configure panel to use the certificate
echo -e " ${ green } Setting certificate paths for the panel... ${ plain } "
${ xui_folder } /x-ui cert -webCert " ${ certDir } /fullchain.pem " -webCertKey " ${ certDir } /privkey.pem "
2026-05-19 11:09:35 +00:00
2026-01-05 04:28:02 +00:00
if [ $? -ne 0 ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ yellow } Warning: Could not set certificate paths automatically ${ plain } "
echo -e " ${ yellow } Certificate files are at: ${ plain } "
echo -e " Cert: ${ certDir } /fullchain.pem "
echo -e " Key: ${ certDir } /privkey.pem "
2026-01-05 04:28:02 +00:00
else
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Certificate paths configured successfully ${ plain } "
2026-01-05 04:28:02 +00:00
fi
2025-12-27 23:03:33 +00:00
2026-01-05 04:28:02 +00:00
echo -e " ${ green } IP certificate installed and configured successfully! ${ plain } "
echo -e " ${ green } Certificate valid for ~6 days, auto-renews via acme.sh cron job. ${ plain } "
2026-05-19 11:09:35 +00:00
echo -e " ${ yellow } acme.sh will automatically renew and reload x-ui before expiry. ${ plain } "
2025-12-27 23:03:33 +00:00
return 0
}
# Comprehensive manual SSL certificate issuance via acme.sh
ssl_cert_issue( ) {
2026-01-03 02:57:19 +00:00
local existing_webBasePath = $( ${ xui_folder } /x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##' )
local existing_port = $( ${ xui_folder } /x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]' )
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
# check for acme.sh first
2026-05-04 11:20:24 +00:00
if ! command -v ~/.acme.sh/acme.sh & > /dev/null; then
2025-12-27 23:03:33 +00:00
echo "acme.sh could not be found. Installing now..."
cd ~ || return 1
curl -s https://get.acme.sh | sh
if [ $? -ne 0 ] ; then
echo -e " ${ red } Failed to install acme.sh ${ plain } "
return 1
else
echo -e " ${ green } acme.sh installed successfully ${ plain } "
fi
fi
# get the domain here, and we need to verify it
local domain = ""
while true; do
read -rp "Please enter your domain name: " domain
2026-05-04 11:20:24 +00:00
domain = " ${ domain // / } " # Trim whitespace
2025-12-27 23:03:33 +00:00
if [ [ -z " $domain " ] ] ; then
echo -e " ${ red } Domain name cannot be empty. Please try again. ${ plain } "
continue
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
if ! is_domain " $domain " ; then
echo -e " ${ red } Invalid domain format: ${ domain } . Please enter a valid domain name. ${ plain } "
continue
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
break
done
echo -e " ${ green } Your domain is: ${ domain } , checking it... ${ plain } "
2026-04-17 10:19:45 +00:00
SSL_ISSUED_DOMAIN = " ${ domain } "
# detect existing certificate and reuse it if present
local cert_exists = 0
2026-05-04 11:20:24 +00:00
if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq " ${ domain } " ; then
2026-04-17 10:19:45 +00:00
cert_exists = 1
2026-05-04 11:20:24 +00:00
local certInfo = $( ~/.acme.sh/acme.sh --list 2> /dev/null | grep -F " ${ domain } " )
2026-04-17 10:19:45 +00:00
echo -e " ${ yellow } Existing certificate found for ${ domain } , will reuse it. ${ plain } "
[ [ -n " ${ certInfo } " ] ] && echo " $certInfo "
2025-12-27 23:03:33 +00:00
else
echo -e " ${ green } Your domain is ready for issuing certificates now... ${ plain } "
fi
# create a directory for the certificate
certPath = " /root/cert/ ${ domain } "
if [ ! -d " $certPath " ] ; then
mkdir -p " $certPath "
else
rm -rf " $certPath "
mkdir -p " $certPath "
fi
# get the port number for the standalone server
local WebPort = 80
read -rp "Please choose which port to use (default is 80): " WebPort
if [ [ ${ WebPort } -gt 65535 || ${ WebPort } -lt 1 ] ] ; then
echo -e " ${ yellow } Your input ${ WebPort } is invalid, will use default port 80. ${ plain } "
WebPort = 80
fi
echo -e " ${ green } Will use port: ${ WebPort } to issue certificates. Please make sure this port is open. ${ plain } "
# Stop panel temporarily
echo -e " ${ yellow } Stopping panel temporarily... ${ plain } "
2026-05-04 11:20:24 +00:00
systemctl stop x-ui 2> /dev/null || rc-service x-ui stop 2> /dev/null
2025-12-27 23:03:33 +00:00
2026-04-17 10:19:45 +00:00
if [ [ ${ cert_exists } -eq 0 ] ] ; then
# issue the certificate
~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
~/.acme.sh/acme.sh --issue -d ${ domain } --listen-v6 --standalone --httpport ${ WebPort } --force
if [ $? -ne 0 ] ; then
echo -e " ${ red } Issuing certificate failed, please check logs. ${ plain } "
rm -rf ~/.acme.sh/${ domain }
2026-05-04 11:20:24 +00:00
systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
2026-04-17 10:19:45 +00:00
return 1
else
echo -e " ${ green } Issuing certificate succeeded, installing certificates... ${ plain } "
fi
2025-12-27 23:03:33 +00:00
else
2026-04-17 10:19:45 +00:00
echo -e " ${ green } Using existing certificate, installing certificates... ${ plain } "
2025-12-27 23:03:33 +00:00
fi
# Setup reload command
reloadCmd = "systemctl restart x-ui || rc-service x-ui restart"
echo -e " ${ green } Default --reloadcmd for ACME is: ${ yellow } systemctl restart x-ui || rc-service x-ui restart ${ plain } "
echo -e " ${ green } This command will run on every certificate issue and renew. ${ plain } "
read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
if [ [ " $setReloadcmd " = = "y" || " $setReloadcmd " = = "Y" ] ] ; then
echo -e " \n ${ green } \t1. ${ plain } Preset: systemctl reload nginx ; systemctl restart x-ui "
echo -e " ${ green } \t2. ${ plain } Input your own command "
echo -e " ${ green } \t0. ${ plain } Keep default reloadcmd "
read -rp "Choose an option: " choice
case " $choice " in
2026-05-04 11:20:24 +00:00
1)
echo -e " ${ green } Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui ${ plain } "
reloadCmd = "systemctl reload nginx ; systemctl restart x-ui"
; ;
2)
echo -e " ${ yellow } It's recommended to put x-ui restart at the end ${ plain } "
read -rp "Please enter your custom reloadcmd: " reloadCmd
echo -e " ${ green } Reloadcmd is: ${ reloadCmd } ${ plain } "
; ;
*)
echo -e " ${ green } Keeping default reloadcmd ${ plain } "
; ;
2025-12-27 23:03:33 +00:00
esac
fi
# install the certificate
2026-04-17 10:19:45 +00:00
local installOutput = ""
installOutput = $( ~/.acme.sh/acme.sh --installcert -d ${ domain } \
2025-12-27 23:03:33 +00:00
--key-file /root/cert/${ domain } /privkey.pem \
2026-04-17 10:19:45 +00:00
--fullchain-file /root/cert/${ domain } /fullchain.pem --reloadcmd " ${ reloadCmd } " 2>& 1)
local installRc = $?
echo " ${ installOutput } "
2025-12-27 23:03:33 +00:00
2026-04-17 10:19:45 +00:00
local installWroteFiles = 0
if echo " ${ installOutput } " | grep -q "Installing key to:" && echo " ${ installOutput } " | grep -q "Installing full chain to:" ; then
installWroteFiles = 1
fi
2026-05-04 11:20:24 +00:00
if [ [ -f " /root/cert/ ${ domain } /privkey.pem " && -f " /root/cert/ ${ domain } /fullchain.pem " && ( ${ installRc } -eq 0 || ${ installWroteFiles } -eq 1) ] ] ; then
2026-04-17 10:19:45 +00:00
echo -e " ${ green } Installing certificate succeeded, enabling auto renew... ${ plain } "
else
2025-12-27 23:03:33 +00:00
echo -e " ${ red } Installing certificate failed, exiting. ${ plain } "
2026-04-17 10:19:45 +00:00
if [ [ ${ cert_exists } -eq 0 ] ] ; then
rm -rf ~/.acme.sh/${ domain }
fi
2026-05-04 11:20:24 +00:00
systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
2025-12-27 23:03:33 +00:00
return 1
fi
# enable auto-renew
~/.acme.sh/acme.sh --upgrade --auto-upgrade
if [ $? -ne 0 ] ; then
echo -e " ${ yellow } Auto renew setup had issues, certificate details: ${ plain } "
ls -lah /root/cert/${ domain } /
2026-05-19 11:09:35 +00:00
# Secure permissions: private key readable only by owner
chmod 600 $certPath /privkey.pem 2> /dev/null
chmod 644 $certPath /fullchain.pem 2> /dev/null
2025-12-27 23:03:33 +00:00
else
echo -e " ${ green } Auto renew succeeded, certificate details: ${ plain } "
ls -lah /root/cert/${ domain } /
2026-05-19 11:09:35 +00:00
# Secure permissions: private key readable only by owner
chmod 600 $certPath /privkey.pem 2> /dev/null
chmod 644 $certPath /fullchain.pem 2> /dev/null
2025-12-27 23:03:33 +00:00
fi
2026-05-19 11:09:35 +00:00
# start panel
2026-05-04 11:20:24 +00:00
systemctl start x-ui 2> /dev/null || rc-service x-ui start 2> /dev/null
2025-12-27 23:03:33 +00:00
# Prompt user to set panel paths after successful certificate installation
read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
if [ [ " $setPanel " = = "y" || " $setPanel " = = "Y" ] ] ; then
local webCertFile = " /root/cert/ ${ domain } /fullchain.pem "
local webKeyFile = " /root/cert/ ${ domain } /privkey.pem "
if [ [ -f " $webCertFile " && -f " $webKeyFile " ] ] ; then
2026-01-03 02:57:19 +00:00
${ xui_folder } /x-ui cert -webCert " $webCertFile " -webCertKey " $webKeyFile "
2025-12-27 23:03:33 +00:00
echo -e " ${ green } Certificate paths set for the panel ${ plain } "
echo -e " ${ green } Certificate File: $webCertFile ${ plain } "
echo -e " ${ green } Private Key File: $webKeyFile ${ plain } "
echo ""
echo -e " ${ green } Access URL: https:// ${ domain } : ${ existing_port } / ${ existing_webBasePath } ${ plain } "
echo -e " ${ yellow } Panel will restart to apply SSL certificate... ${ plain } "
2026-05-04 11:20:24 +00:00
systemctl restart x-ui 2> /dev/null || rc-service x-ui restart 2> /dev/null
2025-12-27 23:03:33 +00:00
else
echo -e " ${ red } Error: Certificate or private key file not found for domain: $domain . ${ plain } "
fi
else
echo -e " ${ yellow } Skipping panel path setting. ${ plain } "
fi
2026-05-04 11:20:24 +00:00
2025-12-27 23:03:33 +00:00
return 0
}
2026-05-19 11:09:35 +00:00
# Reusable interactive SSL setup (domain or IP)
# Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
2025-12-27 23:03:33 +00:00
prompt_and_setup_ssl( ) {
local panel_port = " $1 "
2026-05-19 11:09:35 +00:00
local web_base_path = " $2 "
2025-12-27 23:03:33 +00:00
local server_ip = " $3 "
local ssl_choice = ""
2026-05-19 11:09:35 +00:00
SSL_SCHEME = "https"
2025-12-27 23:03:33 +00:00
echo -e " ${ yellow } Choose SSL certificate setup method: ${ plain } "
2026-01-05 04:28:02 +00:00
echo -e " ${ green } 1. ${ plain } Let's Encrypt for Domain (90-day validity, auto-renews) "
echo -e " ${ green } 2. ${ plain } Let's Encrypt for IP Address (6-day validity, auto-renews) "
2026-01-21 15:47:36 +00:00
echo -e " ${ green } 3. ${ plain } Custom SSL Certificate (Path to existing files) "
2026-05-19 11:09:35 +00:00
echo -e " ${ green } 4. ${ plain } Skip SSL (advanced — behind reverse proxy / SSH tunnel only) "
2026-01-21 15:47:36 +00:00
echo -e " ${ blue } Note: ${ plain } Options 1 & 2 require port 80 open. Option 3 requires manual paths. "
2026-05-19 11:09:35 +00:00
echo -e " ${ blue } Note: ${ plain } Option 4 serves the panel over plain HTTP — only safe behind nginx/Caddy or an SSH tunnel. "
2026-01-05 04:28:02 +00:00
read -rp "Choose an option (default 2 for IP): " ssl_choice
2026-05-04 11:20:24 +00:00
ssl_choice = " ${ ssl_choice // / } " # Trim whitespace
2026-05-19 11:09:35 +00:00
# Default to 2 (IP cert) if input is empty or invalid (not 1, 3 or 4)
if [ [ " $ssl_choice " != "1" && " $ssl_choice " != "3" && " $ssl_choice " != "4" ] ] ; then
2025-12-27 23:03:33 +00:00
ssl_choice = "2"
fi
case " $ssl_choice " in
2026-05-04 11:20:24 +00:00
1)
# User chose Let's Encrypt domain option
echo -e " ${ green } Using Let's Encrypt for domain certificate... ${ plain } "
if ssl_cert_issue; then
local cert_domain = " ${ SSL_ISSUED_DOMAIN } "
if [ [ -z " ${ cert_domain } " ] ] ; then
cert_domain = $( ~/.acme.sh/acme.sh --list 2> /dev/null | tail -1 | awk '{print $1}' )
fi
if [ [ -n " ${ cert_domain } " ] ] ; then
SSL_HOST = " ${ cert_domain } "
echo -e " ${ green } ✓ SSL certificate configured successfully with domain: ${ cert_domain } ${ plain } "
else
echo -e " ${ yellow } SSL setup may have completed, but domain extraction failed ${ plain } "
SSL_HOST = " ${ server_ip } "
fi
else
echo -e " ${ red } SSL certificate setup failed for domain mode. ${ plain } "
SSL_HOST = " ${ server_ip } "
2026-04-17 10:19:45 +00:00
fi
2026-05-04 11:20:24 +00:00
; ;
2)
# User chose Let's Encrypt IP certificate option
echo -e " ${ green } Using Let's Encrypt for IP certificate (shortlived profile)... ${ plain } "
# Ask for optional IPv6
local ipv6_addr = ""
read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
ipv6_addr = " ${ ipv6_addr // / } " # Trim whitespace
2026-04-17 10:19:45 +00:00
2026-05-04 11:20:24 +00:00
# Stop panel if running (port 80 needed)
if [ [ $release = = "alpine" ] ] ; then
rc-service x-ui stop > /dev/null 2>& 1
2026-04-17 10:19:45 +00:00
else
2026-05-04 11:20:24 +00:00
systemctl stop x-ui > /dev/null 2>& 1
2026-04-17 10:19:45 +00:00
fi
2026-05-04 11:20:24 +00:00
setup_ip_certificate " ${ server_ip } " " ${ ipv6_addr } "
if [ $? -eq 0 ] ; then
SSL_HOST = " ${ server_ip } "
echo -e " ${ green } ✓ Let's Encrypt IP certificate configured successfully ${ plain } "
2026-01-21 15:47:36 +00:00
else
2026-05-04 11:20:24 +00:00
echo -e " ${ red } ✗ IP certificate setup failed. Please check port 80 is open. ${ plain } "
SSL_HOST = " ${ server_ip } "
2026-01-21 15:47:36 +00:00
fi
2026-05-04 11:20:24 +00:00
; ;
3)
# User chose Custom Paths (User Provided) option
echo -e " ${ green } Using custom existing certificate... ${ plain } "
local custom_cert = ""
local custom_key = ""
local custom_domain = ""
# 3.1 Request Domain to compose Panel URL later
read -rp "Please enter domain name certificate issued for: " custom_domain
custom_domain = " ${ custom_domain // / } " # Remove spaces
# 3.2 Loop for Certificate Path
while true; do
read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
# Strip quotes if present
custom_cert = $( echo " $custom_cert " | tr -d '"' | tr -d "'" )
if [ [ -f " $custom_cert " && -r " $custom_cert " && -s " $custom_cert " ] ] ; then
break
elif [ [ ! -f " $custom_cert " ] ] ; then
echo -e " ${ red } Error: File does not exist! Try again. ${ plain } "
elif [ [ ! -r " $custom_cert " ] ] ; then
echo -e " ${ red } Error: File exists but is not readable (check permissions)! ${ plain } "
else
echo -e " ${ red } Error: File is empty! ${ plain } "
fi
done
# 3.3 Loop for Private Key Path
while true; do
read -rp "Input private key path (keywords: .key / privatekey): " custom_key
# Strip quotes if present
custom_key = $( echo " $custom_key " | tr -d '"' | tr -d "'" )
if [ [ -f " $custom_key " && -r " $custom_key " && -s " $custom_key " ] ] ; then
break
elif [ [ ! -f " $custom_key " ] ] ; then
echo -e " ${ red } Error: File does not exist! Try again. ${ plain } "
elif [ [ ! -r " $custom_key " ] ] ; then
echo -e " ${ red } Error: File exists but is not readable (check permissions)! ${ plain } "
else
echo -e " ${ red } Error: File is empty! ${ plain } "
fi
done
# 3.4 Apply Settings via x-ui binary
${ xui_folder } /x-ui cert -webCert " $custom_cert " -webCertKey " $custom_key " > /dev/null 2>& 1
# Set SSL_HOST for composing Panel URL
if [ [ -n " $custom_domain " ] ] ; then
SSL_HOST = " $custom_domain "
2026-01-21 15:47:36 +00:00
else
2026-05-04 11:20:24 +00:00
SSL_HOST = " ${ server_ip } "
2026-01-21 15:47:36 +00:00
fi
2026-05-04 11:20:24 +00:00
echo -e " ${ green } ✓ Custom certificate paths applied. ${ plain } "
echo -e " ${ yellow } Note: You are responsible for renewing these files externally. ${ plain } "
2026-01-21 15:47:36 +00:00
2026-05-04 11:20:24 +00:00
systemctl restart x-ui > /dev/null 2>& 1 || rc-service x-ui restart > /dev/null 2>& 1
; ;
2026-05-19 11:09:35 +00:00
4)
echo ""
echo -e " ${ red } ⚠ Panel will be installed WITHOUT SSL/TLS. ${ plain } "
echo -e " ${ yellow } Login credentials and cookies will travel as plain HTTP. ${ plain } "
echo -e " ${ yellow } Only safe when: ${ plain } "
echo -e " ${ yellow } • A reverse proxy (nginx, Caddy, Traefik) terminates TLS for you, or ${ plain } "
echo -e " ${ yellow } • You access the panel exclusively via SSH tunnel ${ plain } "
echo ""
SSL_SCHEME = "http"
SSL_HOST = " ${ server_ip } "
local bind_local = ""
read -rp "Bind the panel to 127.0.0.1 only? (recommended — forces SSH tunnel / reverse-proxy access) [y/N]: " bind_local
if [ [ " $bind_local " = = "y" || " $bind_local " = = "Y" ] ] ; then
${ xui_folder } /x-ui setting -listenIP "127.0.0.1" > /dev/null 2>& 1
SSL_HOST = "127.0.0.1"
echo -e " ${ green } ✓ Panel bound to 127.0.0.1 only. It is now unreachable from the public internet. ${ plain } "
echo ""
echo -e " ${ green } SSH Port Forwarding — open the panel from your local machine via: ${ plain } "
echo -e " Standard SSH command:"
echo -e " ${ yellow } ssh -L 2222:127.0.0.1: ${ panel_port } root@ ${ server_ip } ${ plain } "
echo -e " If using an SSH key:"
echo -e " ${ yellow } ssh -i <sshkeypath> -L 2222:127.0.0.1: ${ panel_port } root@ ${ server_ip } ${ plain } "
echo -e " Then open in your browser:"
echo -e " ${ yellow } http://localhost:2222/ ${ web_base_path } ${ plain } "
echo ""
echo -e " ${ yellow } Alternative: point a reverse proxy (nginx/Caddy) at 127.0.0.1: ${ panel_port } and let it terminate TLS. ${ plain } "
else
echo -e " ${ yellow } Panel will listen on all interfaces over plain HTTP. Make sure something else is terminating TLS in front of it. ${ plain } "
fi
systemctl restart x-ui > /dev/null 2>& 1 || rc-service x-ui restart > /dev/null 2>& 1
echo -e " ${ green } ✓ SSL setup skipped. ${ plain } "
; ;
2026-05-04 11:20:24 +00:00
*)
echo -e " ${ red } Invalid option. Skipping SSL setup. ${ plain } "
SSL_HOST = " ${ server_ip } "
; ;
2025-12-27 23:03:33 +00:00
esac
}
2026-05-19 11:09:35 +00:00
config_after_install( ) {
local existing_hasDefaultCredential = $( ${ xui_folder } /x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}' )
Feat/multi inbound clients (#4469)
* feat(clients): add shadow tables for first-class client promotion
Introduces three new GORM-backed tables (clients, client_inbounds,
inbound_fallback_children) and a populate-only seeder that backfills
them from each inbound's existing settings.clients JSON. Duplicate
emails across inbounds auto-merge under one client row, with each
field conflict logged. Existing services are unchanged and continue
reading from settings.clients — this commit is groundwork only.
* feat(clients): make clients+client_inbounds the runtime source of truth
Adds ClientService.SyncInbound that reconciles the new tables from
each inbound's clients list whenever existing service paths mutate
settings.clients. Wires it into AddInbound, UpdateInbound,
AddInboundClient, UpdateInboundClient, DelInboundClient,
DelInboundClientByEmail, DelDepletedClients, autoRenewClients, and
the timestamp-backfill path in adjustTraffics, plus DetachInbound
on DelInbound.
GetXrayConfig now builds settings.clients from the new tables before
writing config.json, and getInboundsBySubId joins through them
instead of JSON_EACH on settings JSON. Live Xray config and
subscription endpoints are now driven by the relational view;
settings.clients JSON stays in step as a side effect of every write.
* feat(clients): add top-level Clients tab and CRUD API
Adds /panel/api/clients endpoints (list, get, add, update, del,
attach, detach) backed by ClientService methods that orchestrate
the per-inbound Add/Update/Del flows so a single client row is
created once and attached to many inbounds in one operation.
The frontend gains a dedicated Clients page (frontend/clients.html
+ src/pages/clients/) with an AntD table, multi-inbound attach
modal, and full CRUD. Axios interceptor learns to honour
Content-Type: application/json so the JSON endpoints work
alongside the legacy form-encoded ones.
The legacy per-inbound client modal stays untouched in this PR —
both flows now write to the same source of truth.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds): add Port-with-Fallback inbound type
Adds a new "portfallback" protocol that emits as a VLESS-TLS inbound
under the hood but is paired with a sidecar table of child inbounds.
Panel auto-builds settings.fallbacks at Xray-config-gen time from the
sidecar — each child's listen+port becomes the fallback dest, with
SNI/ALPN/path/xver match criteria pulled from the row. No more typing
loopback ports by hand or keeping settings.fallbacks in sync.
Backend: new FallbackService (Get/SetChildren, BuildFallbacksJSON);
two new routes (GET/POST /panel/api/inbounds/:id/fallbackChildren);
xray.GetXrayConfig injects fallbacks for PortFallback inbounds; the
inbound model emits protocol="vless" so Xray accepts the config.
Frontend: PORTFALLBACK joins the protocol dropdown; selecting it
shows the standard VLESS controls plus a Fallback Children table
(inbound picker + per-row SNI/ALPN/path/xver). Children are loaded
on edit and replaced atomically on save.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Reset Traffic, QR Code, Info actions + Online/Remaining columns
The Clients page table gains:
- Online column — green/grey tag driven by /panel/api/inbounds/onlines,
polled every 10s.
- Remaining column — bytes-remaining tag, coloured green/orange/red
against quota, purple infinity when unlimited.
- Action icons per row: QR, Info, Reset traffic, Edit, Delete.
ClientInfoModal shows the full client detail (uuid/password/auth,
traffic ↑/↓ + remaining + all-time, expiry absolute + relative,
attached inbounds chip list, online + last-online).
ClientQrModal fetches links for the client's subId via
/panel/api/inbounds/getSubLinks/:subId and renders each one through
the existing QrPanel component.
Reset Traffic confirms then calls the existing per-inbound endpoint
on the client's first attached inbound (the traffic row is keyed on
email globally, so any attached inbound resets the shared counter).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): expose Attached inbounds in edit mode
The multi-select was gated on add-only, so editing a client had no way
to change which inbounds it belonged to. The picker now shows in both
modes, and on submit the modal diffs the picked set against the
original attachedIds — additions go through the /attach endpoint,
removals through /detach, both after the field update lands so the
new attachments get the latest values.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): unbreak template parsing + stale i18n keys
- InboundFormModal: split the multi-line help string in the
PortFallback section onto one line — Vue's template parser was
bailing on Unterminated string constant because a single-quoted
literal spanned two lines inside a {{ }} interpolation.
- ClientInfoModal: t('disable') was missing at the root level, so
vue-i18n returned the key path literally. Use t('disabled') which
exists.
- Linter cleanup elsewhere: pages.client.* references renamed to
pages.clients.* to match the merged i18n block; whitespace
normalisation in a few unrelated Vue templates.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* 1
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(traffic): drop all-time traffic tracking
Removes the AllTime field from Inbound and ClientTraffic and migrates
existing DBs by dropping the all_time columns on startup. The counter
duplicated up+down without adding signal, and the per-event accumulator
ran on every traffic write.
Frontend: drop the All-time column from the inbound list and the
client-row table, the All-time row from the client info modal, and the
All-Time Total Usage tile from the inbounds summary card. The
allTimeTraffic/allTimeTrafficUsage i18n keys are removed across every
locale.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): mobile cards, multi-select, bulk add
Adds the same row-card layout the inbounds page uses on mobile: the
table is suppressed under the mobile breakpoint and each client renders
as a compact card with a status dot, email, Info button, Enable switch,
and overflow menu. All the per-client detail (traffic, remaining,
expiry, attached inbounds, flow, created/updated, URL, subscription)
opens through the existing info modal.
Multi-select with bulk delete wires AntD row-selection on desktop and
a per-card checkbox on mobile; a Delete (N) button appears in the
toolbar when anything is selected.
Bulk add reuses the five email-generation modes from the inbound bulk
modal but takes a multi-inbound picker so one bulk run can attach to
several inbounds at once. Submits client-by-client through the
existing /panel/api/clients/add endpoint.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(inbounds): remove legacy per-inbound client UI
Now that clients live as first-class rows attached to one or many
inbounds, the per-inbound client UI on the inbounds page is dead
weight — every client action either has a global equivalent on the
Clients page or makes no sense in a many-to-many world.
Deletes ClientFormModal, ClientBulkModal, CopyClientsModal, and
ClientRowTable from inbounds/. Strips the matching emits, refs,
handlers, and dropdown menu items from InboundList and InboundsPage,
and removes the dead mobile expand-chevron state and the desktop
expanded-row plumbing that drove the inline client table.
The InboundFormModal Clients tab still works in add-mode (one inline
client at inbound creation) — that flow goes through ClientService.
SyncInbound on save and remains useful.
Fixes a stray "</a-dropdown>" left over by an earlier toolbar edit
in ClientsPage that broke the template parser.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Delete depleted action
Mirrors the legacy delDepletedClients action that lived under the
inbounds page, but as a first-class /panel/api/clients/delDepleted
endpoint backed by ClientService. The new path goes through
ClientService.Delete for each depleted email, so the new clients +
client_inbounds + xray_client_traffic tables stay consistent.
Adds a danger-styled toolbar button on the Clients page (next to
Reset all client traffic) with a confirm dialog and a toast
reporting the deleted count.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(api): move every client-shaped endpoint off /inbounds onto /clients
After the multi-inbound client migration, client state belongs to the
client API surface, not the inbound one. Twelve routes that were
crammed under /panel/api/inbounds/* now live where they belong, under
/panel/api/clients/*.
Moved (route, handler, doc):
POST /clientIps/:email
POST /clearClientIps/:email
POST /onlines
POST /lastOnline
POST /updateClientTraffic/:email
POST /resetAllClientTraffics/:id
POST /delDepletedClients/:id
POST /:id/resetClientTraffic/:email
GET /getClientTraffics/:email
GET /getClientTrafficsById/:id
GET /getSubLinks/:subId
GET /getClientLinks/:id/:email
Their /clients/* counterparts are:
POST /clients/clientIps/:email
POST /clients/clearClientIps/:email
POST /clients/onlines
POST /clients/lastOnline
POST /clients/updateTraffic/:email
POST /clients/resetTraffic/:email (email-only, fans out)
GET /clients/traffic/:email
GET /clients/traffic/byId/:id
GET /clients/subLinks/:subId
GET /clients/links/:id/:email
per-inbound resetAllClientTraffics and delDepletedClients are dropped
entirely — the Clients page already exposes global Reset All Traffic
and Delete depleted actions, and per-inbound resets are meaningless
once a client can be attached to many inbounds.
ClientService.ResetTrafficByEmail is the new email-only reset path:
it looks up every inbound the client is attached to and pushes the
counter reset + Xray re-add through inboundService.ResetClientTraffic
for each one, so depleted users come back online instantly.
Frontend callers (ClientsPage, useClients, ClientQrModal,
ClientInfoModal, InboundInfoModal, InboundsPage, useInbounds) all
switched to the new paths. The Inbounds page drops its per-inbound
"Reset client traffic" and "Delete depleted clients" dropdown items —
users do those at the client level now. api-docs is rebuilt to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(service): switch tgbot + ldap callers to ClientService
Adds two thin helpers to ClientService (CreateOne, DetachByEmail) and
rewrites tgbot.SubmitAddClient and ldap_sync_job to call ClientService
directly. Removes the JSON-blob payloads (BuildJSONForProtocol output for
add, clientsToJSON/clientToJSON helpers) that callers previously fed to
InboundService.AddInboundClient/DelInboundClient.
ldap_sync_job.batchSetEnable now loops InboundService.SetClientEnableByEmail
per email instead of trying to coerce AddInboundClient into doing the
update — the old path would have failed duplicate-email validation for
existing clients anyway.
The legacy InboundService.AddInboundClient/UpdateInboundClient/
DelInboundClient methods stay in place; they are now only used internally
by ClientService Create/Update/Delete/Attach. Inlining + deleting them
follows in a separate commit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(service): move all client mutation methods to ClientService
Moves the client mutation surface out of InboundService and into
ClientService. These methods all operate on a single client (identity
fields, traffic limits, expiry, ip limit, enable state, telegram tg id)
and didn't belong on the inbound aggregate.
Moved (12 methods): AddInboundClient, UpdateInboundClient, DelInboundClient,
DelInboundClientByEmail, checkEmailsExistForClients, SetClientTelegramUserID,
checkIsEnabledByEmail, ToggleClientEnableByEmail, SetClientEnableByEmail,
ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail,
ResetClientTrafficLimitByEmail.
Each method now takes an explicit *InboundService for the helpers that
legitimately stay on InboundService (GetInbound, GetClients, runtimeFor,
AddClientStat / UpdateClientStat / DelClientStat, DelClientIPs /
UpdateClientIPs, emailUsedByOtherInbounds, getAllEmailSubIDs,
GetClientInboundByEmail / GetClientInboundByTrafficID,
GetClientTrafficByEmail).
Stays on InboundService: ResetClientTrafficByEmail and
ResetClientTraffic(id, email) — these mutate xray_client_traffic rows,
not client identity, so they're inbound-side bookkeeping.
Callers updated: tgbot (6 calls), ldap_sync_job (1 call),
InboundService internal (writeBackClientSubID, CopyInboundClients,
AddInbound's email-uniqueness check), ClientService Create/Update/
Delete/Attach/Detach.
Also removes a dead resetAllClientTraffics controller handler whose
route was already gone after the previous /clients API migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(clients): finish migrating to ClientService + tidy IP routes
Two related cleanups in the new /clients surface:
1. Move ResetAllClientTraffics (bulk-reset of xray_client_traffic +
last_traffic_reset_time, with node-runtime propagation) from
InboundService to ClientService. PeriodicTrafficResetJob now holds
a clientService and calls
j.clientService.ResetAllClientTraffics(&j.inboundService, id).
The last client-mutation method on InboundService is gone.
2. Shorten redundantly-named routes/handlers under /panel/api/clients:
- /clientIps/:email -> /ips/:email (handler getIps)
- /clearClientIps/:email -> /clearIps/:email (handler clearIps)
The "client" prefix was redundant inside the clients namespace.
Frontend (InboundInfoModal) and api-docs updated to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds,clients): clean up inbound modal + enrich client modal
Inbound modal rework (InboundFormModal.vue + inbound.js):
- Drop the embedded Client subform in the Protocol tab. Multi-inbound
clients are managed exclusively from the Clients page now; a fresh
inbound is created with zero clients (settings constructors default
to []) and the user attaches clients afterwards.
- Hide the Protocol tab entirely when it has nothing to render
(VMESS, Trojan without fallbacks, Hysteria). Auto-switches active
tab to Basic when the tab disappears while focused.
- Move the Security section (Security selector + TLS block with certs
and ECH + Reality block) out of the Stream tab into its own
Security tab, sharing the canEnableStream gate.
Client modal additions (ClientFormModal.vue + ClientBulkAddModal.vue):
- Flow select (xtls-rprx-vision / -udp443) appears only when the
panel actually has a Vision-capable inbound (VLESS or PortFallback
on TCP with TLS or Reality). Hidden otherwise, and cleared when
it disappears.
- IP Limit input is disabled when the panel-level ipLimitEnable
setting is off, fetched into useClients alongside subSettings and
threaded through ClientsPage to both modals.
- Edit modal now shows an "IP Log" section listing IPs that have
connected with the client's credentials, with refresh and clear
buttons (calls the renamed /panel/api/clients/ips and /clearIps
endpoints).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(inbounds): drop manual Fallbacks UI from inbound modal
The PortFallback protocol type now covers the common
VLESS-master-plus-children case with auto-wired dests, so the manual
Fallbacks editor (showFallbacks block in the Protocol tab) is mostly
redundant. Removed:
- the v-if="showFallbacks" template block (SNI/ALPN/Path/dest/PROXY rows)
- the showFallbacks computed
- the addFallback / delFallback helpers
- the .fallbacks-header / .fallbacks-title styles
- the showFallbacks gate from hasProtocolTabContent (so Trojan-over-TCP
no longer shows an empty Protocol tab)
Power users who need a non-inbound fallback dest (nginx, static site)
can still author settings.fallbacks via the Advanced JSON tab.
* feat(clients,inbounds): move search/filter to Clients page + small fixes
Search/filter relocation:
- Remove the search/filter toolbar (search switch + filter radio +
protocol/node selects + the visibleInbounds projection +
inboundsFilterState localStorage + filter CSS + the SearchOutlined/
FilterOutlined/ObjectUtil/Inbound imports it required) from
InboundList. The filters were all client-oriented buckets bolted
onto the inbound row.
- Add a search/filter toolbar to ClientsPage with the same shape:
switch between deep-text search and bucket filter (active /
deactive / depleted / expiring / online) + protocol filter that
matches clients attached to at least one inbound with the chosen
protocol. State persists in clientsFilterState localStorage.
filteredClients drives both the desktop table and the mobile card
list, and select-all / allSelected / someSelected only span the
visible subset.
- useClients now also fetches expireDiff and trafficDiff from
/panel/setting/defaultSettings (used to detect the expiring
bucket); ClientsPage threads them into the client-bucket helper.
Loose fixes folded in:
- Add Client: email field is auto-filled with a random handle on
open, matching uuid/subId/password/auth.
- Inbound clone: parse and reuse the source settings JSON (with
clients reset to []) instead of building a fresh defaulted
Settings, so VLESS Encryption/Decryption and other non-client
fields survive the clone.
- en-US.json: add the ipLog string used by the edit-client modal.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Reverse tag field for VLESS-attached clients
Mirrors the Flow field's pattern: a Reverse tag input appears in the
Add/Edit Client modal whenever at least one selected inbound is VLESS
or PortFallback. The value rides over the wire as
client.reverse = { tag: '...' } so it lands directly in model.Client's
*ClientReverse field; an empty value omits the reverse key entirely.
On edit the field is hydrated from props.client.reverse?.tag, and the
showReverseTag watcher clears the field if the user drops the last
VLESS-like inbound from the selection.
* fix(xray): emit only protocol-relevant fields per client entry
The Xray config synthesizer was writing every identifier field (id,
password, flow, auth, security/method, reverse) on every client entry
regardless of the inbound's protocol. Xray ignores unknown fields, so
the config worked, but it diverged from the spec and leaked secrets
across protocols when one client was attached to multiple inbounds —
a VLESS inbound's generated config carried the same client's Trojan
password and Hysteria auth alongside its uuid.
Switch on inbound.Protocol when building each entry:
- VLESS / PortFallback: id, flow, reverse
- VMess: id, security
- Trojan: password, flow
- Shadowsocks: password, method
- Hysteria / Hysteria2: auth
email is emitted for every protocol.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): restore auto-disable kick under new schema
disableInvalidClients still resolved (inbound_tag, email) pairs via
JSON_EACH(inbounds.settings.clients), which is empty after migrating
to the clients + client_inbounds tables. Result: xrayApi.RemoveUser
never ran for depleted clients, clients.enable stayed true so the UI
showed them as active, and only xray_client_traffic.enable got flipped
- making "Restart Xray After Auto Disable" only half-work.
Resolve the targets via a JOIN through the new schema, flip clients.enable
so the Clients page reflects the state, and drop the legacy JSON
write-back plus the subId cascade workaround (email is unique now).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): live WebSocket updates + Ended status surfacing
ClientsPage now subscribes to traffic / client_stats / invalidate
WebSocket events instead of polling /onlines every 10s. Per-row
traffic counters refresh in place, online state stays current, and
list-level mutations elsewhere trigger a refresh.
The client roll-up summary moves from InboundsPage to ClientsPage
where it belongs, restructured into six labeled stat tiles
(Total / Online / Ended / Expiring / Disabled / Active) with email
popovers on the ones with issues.
Auto-disabled clients (traffic exhausted or expiry passed) now
classify as 'depleted' even though clients.enable=false, so they
show up under the Ended filter and render a red Ended tag instead
of looking indistinguishable from an operator-disabled row.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(nodes): per-node client roll-up and panel version
Added transient inboundCount / clientCount / onlineCount /
depletedCount fields to model.Node, populated by NodeService.GetAll
via aggregated queries (one join across inbounds + client_inbounds,
one over client_traffics intersected with the in-memory online
emails). The Nodes list renders these as colored chips on a new
"Clients" column so an operator can see at a glance how many users
each node carries and how many are currently online or depleted.
Also exposes the remote panel's version. The central panel adds
panelVersion to its /api/server/status payload (sourced from
config.GetVersion). Probe reads that field and persists it on the
node row, mirroring how xrayVersion already flows. NodesPage gets
a new column next to Xray Version, in both desktop and mobile
views, with English and Persian strings.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): stop node sync from resurrecting deleted clients
Several related issues around node-managed clients:
- Remote runtime: drop the per-inbound resetAllClientTraffics path
and point traffic/onlines/lastOnline fetches at the new
/panel/api/clients/* routes.
- Delete from master: always push the updated inbound to the node
even when the client was already disabled or depleted, so the
node actually loses the user instead of silently keeping it.
- setRemoteTraffic: mirror remote clients into the central tables
only on first discovery of a node inbound. Matched inbounds let
the master own the join table, so a stale snap can no longer
re-create a ClientRecord (and join row) for a client that was
just deleted on the master.
- ClientService.Delete: route through submitTrafficWrite so deletes
serialize with node traffic merges, and switch the final
ClientRecord delete to an explicit Where("id = ?") clause.
- setRemoteTraffic UNIQUE-constraint fix: use clause.OnConflict on
inserts and email-keyed UPDATEs for client_traffics, so mirroring
a snap doesn't trip the unique email index.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(clients): switch client API endpoints from id to email
All client-scoped routes now use the unique email as the path key
(get, update, del, attach, detach, links). Email is the stable,
protocol-independent identifier — UUIDs don't exist for trojan or
shadowsocks, and internal numeric ids leaked panel implementation
detail into the public API.
Removed the redundant /traffic/byId/:id endpoint (covered by
/traffic/:email) and collapsed /links/:id/:email into /links/:email,
which now returns links across every attached inbound for the client.
Frontend selection, bulk delete, and toggle state are now keyed by
email as well, dropping the id→email lookup workaround.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(server): move cached state and helpers into ServerService
ServerController had grown to hold its own status cache, version-list
TTL cache, history-bucket whitelist, and the loop that drove all three
— concerns that belong in the service layer. Pull them out:
- lastStatus + the @2s refresh become ServerService.RefreshStatus and
ServerService.LastStatus; the controller's cron now just orchestrates
the cross-service side effects (xrayMetrics sample, websocket broadcast).
- The 15-minute Xray-versions cache (with stale-on-error fallback) moves
into ServerService.GetXrayVersionsCached, collapsing the controller
handler to a single call.
- The freedom/blackhole outbound-tag walk used by /xraylogs becomes
ServerService.GetDefaultLogOutboundTags.
- The allowed-history-bucket whitelist moves to package-level
service.IsAllowedHistoryBucket, so both NodeController and
ServerController validate against the same list.
Net result: web/controller/server.go drops from 458 to 365 lines and
contains only HTTP wiring + presentation-y side effects.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(api): emit JSON-text columns as nested objects
Inbound, ClientRecord, and InboundClientIps store settings /
streamSettings / sniffing / reverse / ips as JSON-text in the DB. The
API was passing that text through verbatim, so every consumer had to
JSON.parse a string inside a string. Add MarshalJSON / UnmarshalJSON so
the wire format is a real nested object, while still accepting the
legacy escaped-string shape on write. Frontend dbinbound.js gets a
matching coerceInboundJsonField helper for the same dual-shape read
path, and inbound.js toJson stops emitting empty/placeholder fields
(externalProxy [], sniffing destOverride when disabled, etc.) so the
new normalised JSON stays terse. api-docs and the inbound-clone path
are updated to the new shape. Controller route lists are regrouped so
all GETs sit above POSTs.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): include inboundIds and traffic in /clients/list
ClientRecord got its own MarshalJSON in the previous commit, and
ClientWithAttachments embeds it to add inboundIds and traffic. Go
promotes the embedded MarshalJSON to the outer struct, so the encoder
was calling ClientRecord.MarshalJSON for the whole value and silently
dropping the extras. The frontend reads row.inboundIds / row.traffic
from /clients/list, so attached inbounds didn't render and newly added
clients looked like they hadn't saved. Add an explicit MarshalJSON on
ClientWithAttachments that splices the extras in.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): gate IP Log on ipLimitEnable + clean access-log dropdown
Legacy panel hid the IP Log section when access logging was off; the
Vue 3 migration left it gated on isEdit only, so the section showed
even when xray's access log was 'none' and nothing was being recorded.
Restore the ipLimitEnable gate on the edit modal's IP Log form-item.
While here, clean up the Xray Settings access-log dropdown: previously
two 'none' entries appeared (an empty value labelled with t('none') and
the literal 'none' from the options array). Drop the empty option for
access log (the literal 'none' covers it) and relabel the empty option
for error log / mask address to t('empty') so they're distinguishable.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(nodes): route per-client ops through node clients API + orphan sweep
Adds Runtime methods AddClient, UpdateUser, and DeleteUser so master
mutates clients on a node via /panel/api/clients/{add,update,del} rather
than pushing the whole inbound. The previous rt.UpdateInbound path made
the node DelInbound+AddInbound on every single-client change, briefly
cycling every other user on the same inbound.
DelInbound no longer filters by enable=true, so a disabled node inbound
actually gets removed from the node instead of being resurrected by the
next snap.
setRemoteTrafficLocked now sweeps any ClientRecord with zero
ClientInbound rows after SyncInbound rebuilds the attachments, which is
how a node-side delete propagates back to master instead of leaving a
detached ghost. ClientService.Delete tombstones the email first so a
snap arriving mid-delete can't re-create the record.
WebSocket broadcasts an "invalidate(clients)" message on every client
mutation so the Clients page refreshes without manual reload.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(balancers): allow fallback on all strategies + feed burstObservatory from random/roundRobin
Drops the random/roundRobin gate on the Fallback field in
BalancerFormModal so every strategy can pick a fallback outbound.
syncObservatories now feeds burstObservatory from leastLoad +
random + roundRobin balancers (was leastLoad only), matching how
leastPing feeds observatory.
Fix the JsonEditor "Unexpected end of JSON input" that appeared
when switching a balancer between leastPing and another strategy:
the obsView watcher was gated on showObsEditor (a boolean OR of
the two flags) and missed the case where one observatory
swapped for the other in the same tick. Watch the individual
flags instead so obsView flips to the surviving editor and the
getter stops pointing at a deleted key.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(inbounds): use sortedInbounds for mobile empty-state check
InboundList referenced an undefined visibleInbounds in the mobile
card list's empty-state guard, throwing "Cannot read properties of
undefined (reading 'length')" and breaking the entire mobile render.
* feat(clients): sortable table columns
Adds the same sortState / sortableCol / sortFns pattern InboundList
uses, wrapping filteredClients in sortedClients so sort composes with
the existing search/filter pipeline. Sortable: enable, email,
inboundIds (attachment count), traffic, remaining, expiryTime;
actions and online stay unsorted.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(shadowsocks): generate valid ss2022 keys and per-client method for legacy ciphers
The Add Client flow on shadowsocks inbounds was producing xray configs
that failed to start:
- 2022-blake3-* ciphers need a base64-encoded key of an exact byte
length per cipher. fillProtocolDefaults was assigning a uuid-style
string, which xray rejects as "bad key". Now the password is
generated (or replaced if invalid) via random.Base64Bytes(n) sized
to the chosen cipher.
- Legacy ciphers (aes-256-gcm, chacha20-*, xchacha20-*) require a
per-client method field in multi-user mode; model.Client has no
Method, so settings.clients was stored without one and xray failed
with "unsupported cipher method:". applyShadowsocksClientMethod
now injects the top-level method into each client on add/update,
and healShadowsocksClientMethods backfills it at xray-config-build
time so existing inbounds heal on the next start.
- xray/api.go ssCipherType switch was missing aes-256-gcm, which
fell through to ss2022 path.
- SSMethods dropdown now offers aes-256-gcm.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): preserve ClientRecord on inbound delete + filter Attached inbounds to multi-client protocols
Replace the global orphan sweep in setRemoteTrafficLocked with a
per-inbound diff cleanup: only delete a ClientRecord whose email
disappeared from a snap-tracked inbound (i.e. a node-side delete).
Inbounds that vanished entirely from the snap (e.g. admin deleted
the inbound on master) aren't iterated, so a client whose last
attachment came from that inbound is now left alone instead of
being deleted alongside the inbound.
ClientFormModal and ClientBulkAddModal now filter the Attached
inbounds dropdown to protocols that actually support multiple
clients: shadowsocks, vless, vmess, trojan, hysteria, hysteria2,
and portfallback (which routes through VLESS settings).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): make empty-state text readable on dark/ultra themes
The "No clients yet" empty state had a hardcoded black color
(rgba(0,0,0,0.45)) that vanished against the dark backgrounds.
Drop the inline color, let it inherit from the AntD theme, and
fade with opacity like the mobile card empty state already does.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): client-first tgbot add flow, tgId field, lightweight inbound options
- tgbot: drop legacy per-protocol Add Client UI in favour of a client-first
multi-inbound flow. New BuildClientDraftMessage / getInboundsAttachPicker
let an admin pick one or more inbounds and submit a single client; per-
protocol secrets are now generated server-side via fillProtocolDefaults.
Drops awaiting_id/awaiting_password_tr/awaiting_password_sh state cases
and add_client_ch_default_id/pass_tr/pass_sh/flow callbacks. Adds a
setTGUser button + awaiting_tg_id state so the bot can set Client.TgID
during Add.
- clients UI: add Telegram user ID input to ClientFormModal (0 = none).
Hide IP Limit field entirely when ipLimitEnable is off — disabled fields
still take layout space, this collapses Auth(Hysteria) to full width.
- inbounds API: new GET /panel/api/inbounds/options that returns just
{id, remark, protocol, port, tlsFlowCapable}. Used by the clients page
pickers so the dropdown payload stays small on panels with thousands of
clients (drops settings JSON, clientStats, streamSettings). Server-side
TlsFlowCapable mirrors Inbound.canEnableTlsFlow so the modal no longer
needs to parse streamSettings client-side.
- clientInfoMsg now shows attached inbound remarks, and getInboundUsages
reports the attached client count per inbound.
- api-docs: document the new /options endpoint and add tgId / flow to the
clients add/update bodies.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(inbounds): keep Node column visible for node-attached inbounds
The Node column was bound to hasActiveNode, so disabling every node hid
the column even when inbounds were still attached to those nodes — the
admin lost the visual cue that those inbounds belonged to a node and
would come back when it was re-enabled. Combine hasActiveNode with a
new hasNodeAttachedInbound check (any dbInbound with nodeId != null) so
the column survives node-disable.
* fix(api-docs): accept functional-component icons in EndpointSection
AntD-Vue icons (SafetyCertificateOutlined, etc.) are functional
components, so the icon prop's type: Object validator was rejecting
them with a "Expected Object, got Function" warning at runtime.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test: cover crypto, random, netsafe, sub helpers, xray equals, websocket hub, node service
Adds ~110 unit tests across previously untested packages. Focus on
pure-logic and concurrency surfaces where regressions would silently
affect users:
- util/crypto, util/random: password hashing round-trip, ss2022 key
generation, alphabet/length invariants.
- util/netsafe: IsBlockedIP edge cases, NormalizeHost validation,
SSRF guard with AllowPrivate context bypass.
- util/common, util/json_util: traffic formatter, Combine nil-skip,
RawMessage empty-as-null and copy-on-unmarshal.
- sub: splitLinkLines, searchKey/searchHost, kcp share fields,
finalmask normalization, buildVmessLink round-trip.
- xray: Config.Equals and InboundConfig.Equals field-by-field,
getRequiredUserString/getOptionalUserString type checks.
- web/websocket: hub registration, throttling, slow-client eviction,
nil-receiver safety, concurrent register/unregister.
- web/service: NodeService.normalize validation, normalizeBasePath,
HeartbeatPatch.ToUI mapping.
- web/job: atomicBool concurrent set/takeAndReset semantics.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* i18n(clients): replace English fallbacks with proper translation keys
Pulls every hard-coded English label/title in the Clients page and its
four modals through the i18n layer so localized panels stop leaking
English. New keys live under pages.clients (auth, hysteriaAuth, uuid,
flow, flowNone, reverseTag, reverseTagPlaceholder, telegramId,
telegramIdPlaceholder, created, updated, ipLimit) plus refresh at the
root and toasts.bulkDeletedMixed / bulkCreatedMixed for partial-failure
toasts. Also switches the add-client modal's primary button from "Add"
to "Create" for consistency with other create flows.
The bulk-add Random/Random+Prefix/... email-method options stay
hard-coded by request - they're identifier-shaped strings.
* i18n: backfill 99 missing keys across all 12 non-English locales
Brings every translation file up to parity with en-US.json so the
Clients page, the fallback-children inbound section, the new refresh
verb, the Nodes panel-version label and a handful of older holes stop
falling through to the English fallback. New strings span:
- pages.clients.* (labels, confirmations, toasts, emailMethods)
- pages.inbounds.portFallback.* (Reality fallback inbound section)
- pages.nodes.panelVersion, menu.clients, refresh
Technical identifiers (Auth, UUID, Flow, Reverse tag) are intentionally
left untranslated since they correspond to xray-core field names.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* i18n: drop stale pages.client block duplicated in every non-English locale
Every non-English locale carried a pages.client (singular) section with
30 entries that duplicated pages.clients (plural). The plural namespace
is what the Vue code actually consumes; the singular one was dead
weight from an older rename that never got cleaned up in the
non-English files. Removing it brings every locale to exactly 984
keys, matching en-US.json.
* chore: apply modernize analyzer fixes across codebase
Mechanical replacements suggested by golang.org/x/tools/.../modernize:
strings.Cut/CutPrefix/SplitSeq, slices.Contains, maps.Copy, min(),
range-over-int, new(expr), strings.Builder for hot += loops,
reflect.TypeFor[T](), sync.WaitGroup.Go(), drop legacy //+build lines.
* feat(database): add PostgreSQL as an optional backend alongside SQLite
Lets operators with large client counts or multi-node setups pick PostgreSQL
at install time without breaking the existing SQLite default. Backend is
selected at runtime via XUI_DB_TYPE/XUI_DB_DSN, a small dialect layer keeps
the five JSON_EXTRACT/JSON_EACH queries portable, and a new `x-ui migrate-db`
subcommand copies SQLite data into PostgreSQL in FK-aware order.
* fix(inbounds): gate node selector to multi-node-capable protocols
Hide the Deploy-To selector and clear nodeId when switching to a
protocol that can't run on a remote node. Also:
- subs: return 404 (not 400) when subId matches no inbounds, so VPN
clients distinguish "deleted/unknown" from a server error
- hysteria link gen: use the inbound's resolved address so node-managed
inbounds advertise the node host instead of the central panel
- shadowsocks: default network to 'tcp' (udp was causing issues for some
clients on first-create)
- vite dev proxy: rewrite migrated-route bypass against the live base
path instead of a hardcoded single-segment regex
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): bulk add/delete correctness + perf, working pagination, delayed-start in form
Bulk add/delete were serial on the frontend (one toast per call, N round-trips)
and the backend race exposed by parallelizing them lost client attachments and
hit UNIQUE constraint failed on client_inbounds. The single add/edit modal also
had no Start-After-First-Use option, and the table never showed the delayed
duration.
Backend (web/service/client.go):
- Per-inbound mutex on Add/Update/Del InboundClient so concurrent writers on
the same inbound don't lose the read-modify-write of settings JSON.
- SyncInbound skips create+join when the email is tombstoned so a concurrent
maintenance pass (adjustTraffics, autoRenewClients, markClientsDisabledIn-
Settings) that did a stale RMW can't resurrect a just-deleted client with a
fresh id.
- compactOrphans sweeps settings.clients entries whose ClientRecord no longer
exists, applied in Add/DelInboundClient + DelInboundClientByEmail so each
user-initiated mutation self-heals the inbound's settings.
- DelInboundClient uses Pluck instead of First for the stats lookup so a
missing row doesn't abort the delete with a noisy ErrRecordNotFound log.
Frontend:
- HttpUtil.{get,post} accept a silent option that suppresses the auto-toast.
- ClientBulkAddModal fires creates in parallel + silent + one summary toast.
- useClients.removeMany runs deletes in parallel + silent and refreshes once;
ClientsPage bulk delete uses it and shows one aggregate toast.
- useClients.applyInvalidate debounces 200 ms so the burst of N WebSocket
invalidate events from the backend collapses into a single refresh.
- ClientsPage pagination is reactive (paginationState ref + tablePagination
computed); onTableChange persists page-size and page changes.
- ClientFormModal gains a Start-After-First-Use switch + Duration days input
alongside the existing Expiry Date picker; on edit-mode open a negative
expiryTime is decoded back to delayed mode + days; on submit the payload
sends -86400000 * days or the absolute timestamp.
- ClientsPage table shows the delayed-start duration (blue tag Nd, tooltip
Start After First Use: Nd) instead of infinity.
- Telegram ID field in the form is hidden when /panel/setting/defaultSettings
reports tgBotEnable=false; Comment then fills the row.
- Form row 3 collapses UUID (span 12) + Total GB (span 8) + Limit IP (span 4)
when ipLimitEnable is on, else UUID + Total GB at 12/12.
- useInbounds.rollupClients counts only clients with a matching clientStats
row, so orphans in settings.clients no longer inflate the inbound's count.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(windows): clean shutdown, working panel restart, harden kernel32 load
Three Windows-specific issues addressed:
1. Orphaned xray-windows-amd64 after VS Code debugger stop. Delve's
"Stop" sends TerminateProcess to the Go binary, which is uncatchable
— our signal handlers never run, so xrayService.StopXray() is skipped
and xray is left dangling. Spawn xray as a child of a Job Object with
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so the OS kills xray when our
handle to the job is closed (which happens even on TerminateProcess).
Also trap os.Interrupt in main so Ctrl+C in the terminal runs the
graceful path.
2. /panel/setting/restartPanel logged "failed to send SIGHUP signal: not
supported by windows" because Windows can't deliver arbitrary signals.
Add a restart hook in web/global; main registers it to push SIGHUP
into its own signal channel, and RestartPanel calls the hook before
falling back to the (Unix-only) signal path. Same restart-loop code
runs in both cases.
3. util/sys/sys_windows.go now uses windows.NewLazySystemDLL so the
kernel32.dll resolve is pinned to %SystemRoot%\System32 (prevents
DLL hijacking by a planted DLL next to the binary). Local filetime
type replaced with windows.Filetime, and the unreliable
syscall.GetLastError() fallback replaced with a type assertion on the
errno captured at call time.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(sys): correct CPU/connection accounting on linux + darwin
util/sys/sys_linux.go:
- GetTCPCount/GetUDPCount were counting the column header row in
/proc/net/{tcp,udp}[6] as a connection, inflating the reported total
by 1 per non-empty file (so the panel status line always showed 2
more connections than actually existed). Replace getLinesNum +
safeGetLinesNum with a single bufio.Scanner-based countConnections
that skips the header.
- CPUPercentRaw now opens HostProc("stat") instead of a hardcoded
/proc/stat so HOST_PROC overrides apply, matching the connection
counters in the same file.
- Simplify CPU field unpacking: pad nums to 8 once instead of guarding
every assignment with a len check.
util/sys/sys_darwin.go:
- Fix swapped idle/intr indices on kern.cp_time. BSD CPUSTATES order
is user, nice, sys, intr, idle (CP_INTR=3, CP_IDLE=4) — gopsutil's
cpu_darwin_nocgo.go reads the same layout. The previous code used
out[3] as idle and out[4] as intr, so busy = total - dIdle was
actually subtracting interrupt time, making the panel report CPU
usage close to 100% on macOS regardless of actual load.
- Collapse the per-field delta math into a single loop.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(xray): rotate crash reports into log folder, prevent overwrites
writeCrashReport had two flaws: it wrote to the bin folder (alongside the
xray binary) which conflates artifacts, and the second-precision timestamp
meant a tight restart-loop crash burst overwrote prior reports. Write to
the log folder with nanosecond precision and keep the last 10 reports.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* revert(inbounds): drop unreleased portfallback protocol
The Port-with-Fallback inbound (commit 62fd9f9d) was confusing as a
standalone protocol — fallbacks belong on a regular VLESS/Trojan TCP-TLS
inbound, the way Xray models them natively. Rip out the entire feature
cleanly (no migration needed since it was never released): protocol
constant, fallback children DB table, FallbackService, 2 API endpoints,
all UI rows, related translations and api-docs. A native fallback flow
attached to VLESS/Trojan TCP-TLS/Reality will land in a follow-up commit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds): native fallbacks on VLESS/Trojan TCP-TLS, with working child links
A VLESS or Trojan inbound on TCP with TLS or Reality can now act as a
fallback master: pick existing inbounds as children and the panel auto-
fills the SNI / ALPN / path / xver routing fields from each child's
transport, auto-builds settings.fallbacks at config-gen time, and
rewrites the child's client-share link so it advertises the master's
reachable endpoint and TLS state instead of the child's loopback listen.
Layout matches the Xray All-in-One Nginx example: master at :443 with
clients + TLS, each child on 127.0.0.1 with its own transport+clients.
Order matters (Xray walks fallbacks top-to-bottom) — reorder via the
per-row up/down arrows. Path / SNI / ALPN are exposed under a per-row
Edit toggle for the rare cases where the auto-derivation needs
overriding; otherwise just pick a child and you're done.
Backend: new InboundFallback table + FallbackService (GetByMaster /
SetByMaster / GetParentForChild / BuildFallbacksJSON); two routes
(GET / POST /panel/api/inbounds/:id/fallbacks); xray.GetXrayConfig
injects settings.fallbacks for any VLESS/Trojan TCP-TLS/Reality
inbound; GetInbounds annotates each child with FallbackParent so the
frontend can rewrite links without an extra round-trip.
Link projection covers every emission path — clients-page QR/links,
per-inbound Get URL, raw subscription, sub-JSON, sub-Clash, and the
inbounds-page link/info/QR — via a shared projectThroughFallbackMaster
on the backend and a shared projectChildThroughMaster on the frontend
that both handle the panel-tracked relationship and the legacy
unix-socket (@vless-ws) convention.
Strings translated into all 12 non-English locales.
* docs: rewrite CONTRIBUTING with full local-dev setup
The prior three-line CONTRIBUTING left newcomers guessing at every
non-trivial step: which Go / Node versions, where xray comes from, why
the panel goes blank when XUI_DEBUG=true is flipped on, how the Vue
multi-page setup is wired, what to do on Windows when go build trips
on the CGo SQLite driver.
Now covers prerequisites, MinGW-w64 install on Windows (niXman builds
or MSYS2), one-shot first-time setup, two frontend dev workflows with
the XUI_DEBUG asset-cache gotcha called out, the architecture and
conventions of the Vue side, a project-layout map, useful env vars,
and the PR checklist.
---------
2026-05-19 10:16:42 +00:00
local existing_webBasePath = $( ${ xui_folder } /x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##' )
2026-05-19 11:09:35 +00:00
local existing_port = $( ${ xui_folder } /x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}' )
# Properly detect empty cert by checking if cert: line exists and has content after it
local existing_cert = $( ${ xui_folder } /x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]' )
2025-08-21 12:24:25 +00:00
local URL_lists = (
"https://api4.ipify.org"
2025-12-03 20:40:49 +00:00
"https://ipv4.icanhazip.com"
"https://v4.api.ipinfo.io/ip"
"https://ipv4.myexternalip.com/raw"
"https://4.ident.me"
"https://check-host.net/ip"
2025-08-21 12:24:25 +00:00
)
local server_ip = ""
for ip_address in " ${ URL_lists [@] } " ; do
2026-05-04 11:20:24 +00:00
local response = $( curl -s -w "\n%{http_code}" --max-time 3 " ${ ip_address } " 2> /dev/null)
2026-02-11 20:32:23 +00:00
local http_code = $( echo " $response " | tail -n1)
2026-05-07 22:51:28 +00:00
local ip_result = $( echo " $response " | head -n-1 | tr -d '[:space:]"' )
if [ [ " ${ http_code } " = = "200" && " ${ ip_result } " = ~ ^[ 0-9] +\. [ 0-9] +\. [ 0-9] +\. [ 0-9] +$ ] ] ; then
2026-02-11 20:32:23 +00:00
server_ip = " ${ ip_result } "
2025-07-27 15:24:11 +00:00
break
fi
done
2026-05-04 11:20:24 +00:00
2026-05-07 22:51:28 +00:00
if [ [ -z " $server_ip " ] ] ; then
echo -e " ${ yellow } Could not auto-detect server IP from any provider. ${ plain } "
while [ [ -z " $server_ip " ] ] ; do
read -rp "Please enter your server's public IPv4 address: " server_ip
server_ip = " ${ server_ip // / } "
if [ [ ! " $server_ip " = ~ ^[ 0-9] +\. [ 0-9] +\. [ 0-9] +\. [ 0-9] +$ ] ] ; then
echo -e " ${ red } Invalid IPv4 address. Please try again. ${ plain } "
server_ip = ""
fi
done
fi
2024-10-25 09:05:22 +00:00
if [ [ ${# existing_webBasePath } -lt 4 ] ] ; then
2026-05-19 11:09:35 +00:00
if [ [ " $existing_hasDefaultCredential " = = "true" ] ] ; then
local config_webBasePath = $( gen_random_string 18)
local config_username = $( gen_random_string 10)
local config_password = $( gen_random_string 10)
2026-05-23 17:52:37 +00:00
local db_label = "SQLite (/etc/x-ui/x-ui.db)"
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } Database Selection ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
2026-05-28 15:20:16 +00:00
echo -e " 1) SQLite (default — recommended for < 500 clients)"
2026-05-23 17:52:37 +00:00
echo -e " 2) PostgreSQL (recommended for high client counts / many nodes)"
read -rp "Choose [1]: " db_choice
db_choice = " ${ db_choice :- 1 } "
if [ [ " $db_choice " = = "2" ] ] ; then
local xui_env_file
case " ${ release } " in
ubuntu | debian | armbian)
xui_env_file = "/etc/default/x-ui"
; ;
arch | manjaro | parch | alpine)
xui_env_file = "/etc/conf.d/x-ui"
; ;
*)
xui_env_file = "/etc/sysconfig/x-ui"
; ;
esac
local xui_dsn = ""
local pg_mode = ""
2026-05-28 15:20:16 +00:00
local pg_local_installed = 0
2026-05-23 17:52:37 +00:00
while [ [ -z " $xui_dsn " ] ] ; do
echo ""
echo -e " 1) Install PostgreSQL locally and create a dedicated user/db (recommended)"
echo -e " 2) Use an existing PostgreSQL server (enter DSN)"
read -rp "Choose [1]: " pg_mode
pg_mode = " ${ pg_mode :- 1 } "
if [ [ " $pg_mode " = = "2" ] ] ; then
while [ [ -z " $xui_dsn " ] ] ; do
read -rp "Enter PostgreSQL DSN (postgres://user:pass@host:port/dbname?sslmode=disable): " xui_dsn
xui_dsn = " ${ xui_dsn // / } "
done
db_label = "PostgreSQL (external)"
else
echo -e " ${ yellow } Installing PostgreSQL — this may take a moment... ${ plain } "
2026-05-28 15:20:16 +00:00
local pg_cred_file
pg_cred_file = $( mktemp 2> /dev/null) || pg_cred_file = $( mktemp -t x-ui-pg-creds.XXXXXXXX)
if [ [ -z " ${ pg_cred_file } " ] ] ; then
echo -e " ${ red } Failed to create temporary credentials file. ${ plain } "
xui_dsn = ""
continue
fi
if xui_dsn = $( PG_CRED_FILE = " ${ pg_cred_file } " install_postgres_local) ; then
pg_local_installed = 1
if [ [ -r " ${ pg_cred_file } " ] ] ; then
# shellcheck disable=SC1090
source " ${ pg_cred_file } "
fi
rm -f " ${ pg_cred_file } "
db_label = " PostgreSQL ( ${ PG_USER } @ ${ PG_HOST } : ${ PG_PORT } / ${ PG_DB } ) "
2026-05-23 17:52:37 +00:00
else
2026-05-28 15:20:16 +00:00
rm -f " ${ pg_cred_file } "
2026-05-23 17:52:37 +00:00
echo ""
echo -e " ${ red } PostgreSQL installation failed. ${ plain } "
echo -e " 1) Retry local install"
echo -e " 2) Enter an external DSN instead"
echo -e " 3) Abort install"
echo -e " 4) Fall back to SQLite"
read -rp "Choose [1]: " pg_fail
pg_fail = " ${ pg_fail :- 1 } "
case " $pg_fail " in
2) pg_mode = "2" ; ;
2026-05-28 15:20:16 +00:00
3)
echo -e " ${ red } Install aborted. ${ plain } "
exit 1
; ;
4)
db_choice = "1"
xui_dsn = ""
break
; ;
2026-05-23 17:52:37 +00:00
*) xui_dsn = "" ; ;
esac
fi
fi
done
if [ [ -n " $xui_dsn " ] ] ; then
install -d -m 755 " $( dirname " $xui_env_file " ) "
umask 077
cat > " $xui_env_file " << EOF
XUI_DB_TYPE = postgres
XUI_DB_DSN = ${ xui_dsn }
EOF
chmod 600 " $xui_env_file "
umask 022
export XUI_DB_TYPE = postgres
export XUI_DB_DSN = " ${ xui_dsn } "
2026-05-31 15:53:34 +00:00
ensure_pg_client || echo -e " ${ yellow } ⚠ Could not install pg_dump/pg_restore. In-panel database backup/restore will be unavailable until you install the postgresql-client package. ${ plain } "
2026-05-23 17:52:37 +00:00
fi
fi
2026-05-19 11:09:35 +00:00
read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
if [ [ " ${ config_confirm } " = = "y" || " ${ config_confirm } " = = "Y" ] ] ; then
read -rp "Please set up the panel port: " config_port
echo -e " ${ yellow } Your Panel Port is: ${ config_port } ${ plain } "
else
local config_port = $( shuf -i 1024-62000 -n 1)
echo -e " ${ yellow } Generated random port: ${ config_port } ${ plain } "
fi
${ xui_folder } /x-ui setting -username " ${ config_username } " -password " ${ config_password } " -port " ${ config_port } " -webBasePath " ${ config_webBasePath } "
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } SSL Certificate Setup (RECOMMENDED) ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ yellow } SSL is strongly recommended. Skip only if a reverse proxy ${ plain } "
echo -e " ${ yellow } or SSH tunnel handles TLS for you. ${ plain } "
echo -e " ${ yellow } Let's Encrypt now supports both domains and IP addresses! ${ plain } "
echo ""
prompt_and_setup_ssl " ${ config_port } " " ${ config_webBasePath } " " ${ server_ip } "
# Retrieve the API token for display
local config_apiToken = $( ${ xui_folder } /x-ui setting -getApiToken true | grep -Eo 'apiToken: .+' | awk '{print $2}' )
# Display final credentials and access information
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } Panel Installation Complete! ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } Username: ${ config_username } ${ plain } "
echo -e " ${ green } Password: ${ config_password } ${ plain } "
echo -e " ${ green } Port: ${ config_port } ${ plain } "
echo -e " ${ green } WebBasePath: ${ config_webBasePath } ${ plain } "
2026-05-23 17:52:37 +00:00
echo -e " ${ green } Database: ${ db_label } ${ plain } "
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Access URL: ${ SSL_SCHEME } :// ${ SSL_HOST } : ${ config_port } / ${ config_webBasePath } ${ plain } "
echo -e " ${ green } API Token: ${ config_apiToken } ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ yellow } ⚠ IMPORTANT: Save these credentials securely! ${ plain } "
if [ [ " $SSL_SCHEME " = = "https" ] ] ; then
echo -e " ${ yellow } ⚠ SSL Certificate: Enabled and configured ${ plain } "
else
echo -e " ${ yellow } ⚠ SSL Certificate: Skipped — panel is HTTP-only. Use a reverse proxy or SSH tunnel. ${ plain } "
fi
2026-05-28 15:20:16 +00:00
2026-05-31 15:53:34 +00:00
if [ [ " $db_choice " = = "2" ] ] ; then
echo ""
echo -e " ${ green } PostgreSQL backup & restore is built into the panel: ${ plain } "
echo -e " ${ blue } ${ SSL_SCHEME } :// ${ SSL_HOST } : ${ config_port } / ${ config_webBasePath } ${ plain } → Backup & Restore "
echo -e " ${ yellow } Back Up downloads a pg_dump .dump file; Restore reloads it via pg_restore. ${ plain } "
fi
2026-05-28 15:20:16 +00:00
if [ [ " $db_choice " = = "2" && " $pg_local_installed " = = "1" ] ] ; then
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } PostgreSQL Credentials ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } DB Name: ${ PG_DB } ${ plain } "
echo -e " ${ green } Username: ${ PG_USER } ${ plain } "
echo -e " ${ green } Password: ${ PG_PASS } ${ plain } "
echo -e " ${ green } Host: ${ PG_HOST } ${ plain } "
echo -e " ${ green } Port: ${ PG_PORT } ${ plain } "
echo -e " ${ green } DSN: ${ xui_dsn } ${ plain } "
echo -e " ${ green } Env file: ${ xui_env_file } ${ plain } "
echo -e " ${ green } ------------------------------------------- ${ plain } "
echo -e " ${ green } Connect from this server: ${ plain } "
echo -e " ${ blue } sudo -u postgres psql -d ${ PG_DB } ${ plain } (as the postgres superuser) "
echo -e " ${ blue } PGPASSWORD=' ${ PG_PASS } ' psql -h ${ PG_HOST } -p ${ PG_PORT } -U ${ PG_USER } -d ${ PG_DB } ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ yellow } ⚠ The panel reads these credentials from ${ xui_env_file } . ${ plain } "
echo -e " ${ yellow } ⚠ Save the password — it is not stored anywhere else in plain text. ${ plain } "
unset PG_USER PG_PASS PG_HOST PG_PORT PG_DB
fi
2026-05-19 11:09:35 +00:00
else
local config_webBasePath = $( gen_random_string 18)
echo -e " ${ yellow } WebBasePath is missing or too short. Generating a new one... ${ plain } "
${ xui_folder } /x-ui setting -webBasePath " ${ config_webBasePath } "
echo -e " ${ green } New WebBasePath: ${ config_webBasePath } ${ plain } "
# If the panel is already installed but no certificate is configured, prompt for SSL now
if [ [ -z " ${ existing_cert } " ] ] ; then
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } SSL Certificate Setup (RECOMMENDED) ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ yellow } Let's Encrypt now supports both domains and IP addresses! ${ plain } "
echo ""
prompt_and_setup_ssl " ${ existing_port } " " ${ config_webBasePath } " " ${ server_ip } "
echo -e " ${ green } Access URL: ${ SSL_SCHEME } :// ${ SSL_HOST } : ${ existing_port } / ${ config_webBasePath } ${ plain } "
else
# If a cert already exists, just show the access URL
echo -e " ${ green } Access URL: https:// ${ server_ip } : ${ existing_port } / ${ config_webBasePath } ${ plain } "
fi
fi
2024-10-24 19:17:00 +00:00
else
2026-05-19 11:09:35 +00:00
if [ [ " $existing_hasDefaultCredential " = = "true" ] ] ; then
local config_username = $( gen_random_string 10)
local config_password = $( gen_random_string 10)
echo -e " ${ yellow } Default credentials detected. Security update required... ${ plain } "
${ xui_folder } /x-ui setting -username " ${ config_username } " -password " ${ config_password } "
echo -e "Generated new random login credentials:"
echo -e "###############################################"
echo -e " ${ green } Username: ${ config_username } ${ plain } "
echo -e " ${ green } Password: ${ config_password } ${ plain } "
echo -e "###############################################"
else
echo -e " ${ green } Username, Password, and WebBasePath are properly set. ${ plain } "
fi
# Existing install: if no cert configured, prompt user for SSL setup
# Properly detect empty cert by checking if cert: line exists and has content after it
existing_cert = $( ${ xui_folder } /x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]' )
if [ [ -z " $existing_cert " ] ] ; then
echo ""
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ green } SSL Certificate Setup (RECOMMENDED) ${ plain } "
echo -e " ${ green } ═══════════════════════════════════════════ ${ plain } "
echo -e " ${ yellow } Let's Encrypt now supports both domains and IP addresses! ${ plain } "
echo ""
prompt_and_setup_ssl " ${ existing_port } " " ${ existing_webBasePath } " " ${ server_ip } "
echo -e " ${ green } Access URL: ${ SSL_SCHEME } :// ${ SSL_HOST } : ${ existing_port } / ${ existing_webBasePath } ${ plain } "
else
echo -e " ${ green } SSL certificate already configured. No action needed. ${ plain } "
fi
2023-02-09 19:18:06 +00:00
fi
2026-05-19 11:09:35 +00:00
${ xui_folder } /x-ui migrate
2023-02-09 19:18:06 +00:00
}
2026-05-19 11:09:35 +00:00
install_x-ui( ) {
2026-01-03 02:57:19 +00:00
cd ${ xui_folder %/x-ui } /
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
# Download resources
if [ $# = = 0 ] ; then
tag_version = $( curl -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' )
if [ [ ! -n " $tag_version " ] ] ; then
echo -e " ${ yellow } Trying to fetch version with IPv4... ${ plain } "
tag_version = $( curl -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' )
if [ [ ! -n " $tag_version " ] ] ; then
echo -e " ${ red } Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later ${ plain } "
exit 1
fi
fi
echo -e " Got x-ui latest version: ${ tag_version } , beginning the installation... "
curl -4fLRo ${ xui_folder } -linux-$( arch) .tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${ tag_version } /x-ui-linux-$( arch) .tar.gz
if [ [ $? -ne 0 ] ] ; then
echo -e " ${ red } Downloading x-ui failed, please be sure that your server can access GitHub ${ plain } "
exit 1
fi
2023-02-09 19:18:06 +00:00
else
2026-05-19 11:09:35 +00:00
tag_version = $1
tag_version_numeric = ${ tag_version #v }
min_version = "2.3.5"
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
if [ [ " $( printf '%s\n' " $min_version " " $tag_version_numeric " | sort -V | head -n1) " != " $min_version " ] ] ; then
echo -e " ${ red } Please use a newer version (at least v2.3.5). Exiting installation. ${ plain } "
exit 1
fi
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
url = " https://github.com/MHSanaei/3x-ui/releases/download/ ${ tag_version } /x-ui-linux- $( arch) .tar.gz "
echo -e " Beginning to install x-ui $1 "
curl -4fLRo ${ xui_folder } -linux-$( arch) .tar.gz ${ url }
if [ [ $? -ne 0 ] ] ; then
echo -e " ${ red } Download x-ui $1 failed, please check if the version exists ${ plain } "
exit 1
2023-02-09 19:18:06 +00:00
fi
fi
2026-05-19 11:09:35 +00:00
curl -4fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
2025-09-25 12:34:12 +00:00
if [ [ $? -ne 0 ] ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ red } Failed to download x-ui.sh ${ plain } "
exit 1
2025-09-25 12:34:12 +00:00
fi
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
# Stop x-ui service and remove old resources
2026-01-03 02:57:19 +00:00
if [ [ -e ${ xui_folder } / ] ] ; then
2025-09-22 19:56:43 +00:00
if [ [ $release = = "alpine" ] ] ; then
2026-05-19 11:09:35 +00:00
rc-service x-ui stop
2025-09-22 19:56:43 +00:00
else
2026-05-19 11:09:35 +00:00
systemctl stop x-ui
2025-09-22 19:56:43 +00:00
fi
2026-05-19 11:09:35 +00:00
rm ${ xui_folder } / -rf
2023-02-09 19:18:06 +00:00
fi
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
# Extract resources and set permissions
tar zxvf x-ui-linux-$( arch) .tar.gz
rm x-ui-linux-$( arch) .tar.gz -f
cd x-ui
chmod +x x-ui
chmod +x x-ui.sh
2026-05-04 11:20:24 +00:00
2024-01-16 00:01:15 +00:00
# Check the system's architecture and rename the file accordingly
2024-04-01 08:42:28 +00:00
if [ [ $( arch) = = "armv5" || $( arch) = = "armv6" || $( arch) = = "armv7" ] ] ; then
2026-05-19 11:09:35 +00:00
mv bin/xray-linux-$( arch) bin/xray-linux-arm
chmod +x bin/xray-linux-arm
2024-01-16 00:01:15 +00:00
fi
2026-05-19 11:09:35 +00:00
chmod +x x-ui bin/xray-linux-$( arch)
# Update x-ui cli and se set permission
mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui
config_after_install
# Etckeeper compatibility
if [ -d "/etc/.git" ] ; then
if [ -f "/etc/.gitignore" ] ; then
if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore" ; then
echo "" >> "/etc/.gitignore"
echo "x-ui/x-ui.db" >> "/etc/.gitignore"
echo -e " ${ green } Added x-ui.db to /etc/.gitignore for etckeeper ${ plain } "
fi
else
echo "x-ui/x-ui.db" > "/etc/.gitignore"
echo -e " ${ green } Created /etc/.gitignore and added x-ui.db for etckeeper ${ plain } "
2026-01-03 02:13:00 +00:00
fi
fi
2026-05-04 11:20:24 +00:00
2025-09-22 19:56:43 +00:00
if [ [ $release = = "alpine" ] ] ; then
2026-05-19 11:09:35 +00:00
curl -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
2025-09-25 12:34:12 +00:00
if [ [ $? -ne 0 ] ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ red } Failed to download x-ui.rc ${ plain } "
exit 1
2025-09-25 12:34:12 +00:00
fi
2026-05-19 11:09:35 +00:00
chmod +x /etc/init.d/x-ui
rc-update add x-ui
rc-service x-ui start
2025-09-22 19:56:43 +00:00
else
2026-05-19 11:09:35 +00:00
# Install systemd service file
service_installed = false
2026-01-03 02:37:48 +00:00
if [ -f "x-ui.service" ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Found x-ui.service in extracted files, installing... ${ plain } "
2026-05-04 11:20:24 +00:00
cp -f x-ui.service ${ xui_service } / > /dev/null 2>& 1
2026-05-19 11:09:35 +00:00
if [ [ $? -eq 0 ] ] ; then
service_installed = true
2026-01-03 06:27:39 +00:00
fi
2026-05-19 11:09:35 +00:00
fi
if [ " $service_installed " = false ] ; then
2026-01-03 06:27:39 +00:00
case " ${ release } " in
ubuntu | debian | armbian)
if [ -f "x-ui.service.debian" ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Found x-ui.service.debian in extracted files, installing... ${ plain } "
2026-05-04 11:20:24 +00:00
cp -f x-ui.service.debian ${ xui_service } /x-ui.service > /dev/null 2>& 1
2026-01-03 06:27:39 +00:00
if [ [ $? -eq 0 ] ] ; then
service_installed = true
fi
fi
2026-05-04 11:20:24 +00:00
; ;
2026-01-18 14:41:07 +00:00
arch | manjaro | parch)
if [ -f "x-ui.service.arch" ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Found x-ui.service.arch in extracted files, installing... ${ plain } "
2026-05-04 11:20:24 +00:00
cp -f x-ui.service.arch ${ xui_service } /x-ui.service > /dev/null 2>& 1
2026-01-18 14:41:07 +00:00
if [ [ $? -eq 0 ] ] ; then
service_installed = true
fi
fi
2026-05-04 11:20:24 +00:00
; ;
2026-01-03 06:27:39 +00:00
*)
if [ -f "x-ui.service.rhel" ] ; then
2026-05-19 11:09:35 +00:00
echo -e " ${ green } Found x-ui.service.rhel in extracted files, installing... ${ plain } "
2026-05-04 11:20:24 +00:00
cp -f x-ui.service.rhel ${ xui_service } /x-ui.service > /dev/null 2>& 1
2026-01-03 06:27:39 +00:00
if [ [ $? -eq 0 ] ] ; then
service_installed = true
fi
fi
2026-05-04 11:20:24 +00:00
; ;
2026-01-03 06:27:39 +00:00
esac
2026-05-19 11:09:35 +00:00
fi
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
# If service file not found in tar.gz, download from GitHub
if [ " $service_installed " = false ] ; then
echo -e " ${ yellow } Service files not found in tar.gz, downloading from GitHub... ${ plain } "
case " ${ release } " in
ubuntu | debian | armbian)
curl -4fLRo ${ xui_service } /x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian > /dev/null 2>& 1
; ;
arch | manjaro | parch)
curl -4fLRo ${ xui_service } /x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch > /dev/null 2>& 1
; ;
*)
curl -4fLRo ${ xui_service } /x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel > /dev/null 2>& 1
; ;
esac
if [ [ $? -ne 0 ] ] ; then
echo -e " ${ red } Failed to install x-ui.service from GitHub ${ plain } "
exit 1
2026-01-03 06:27:39 +00:00
fi
2026-05-19 11:09:35 +00:00
service_installed = true
2026-01-03 02:37:48 +00:00
fi
2026-05-04 11:20:24 +00:00
2026-05-19 11:09:35 +00:00
if [ " $service_installed " = true ] ; then
echo -e " ${ green } Setting up systemd unit... ${ plain } "
chown root:root ${ xui_service } /x-ui.service > /dev/null 2>& 1
chmod 644 ${ xui_service } /x-ui.service > /dev/null 2>& 1
systemctl daemon-reload
systemctl enable x-ui
systemctl start x-ui
else
echo -e " ${ red } Failed to install x-ui.service file ${ plain } "
exit 1
fi
fi
Feat/multi inbound clients (#4469)
* feat(clients): add shadow tables for first-class client promotion
Introduces three new GORM-backed tables (clients, client_inbounds,
inbound_fallback_children) and a populate-only seeder that backfills
them from each inbound's existing settings.clients JSON. Duplicate
emails across inbounds auto-merge under one client row, with each
field conflict logged. Existing services are unchanged and continue
reading from settings.clients — this commit is groundwork only.
* feat(clients): make clients+client_inbounds the runtime source of truth
Adds ClientService.SyncInbound that reconciles the new tables from
each inbound's clients list whenever existing service paths mutate
settings.clients. Wires it into AddInbound, UpdateInbound,
AddInboundClient, UpdateInboundClient, DelInboundClient,
DelInboundClientByEmail, DelDepletedClients, autoRenewClients, and
the timestamp-backfill path in adjustTraffics, plus DetachInbound
on DelInbound.
GetXrayConfig now builds settings.clients from the new tables before
writing config.json, and getInboundsBySubId joins through them
instead of JSON_EACH on settings JSON. Live Xray config and
subscription endpoints are now driven by the relational view;
settings.clients JSON stays in step as a side effect of every write.
* feat(clients): add top-level Clients tab and CRUD API
Adds /panel/api/clients endpoints (list, get, add, update, del,
attach, detach) backed by ClientService methods that orchestrate
the per-inbound Add/Update/Del flows so a single client row is
created once and attached to many inbounds in one operation.
The frontend gains a dedicated Clients page (frontend/clients.html
+ src/pages/clients/) with an AntD table, multi-inbound attach
modal, and full CRUD. Axios interceptor learns to honour
Content-Type: application/json so the JSON endpoints work
alongside the legacy form-encoded ones.
The legacy per-inbound client modal stays untouched in this PR —
both flows now write to the same source of truth.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds): add Port-with-Fallback inbound type
Adds a new "portfallback" protocol that emits as a VLESS-TLS inbound
under the hood but is paired with a sidecar table of child inbounds.
Panel auto-builds settings.fallbacks at Xray-config-gen time from the
sidecar — each child's listen+port becomes the fallback dest, with
SNI/ALPN/path/xver match criteria pulled from the row. No more typing
loopback ports by hand or keeping settings.fallbacks in sync.
Backend: new FallbackService (Get/SetChildren, BuildFallbacksJSON);
two new routes (GET/POST /panel/api/inbounds/:id/fallbackChildren);
xray.GetXrayConfig injects fallbacks for PortFallback inbounds; the
inbound model emits protocol="vless" so Xray accepts the config.
Frontend: PORTFALLBACK joins the protocol dropdown; selecting it
shows the standard VLESS controls plus a Fallback Children table
(inbound picker + per-row SNI/ALPN/path/xver). Children are loaded
on edit and replaced atomically on save.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Reset Traffic, QR Code, Info actions + Online/Remaining columns
The Clients page table gains:
- Online column — green/grey tag driven by /panel/api/inbounds/onlines,
polled every 10s.
- Remaining column — bytes-remaining tag, coloured green/orange/red
against quota, purple infinity when unlimited.
- Action icons per row: QR, Info, Reset traffic, Edit, Delete.
ClientInfoModal shows the full client detail (uuid/password/auth,
traffic ↑/↓ + remaining + all-time, expiry absolute + relative,
attached inbounds chip list, online + last-online).
ClientQrModal fetches links for the client's subId via
/panel/api/inbounds/getSubLinks/:subId and renders each one through
the existing QrPanel component.
Reset Traffic confirms then calls the existing per-inbound endpoint
on the client's first attached inbound (the traffic row is keyed on
email globally, so any attached inbound resets the shared counter).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): expose Attached inbounds in edit mode
The multi-select was gated on add-only, so editing a client had no way
to change which inbounds it belonged to. The picker now shows in both
modes, and on submit the modal diffs the picked set against the
original attachedIds — additions go through the /attach endpoint,
removals through /detach, both after the field update lands so the
new attachments get the latest values.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): unbreak template parsing + stale i18n keys
- InboundFormModal: split the multi-line help string in the
PortFallback section onto one line — Vue's template parser was
bailing on Unterminated string constant because a single-quoted
literal spanned two lines inside a {{ }} interpolation.
- ClientInfoModal: t('disable') was missing at the root level, so
vue-i18n returned the key path literally. Use t('disabled') which
exists.
- Linter cleanup elsewhere: pages.client.* references renamed to
pages.clients.* to match the merged i18n block; whitespace
normalisation in a few unrelated Vue templates.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* 1
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(traffic): drop all-time traffic tracking
Removes the AllTime field from Inbound and ClientTraffic and migrates
existing DBs by dropping the all_time columns on startup. The counter
duplicated up+down without adding signal, and the per-event accumulator
ran on every traffic write.
Frontend: drop the All-time column from the inbound list and the
client-row table, the All-time row from the client info modal, and the
All-Time Total Usage tile from the inbounds summary card. The
allTimeTraffic/allTimeTrafficUsage i18n keys are removed across every
locale.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): mobile cards, multi-select, bulk add
Adds the same row-card layout the inbounds page uses on mobile: the
table is suppressed under the mobile breakpoint and each client renders
as a compact card with a status dot, email, Info button, Enable switch,
and overflow menu. All the per-client detail (traffic, remaining,
expiry, attached inbounds, flow, created/updated, URL, subscription)
opens through the existing info modal.
Multi-select with bulk delete wires AntD row-selection on desktop and
a per-card checkbox on mobile; a Delete (N) button appears in the
toolbar when anything is selected.
Bulk add reuses the five email-generation modes from the inbound bulk
modal but takes a multi-inbound picker so one bulk run can attach to
several inbounds at once. Submits client-by-client through the
existing /panel/api/clients/add endpoint.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(inbounds): remove legacy per-inbound client UI
Now that clients live as first-class rows attached to one or many
inbounds, the per-inbound client UI on the inbounds page is dead
weight — every client action either has a global equivalent on the
Clients page or makes no sense in a many-to-many world.
Deletes ClientFormModal, ClientBulkModal, CopyClientsModal, and
ClientRowTable from inbounds/. Strips the matching emits, refs,
handlers, and dropdown menu items from InboundList and InboundsPage,
and removes the dead mobile expand-chevron state and the desktop
expanded-row plumbing that drove the inline client table.
The InboundFormModal Clients tab still works in add-mode (one inline
client at inbound creation) — that flow goes through ClientService.
SyncInbound on save and remains useful.
Fixes a stray "</a-dropdown>" left over by an earlier toolbar edit
in ClientsPage that broke the template parser.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Delete depleted action
Mirrors the legacy delDepletedClients action that lived under the
inbounds page, but as a first-class /panel/api/clients/delDepleted
endpoint backed by ClientService. The new path goes through
ClientService.Delete for each depleted email, so the new clients +
client_inbounds + xray_client_traffic tables stay consistent.
Adds a danger-styled toolbar button on the Clients page (next to
Reset all client traffic) with a confirm dialog and a toast
reporting the deleted count.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(api): move every client-shaped endpoint off /inbounds onto /clients
After the multi-inbound client migration, client state belongs to the
client API surface, not the inbound one. Twelve routes that were
crammed under /panel/api/inbounds/* now live where they belong, under
/panel/api/clients/*.
Moved (route, handler, doc):
POST /clientIps/:email
POST /clearClientIps/:email
POST /onlines
POST /lastOnline
POST /updateClientTraffic/:email
POST /resetAllClientTraffics/:id
POST /delDepletedClients/:id
POST /:id/resetClientTraffic/:email
GET /getClientTraffics/:email
GET /getClientTrafficsById/:id
GET /getSubLinks/:subId
GET /getClientLinks/:id/:email
Their /clients/* counterparts are:
POST /clients/clientIps/:email
POST /clients/clearClientIps/:email
POST /clients/onlines
POST /clients/lastOnline
POST /clients/updateTraffic/:email
POST /clients/resetTraffic/:email (email-only, fans out)
GET /clients/traffic/:email
GET /clients/traffic/byId/:id
GET /clients/subLinks/:subId
GET /clients/links/:id/:email
per-inbound resetAllClientTraffics and delDepletedClients are dropped
entirely — the Clients page already exposes global Reset All Traffic
and Delete depleted actions, and per-inbound resets are meaningless
once a client can be attached to many inbounds.
ClientService.ResetTrafficByEmail is the new email-only reset path:
it looks up every inbound the client is attached to and pushes the
counter reset + Xray re-add through inboundService.ResetClientTraffic
for each one, so depleted users come back online instantly.
Frontend callers (ClientsPage, useClients, ClientQrModal,
ClientInfoModal, InboundInfoModal, InboundsPage, useInbounds) all
switched to the new paths. The Inbounds page drops its per-inbound
"Reset client traffic" and "Delete depleted clients" dropdown items —
users do those at the client level now. api-docs is rebuilt to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(service): switch tgbot + ldap callers to ClientService
Adds two thin helpers to ClientService (CreateOne, DetachByEmail) and
rewrites tgbot.SubmitAddClient and ldap_sync_job to call ClientService
directly. Removes the JSON-blob payloads (BuildJSONForProtocol output for
add, clientsToJSON/clientToJSON helpers) that callers previously fed to
InboundService.AddInboundClient/DelInboundClient.
ldap_sync_job.batchSetEnable now loops InboundService.SetClientEnableByEmail
per email instead of trying to coerce AddInboundClient into doing the
update — the old path would have failed duplicate-email validation for
existing clients anyway.
The legacy InboundService.AddInboundClient/UpdateInboundClient/
DelInboundClient methods stay in place; they are now only used internally
by ClientService Create/Update/Delete/Attach. Inlining + deleting them
follows in a separate commit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(service): move all client mutation methods to ClientService
Moves the client mutation surface out of InboundService and into
ClientService. These methods all operate on a single client (identity
fields, traffic limits, expiry, ip limit, enable state, telegram tg id)
and didn't belong on the inbound aggregate.
Moved (12 methods): AddInboundClient, UpdateInboundClient, DelInboundClient,
DelInboundClientByEmail, checkEmailsExistForClients, SetClientTelegramUserID,
checkIsEnabledByEmail, ToggleClientEnableByEmail, SetClientEnableByEmail,
ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail,
ResetClientTrafficLimitByEmail.
Each method now takes an explicit *InboundService for the helpers that
legitimately stay on InboundService (GetInbound, GetClients, runtimeFor,
AddClientStat / UpdateClientStat / DelClientStat, DelClientIPs /
UpdateClientIPs, emailUsedByOtherInbounds, getAllEmailSubIDs,
GetClientInboundByEmail / GetClientInboundByTrafficID,
GetClientTrafficByEmail).
Stays on InboundService: ResetClientTrafficByEmail and
ResetClientTraffic(id, email) — these mutate xray_client_traffic rows,
not client identity, so they're inbound-side bookkeeping.
Callers updated: tgbot (6 calls), ldap_sync_job (1 call),
InboundService internal (writeBackClientSubID, CopyInboundClients,
AddInbound's email-uniqueness check), ClientService Create/Update/
Delete/Attach/Detach.
Also removes a dead resetAllClientTraffics controller handler whose
route was already gone after the previous /clients API migration.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(clients): finish migrating to ClientService + tidy IP routes
Two related cleanups in the new /clients surface:
1. Move ResetAllClientTraffics (bulk-reset of xray_client_traffic +
last_traffic_reset_time, with node-runtime propagation) from
InboundService to ClientService. PeriodicTrafficResetJob now holds
a clientService and calls
j.clientService.ResetAllClientTraffics(&j.inboundService, id).
The last client-mutation method on InboundService is gone.
2. Shorten redundantly-named routes/handlers under /panel/api/clients:
- /clientIps/:email -> /ips/:email (handler getIps)
- /clearClientIps/:email -> /clearIps/:email (handler clearIps)
The "client" prefix was redundant inside the clients namespace.
Frontend (InboundInfoModal) and api-docs updated to match.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds,clients): clean up inbound modal + enrich client modal
Inbound modal rework (InboundFormModal.vue + inbound.js):
- Drop the embedded Client subform in the Protocol tab. Multi-inbound
clients are managed exclusively from the Clients page now; a fresh
inbound is created with zero clients (settings constructors default
to []) and the user attaches clients afterwards.
- Hide the Protocol tab entirely when it has nothing to render
(VMESS, Trojan without fallbacks, Hysteria). Auto-switches active
tab to Basic when the tab disappears while focused.
- Move the Security section (Security selector + TLS block with certs
and ECH + Reality block) out of the Stream tab into its own
Security tab, sharing the canEnableStream gate.
Client modal additions (ClientFormModal.vue + ClientBulkAddModal.vue):
- Flow select (xtls-rprx-vision / -udp443) appears only when the
panel actually has a Vision-capable inbound (VLESS or PortFallback
on TCP with TLS or Reality). Hidden otherwise, and cleared when
it disappears.
- IP Limit input is disabled when the panel-level ipLimitEnable
setting is off, fetched into useClients alongside subSettings and
threaded through ClientsPage to both modals.
- Edit modal now shows an "IP Log" section listing IPs that have
connected with the client's credentials, with refresh and clear
buttons (calls the renamed /panel/api/clients/ips and /clearIps
endpoints).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(inbounds): drop manual Fallbacks UI from inbound modal
The PortFallback protocol type now covers the common
VLESS-master-plus-children case with auto-wired dests, so the manual
Fallbacks editor (showFallbacks block in the Protocol tab) is mostly
redundant. Removed:
- the v-if="showFallbacks" template block (SNI/ALPN/Path/dest/PROXY rows)
- the showFallbacks computed
- the addFallback / delFallback helpers
- the .fallbacks-header / .fallbacks-title styles
- the showFallbacks gate from hasProtocolTabContent (so Trojan-over-TCP
no longer shows an empty Protocol tab)
Power users who need a non-inbound fallback dest (nginx, static site)
can still author settings.fallbacks via the Advanced JSON tab.
* feat(clients,inbounds): move search/filter to Clients page + small fixes
Search/filter relocation:
- Remove the search/filter toolbar (search switch + filter radio +
protocol/node selects + the visibleInbounds projection +
inboundsFilterState localStorage + filter CSS + the SearchOutlined/
FilterOutlined/ObjectUtil/Inbound imports it required) from
InboundList. The filters were all client-oriented buckets bolted
onto the inbound row.
- Add a search/filter toolbar to ClientsPage with the same shape:
switch between deep-text search and bucket filter (active /
deactive / depleted / expiring / online) + protocol filter that
matches clients attached to at least one inbound with the chosen
protocol. State persists in clientsFilterState localStorage.
filteredClients drives both the desktop table and the mobile card
list, and select-all / allSelected / someSelected only span the
visible subset.
- useClients now also fetches expireDiff and trafficDiff from
/panel/setting/defaultSettings (used to detect the expiring
bucket); ClientsPage threads them into the client-bucket helper.
Loose fixes folded in:
- Add Client: email field is auto-filled with a random handle on
open, matching uuid/subId/password/auth.
- Inbound clone: parse and reuse the source settings JSON (with
clients reset to []) instead of building a fresh defaulted
Settings, so VLESS Encryption/Decryption and other non-client
fields survive the clone.
- en-US.json: add the ipLog string used by the edit-client modal.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): add Reverse tag field for VLESS-attached clients
Mirrors the Flow field's pattern: a Reverse tag input appears in the
Add/Edit Client modal whenever at least one selected inbound is VLESS
or PortFallback. The value rides over the wire as
client.reverse = { tag: '...' } so it lands directly in model.Client's
*ClientReverse field; an empty value omits the reverse key entirely.
On edit the field is hydrated from props.client.reverse?.tag, and the
showReverseTag watcher clears the field if the user drops the last
VLESS-like inbound from the selection.
* fix(xray): emit only protocol-relevant fields per client entry
The Xray config synthesizer was writing every identifier field (id,
password, flow, auth, security/method, reverse) on every client entry
regardless of the inbound's protocol. Xray ignores unknown fields, so
the config worked, but it diverged from the spec and leaked secrets
across protocols when one client was attached to multiple inbounds —
a VLESS inbound's generated config carried the same client's Trojan
password and Hysteria auth alongside its uuid.
Switch on inbound.Protocol when building each entry:
- VLESS / PortFallback: id, flow, reverse
- VMess: id, security
- Trojan: password, flow
- Shadowsocks: password, method
- Hysteria / Hysteria2: auth
email is emitted for every protocol.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): restore auto-disable kick under new schema
disableInvalidClients still resolved (inbound_tag, email) pairs via
JSON_EACH(inbounds.settings.clients), which is empty after migrating
to the clients + client_inbounds tables. Result: xrayApi.RemoveUser
never ran for depleted clients, clients.enable stayed true so the UI
showed them as active, and only xray_client_traffic.enable got flipped
- making "Restart Xray After Auto Disable" only half-work.
Resolve the targets via a JOIN through the new schema, flip clients.enable
so the Clients page reflects the state, and drop the legacy JSON
write-back plus the subId cascade workaround (email is unique now).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): live WebSocket updates + Ended status surfacing
ClientsPage now subscribes to traffic / client_stats / invalidate
WebSocket events instead of polling /onlines every 10s. Per-row
traffic counters refresh in place, online state stays current, and
list-level mutations elsewhere trigger a refresh.
The client roll-up summary moves from InboundsPage to ClientsPage
where it belongs, restructured into six labeled stat tiles
(Total / Online / Ended / Expiring / Disabled / Active) with email
popovers on the ones with issues.
Auto-disabled clients (traffic exhausted or expiry passed) now
classify as 'depleted' even though clients.enable=false, so they
show up under the Ended filter and render a red Ended tag instead
of looking indistinguishable from an operator-disabled row.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(nodes): per-node client roll-up and panel version
Added transient inboundCount / clientCount / onlineCount /
depletedCount fields to model.Node, populated by NodeService.GetAll
via aggregated queries (one join across inbounds + client_inbounds,
one over client_traffics intersected with the in-memory online
emails). The Nodes list renders these as colored chips on a new
"Clients" column so an operator can see at a glance how many users
each node carries and how many are currently online or depleted.
Also exposes the remote panel's version. The central panel adds
panelVersion to its /api/server/status payload (sourced from
config.GetVersion). Probe reads that field and persists it on the
node row, mirroring how xrayVersion already flows. NodesPage gets
a new column next to Xray Version, in both desktop and mobile
views, with English and Persian strings.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): stop node sync from resurrecting deleted clients
Several related issues around node-managed clients:
- Remote runtime: drop the per-inbound resetAllClientTraffics path
and point traffic/onlines/lastOnline fetches at the new
/panel/api/clients/* routes.
- Delete from master: always push the updated inbound to the node
even when the client was already disabled or depleted, so the
node actually loses the user instead of silently keeping it.
- setRemoteTraffic: mirror remote clients into the central tables
only on first discovery of a node inbound. Matched inbounds let
the master own the join table, so a stale snap can no longer
re-create a ClientRecord (and join row) for a client that was
just deleted on the master.
- ClientService.Delete: route through submitTrafficWrite so deletes
serialize with node traffic merges, and switch the final
ClientRecord delete to an explicit Where("id = ?") clause.
- setRemoteTraffic UNIQUE-constraint fix: use clause.OnConflict on
inserts and email-keyed UPDATEs for client_traffics, so mirroring
a snap doesn't trip the unique email index.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(clients): switch client API endpoints from id to email
All client-scoped routes now use the unique email as the path key
(get, update, del, attach, detach, links). Email is the stable,
protocol-independent identifier — UUIDs don't exist for trojan or
shadowsocks, and internal numeric ids leaked panel implementation
detail into the public API.
Removed the redundant /traffic/byId/:id endpoint (covered by
/traffic/:email) and collapsed /links/:id/:email into /links/:email,
which now returns links across every attached inbound for the client.
Frontend selection, bulk delete, and toggle state are now keyed by
email as well, dropping the id→email lookup workaround.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(server): move cached state and helpers into ServerService
ServerController had grown to hold its own status cache, version-list
TTL cache, history-bucket whitelist, and the loop that drove all three
— concerns that belong in the service layer. Pull them out:
- lastStatus + the @2s refresh become ServerService.RefreshStatus and
ServerService.LastStatus; the controller's cron now just orchestrates
the cross-service side effects (xrayMetrics sample, websocket broadcast).
- The 15-minute Xray-versions cache (with stale-on-error fallback) moves
into ServerService.GetXrayVersionsCached, collapsing the controller
handler to a single call.
- The freedom/blackhole outbound-tag walk used by /xraylogs becomes
ServerService.GetDefaultLogOutboundTags.
- The allowed-history-bucket whitelist moves to package-level
service.IsAllowedHistoryBucket, so both NodeController and
ServerController validate against the same list.
Net result: web/controller/server.go drops from 458 to 365 lines and
contains only HTTP wiring + presentation-y side effects.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* refactor(api): emit JSON-text columns as nested objects
Inbound, ClientRecord, and InboundClientIps store settings /
streamSettings / sniffing / reverse / ips as JSON-text in the DB. The
API was passing that text through verbatim, so every consumer had to
JSON.parse a string inside a string. Add MarshalJSON / UnmarshalJSON so
the wire format is a real nested object, while still accepting the
legacy escaped-string shape on write. Frontend dbinbound.js gets a
matching coerceInboundJsonField helper for the same dual-shape read
path, and inbound.js toJson stops emitting empty/placeholder fields
(externalProxy [], sniffing destOverride when disabled, etc.) so the
new normalised JSON stays terse. api-docs and the inbound-clone path
are updated to the new shape. Controller route lists are regrouped so
all GETs sit above POSTs.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): include inboundIds and traffic in /clients/list
ClientRecord got its own MarshalJSON in the previous commit, and
ClientWithAttachments embeds it to add inboundIds and traffic. Go
promotes the embedded MarshalJSON to the outer struct, so the encoder
was calling ClientRecord.MarshalJSON for the whole value and silently
dropping the extras. The frontend reads row.inboundIds / row.traffic
from /clients/list, so attached inbounds didn't render and newly added
clients looked like they hadn't saved. Add an explicit MarshalJSON on
ClientWithAttachments that splices the extras in.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): gate IP Log on ipLimitEnable + clean access-log dropdown
Legacy panel hid the IP Log section when access logging was off; the
Vue 3 migration left it gated on isEdit only, so the section showed
even when xray's access log was 'none' and nothing was being recorded.
Restore the ipLimitEnable gate on the edit modal's IP Log form-item.
While here, clean up the Xray Settings access-log dropdown: previously
two 'none' entries appeared (an empty value labelled with t('none') and
the literal 'none' from the options array). Drop the empty option for
access log (the literal 'none' covers it) and relabel the empty option
for error log / mask address to t('empty') so they're distinguishable.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(nodes): route per-client ops through node clients API + orphan sweep
Adds Runtime methods AddClient, UpdateUser, and DeleteUser so master
mutates clients on a node via /panel/api/clients/{add,update,del} rather
than pushing the whole inbound. The previous rt.UpdateInbound path made
the node DelInbound+AddInbound on every single-client change, briefly
cycling every other user on the same inbound.
DelInbound no longer filters by enable=true, so a disabled node inbound
actually gets removed from the node instead of being resurrected by the
next snap.
setRemoteTrafficLocked now sweeps any ClientRecord with zero
ClientInbound rows after SyncInbound rebuilds the attachments, which is
how a node-side delete propagates back to master instead of leaving a
detached ghost. ClientService.Delete tombstones the email first so a
snap arriving mid-delete can't re-create the record.
WebSocket broadcasts an "invalidate(clients)" message on every client
mutation so the Clients page refreshes without manual reload.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(balancers): allow fallback on all strategies + feed burstObservatory from random/roundRobin
Drops the random/roundRobin gate on the Fallback field in
BalancerFormModal so every strategy can pick a fallback outbound.
syncObservatories now feeds burstObservatory from leastLoad +
random + roundRobin balancers (was leastLoad only), matching how
leastPing feeds observatory.
Fix the JsonEditor "Unexpected end of JSON input" that appeared
when switching a balancer between leastPing and another strategy:
the obsView watcher was gated on showObsEditor (a boolean OR of
the two flags) and missed the case where one observatory
swapped for the other in the same tick. Watch the individual
flags instead so obsView flips to the surviving editor and the
getter stops pointing at a deleted key.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(inbounds): use sortedInbounds for mobile empty-state check
InboundList referenced an undefined visibleInbounds in the mobile
card list's empty-state guard, throwing "Cannot read properties of
undefined (reading 'length')" and breaking the entire mobile render.
* feat(clients): sortable table columns
Adds the same sortState / sortableCol / sortFns pattern InboundList
uses, wrapping filteredClients in sortedClients so sort composes with
the existing search/filter pipeline. Sortable: enable, email,
inboundIds (attachment count), traffic, remaining, expiryTime;
actions and online stay unsorted.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(shadowsocks): generate valid ss2022 keys and per-client method for legacy ciphers
The Add Client flow on shadowsocks inbounds was producing xray configs
that failed to start:
- 2022-blake3-* ciphers need a base64-encoded key of an exact byte
length per cipher. fillProtocolDefaults was assigning a uuid-style
string, which xray rejects as "bad key". Now the password is
generated (or replaced if invalid) via random.Base64Bytes(n) sized
to the chosen cipher.
- Legacy ciphers (aes-256-gcm, chacha20-*, xchacha20-*) require a
per-client method field in multi-user mode; model.Client has no
Method, so settings.clients was stored without one and xray failed
with "unsupported cipher method:". applyShadowsocksClientMethod
now injects the top-level method into each client on add/update,
and healShadowsocksClientMethods backfills it at xray-config-build
time so existing inbounds heal on the next start.
- xray/api.go ssCipherType switch was missing aes-256-gcm, which
fell through to ss2022 path.
- SSMethods dropdown now offers aes-256-gcm.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): preserve ClientRecord on inbound delete + filter Attached inbounds to multi-client protocols
Replace the global orphan sweep in setRemoteTrafficLocked with a
per-inbound diff cleanup: only delete a ClientRecord whose email
disappeared from a snap-tracked inbound (i.e. a node-side delete).
Inbounds that vanished entirely from the snap (e.g. admin deleted
the inbound on master) aren't iterated, so a client whose last
attachment came from that inbound is now left alone instead of
being deleted alongside the inbound.
ClientFormModal and ClientBulkAddModal now filter the Attached
inbounds dropdown to protocols that actually support multiple
clients: shadowsocks, vless, vmess, trojan, hysteria, hysteria2,
and portfallback (which routes through VLESS settings).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): make empty-state text readable on dark/ultra themes
The "No clients yet" empty state had a hardcoded black color
(rgba(0,0,0,0.45)) that vanished against the dark backgrounds.
Drop the inline color, let it inherit from the AntD theme, and
fade with opacity like the mobile card empty state already does.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(clients): client-first tgbot add flow, tgId field, lightweight inbound options
- tgbot: drop legacy per-protocol Add Client UI in favour of a client-first
multi-inbound flow. New BuildClientDraftMessage / getInboundsAttachPicker
let an admin pick one or more inbounds and submit a single client; per-
protocol secrets are now generated server-side via fillProtocolDefaults.
Drops awaiting_id/awaiting_password_tr/awaiting_password_sh state cases
and add_client_ch_default_id/pass_tr/pass_sh/flow callbacks. Adds a
setTGUser button + awaiting_tg_id state so the bot can set Client.TgID
during Add.
- clients UI: add Telegram user ID input to ClientFormModal (0 = none).
Hide IP Limit field entirely when ipLimitEnable is off — disabled fields
still take layout space, this collapses Auth(Hysteria) to full width.
- inbounds API: new GET /panel/api/inbounds/options that returns just
{id, remark, protocol, port, tlsFlowCapable}. Used by the clients page
pickers so the dropdown payload stays small on panels with thousands of
clients (drops settings JSON, clientStats, streamSettings). Server-side
TlsFlowCapable mirrors Inbound.canEnableTlsFlow so the modal no longer
needs to parse streamSettings client-side.
- clientInfoMsg now shows attached inbound remarks, and getInboundUsages
reports the attached client count per inbound.
- api-docs: document the new /options endpoint and add tgId / flow to the
clients add/update bodies.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(inbounds): keep Node column visible for node-attached inbounds
The Node column was bound to hasActiveNode, so disabling every node hid
the column even when inbounds were still attached to those nodes — the
admin lost the visual cue that those inbounds belonged to a node and
would come back when it was re-enabled. Combine hasActiveNode with a
new hasNodeAttachedInbound check (any dbInbound with nodeId != null) so
the column survives node-disable.
* fix(api-docs): accept functional-component icons in EndpointSection
AntD-Vue icons (SafetyCertificateOutlined, etc.) are functional
components, so the icon prop's type: Object validator was rejecting
them with a "Expected Object, got Function" warning at runtime.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* test: cover crypto, random, netsafe, sub helpers, xray equals, websocket hub, node service
Adds ~110 unit tests across previously untested packages. Focus on
pure-logic and concurrency surfaces where regressions would silently
affect users:
- util/crypto, util/random: password hashing round-trip, ss2022 key
generation, alphabet/length invariants.
- util/netsafe: IsBlockedIP edge cases, NormalizeHost validation,
SSRF guard with AllowPrivate context bypass.
- util/common, util/json_util: traffic formatter, Combine nil-skip,
RawMessage empty-as-null and copy-on-unmarshal.
- sub: splitLinkLines, searchKey/searchHost, kcp share fields,
finalmask normalization, buildVmessLink round-trip.
- xray: Config.Equals and InboundConfig.Equals field-by-field,
getRequiredUserString/getOptionalUserString type checks.
- web/websocket: hub registration, throttling, slow-client eviction,
nil-receiver safety, concurrent register/unregister.
- web/service: NodeService.normalize validation, normalizeBasePath,
HeartbeatPatch.ToUI mapping.
- web/job: atomicBool concurrent set/takeAndReset semantics.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* i18n(clients): replace English fallbacks with proper translation keys
Pulls every hard-coded English label/title in the Clients page and its
four modals through the i18n layer so localized panels stop leaking
English. New keys live under pages.clients (auth, hysteriaAuth, uuid,
flow, flowNone, reverseTag, reverseTagPlaceholder, telegramId,
telegramIdPlaceholder, created, updated, ipLimit) plus refresh at the
root and toasts.bulkDeletedMixed / bulkCreatedMixed for partial-failure
toasts. Also switches the add-client modal's primary button from "Add"
to "Create" for consistency with other create flows.
The bulk-add Random/Random+Prefix/... email-method options stay
hard-coded by request - they're identifier-shaped strings.
* i18n: backfill 99 missing keys across all 12 non-English locales
Brings every translation file up to parity with en-US.json so the
Clients page, the fallback-children inbound section, the new refresh
verb, the Nodes panel-version label and a handful of older holes stop
falling through to the English fallback. New strings span:
- pages.clients.* (labels, confirmations, toasts, emailMethods)
- pages.inbounds.portFallback.* (Reality fallback inbound section)
- pages.nodes.panelVersion, menu.clients, refresh
Technical identifiers (Auth, UUID, Flow, Reverse tag) are intentionally
left untranslated since they correspond to xray-core field names.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* i18n: drop stale pages.client block duplicated in every non-English locale
Every non-English locale carried a pages.client (singular) section with
30 entries that duplicated pages.clients (plural). The plural namespace
is what the Vue code actually consumes; the singular one was dead
weight from an older rename that never got cleaned up in the
non-English files. Removing it brings every locale to exactly 984
keys, matching en-US.json.
* chore: apply modernize analyzer fixes across codebase
Mechanical replacements suggested by golang.org/x/tools/.../modernize:
strings.Cut/CutPrefix/SplitSeq, slices.Contains, maps.Copy, min(),
range-over-int, new(expr), strings.Builder for hot += loops,
reflect.TypeFor[T](), sync.WaitGroup.Go(), drop legacy //+build lines.
* feat(database): add PostgreSQL as an optional backend alongside SQLite
Lets operators with large client counts or multi-node setups pick PostgreSQL
at install time without breaking the existing SQLite default. Backend is
selected at runtime via XUI_DB_TYPE/XUI_DB_DSN, a small dialect layer keeps
the five JSON_EXTRACT/JSON_EACH queries portable, and a new `x-ui migrate-db`
subcommand copies SQLite data into PostgreSQL in FK-aware order.
* fix(inbounds): gate node selector to multi-node-capable protocols
Hide the Deploy-To selector and clear nodeId when switching to a
protocol that can't run on a remote node. Also:
- subs: return 404 (not 400) when subId matches no inbounds, so VPN
clients distinguish "deleted/unknown" from a server error
- hysteria link gen: use the inbound's resolved address so node-managed
inbounds advertise the node host instead of the central panel
- shadowsocks: default network to 'tcp' (udp was causing issues for some
clients on first-create)
- vite dev proxy: rewrite migrated-route bypass against the live base
path instead of a hardcoded single-segment regex
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(clients): bulk add/delete correctness + perf, working pagination, delayed-start in form
Bulk add/delete were serial on the frontend (one toast per call, N round-trips)
and the backend race exposed by parallelizing them lost client attachments and
hit UNIQUE constraint failed on client_inbounds. The single add/edit modal also
had no Start-After-First-Use option, and the table never showed the delayed
duration.
Backend (web/service/client.go):
- Per-inbound mutex on Add/Update/Del InboundClient so concurrent writers on
the same inbound don't lose the read-modify-write of settings JSON.
- SyncInbound skips create+join when the email is tombstoned so a concurrent
maintenance pass (adjustTraffics, autoRenewClients, markClientsDisabledIn-
Settings) that did a stale RMW can't resurrect a just-deleted client with a
fresh id.
- compactOrphans sweeps settings.clients entries whose ClientRecord no longer
exists, applied in Add/DelInboundClient + DelInboundClientByEmail so each
user-initiated mutation self-heals the inbound's settings.
- DelInboundClient uses Pluck instead of First for the stats lookup so a
missing row doesn't abort the delete with a noisy ErrRecordNotFound log.
Frontend:
- HttpUtil.{get,post} accept a silent option that suppresses the auto-toast.
- ClientBulkAddModal fires creates in parallel + silent + one summary toast.
- useClients.removeMany runs deletes in parallel + silent and refreshes once;
ClientsPage bulk delete uses it and shows one aggregate toast.
- useClients.applyInvalidate debounces 200 ms so the burst of N WebSocket
invalidate events from the backend collapses into a single refresh.
- ClientsPage pagination is reactive (paginationState ref + tablePagination
computed); onTableChange persists page-size and page changes.
- ClientFormModal gains a Start-After-First-Use switch + Duration days input
alongside the existing Expiry Date picker; on edit-mode open a negative
expiryTime is decoded back to delayed mode + days; on submit the payload
sends -86400000 * days or the absolute timestamp.
- ClientsPage table shows the delayed-start duration (blue tag Nd, tooltip
Start After First Use: Nd) instead of infinity.
- Telegram ID field in the form is hidden when /panel/setting/defaultSettings
reports tgBotEnable=false; Comment then fills the row.
- Form row 3 collapses UUID (span 12) + Total GB (span 8) + Limit IP (span 4)
when ipLimitEnable is on, else UUID + Total GB at 12/12.
- useInbounds.rollupClients counts only clients with a matching clientStats
row, so orphans in settings.clients no longer inflate the inbound's count.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(windows): clean shutdown, working panel restart, harden kernel32 load
Three Windows-specific issues addressed:
1. Orphaned xray-windows-amd64 after VS Code debugger stop. Delve's
"Stop" sends TerminateProcess to the Go binary, which is uncatchable
— our signal handlers never run, so xrayService.StopXray() is skipped
and xray is left dangling. Spawn xray as a child of a Job Object with
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so the OS kills xray when our
handle to the job is closed (which happens even on TerminateProcess).
Also trap os.Interrupt in main so Ctrl+C in the terminal runs the
graceful path.
2. /panel/setting/restartPanel logged "failed to send SIGHUP signal: not
supported by windows" because Windows can't deliver arbitrary signals.
Add a restart hook in web/global; main registers it to push SIGHUP
into its own signal channel, and RestartPanel calls the hook before
falling back to the (Unix-only) signal path. Same restart-loop code
runs in both cases.
3. util/sys/sys_windows.go now uses windows.NewLazySystemDLL so the
kernel32.dll resolve is pinned to %SystemRoot%\System32 (prevents
DLL hijacking by a planted DLL next to the binary). Local filetime
type replaced with windows.Filetime, and the unreliable
syscall.GetLastError() fallback replaced with a type assertion on the
errno captured at call time.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(sys): correct CPU/connection accounting on linux + darwin
util/sys/sys_linux.go:
- GetTCPCount/GetUDPCount were counting the column header row in
/proc/net/{tcp,udp}[6] as a connection, inflating the reported total
by 1 per non-empty file (so the panel status line always showed 2
more connections than actually existed). Replace getLinesNum +
safeGetLinesNum with a single bufio.Scanner-based countConnections
that skips the header.
- CPUPercentRaw now opens HostProc("stat") instead of a hardcoded
/proc/stat so HOST_PROC overrides apply, matching the connection
counters in the same file.
- Simplify CPU field unpacking: pad nums to 8 once instead of guarding
every assignment with a len check.
util/sys/sys_darwin.go:
- Fix swapped idle/intr indices on kern.cp_time. BSD CPUSTATES order
is user, nice, sys, intr, idle (CP_INTR=3, CP_IDLE=4) — gopsutil's
cpu_darwin_nocgo.go reads the same layout. The previous code used
out[3] as idle and out[4] as intr, so busy = total - dIdle was
actually subtracting interrupt time, making the panel report CPU
usage close to 100% on macOS regardless of actual load.
- Collapse the per-field delta math into a single loop.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* fix(xray): rotate crash reports into log folder, prevent overwrites
writeCrashReport had two flaws: it wrote to the bin folder (alongside the
xray binary) which conflates artifacts, and the second-precision timestamp
meant a tight restart-loop crash burst overwrote prior reports. Write to
the log folder with nanosecond precision and keep the last 10 reports.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* revert(inbounds): drop unreleased portfallback protocol
The Port-with-Fallback inbound (commit 62fd9f9d) was confusing as a
standalone protocol — fallbacks belong on a regular VLESS/Trojan TCP-TLS
inbound, the way Xray models them natively. Rip out the entire feature
cleanly (no migration needed since it was never released): protocol
constant, fallback children DB table, FallbackService, 2 API endpoints,
all UI rows, related translations and api-docs. A native fallback flow
attached to VLESS/Trojan TCP-TLS/Reality will land in a follow-up commit.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* feat(inbounds): native fallbacks on VLESS/Trojan TCP-TLS, with working child links
A VLESS or Trojan inbound on TCP with TLS or Reality can now act as a
fallback master: pick existing inbounds as children and the panel auto-
fills the SNI / ALPN / path / xver routing fields from each child's
transport, auto-builds settings.fallbacks at config-gen time, and
rewrites the child's client-share link so it advertises the master's
reachable endpoint and TLS state instead of the child's loopback listen.
Layout matches the Xray All-in-One Nginx example: master at :443 with
clients + TLS, each child on 127.0.0.1 with its own transport+clients.
Order matters (Xray walks fallbacks top-to-bottom) — reorder via the
per-row up/down arrows. Path / SNI / ALPN are exposed under a per-row
Edit toggle for the rare cases where the auto-derivation needs
overriding; otherwise just pick a child and you're done.
Backend: new InboundFallback table + FallbackService (GetByMaster /
SetByMaster / GetParentForChild / BuildFallbacksJSON); two routes
(GET / POST /panel/api/inbounds/:id/fallbacks); xray.GetXrayConfig
injects settings.fallbacks for any VLESS/Trojan TCP-TLS/Reality
inbound; GetInbounds annotates each child with FallbackParent so the
frontend can rewrite links without an extra round-trip.
Link projection covers every emission path — clients-page QR/links,
per-inbound Get URL, raw subscription, sub-JSON, sub-Clash, and the
inbounds-page link/info/QR — via a shared projectThroughFallbackMaster
on the backend and a shared projectChildThroughMaster on the frontend
that both handle the panel-tracked relationship and the legacy
unix-socket (@vless-ws) convention.
Strings translated into all 12 non-English locales.
* docs: rewrite CONTRIBUTING with full local-dev setup
The prior three-line CONTRIBUTING left newcomers guessing at every
non-trivial step: which Go / Node versions, where xray comes from, why
the panel goes blank when XUI_DEBUG=true is flipped on, how the Vue
multi-page setup is wired, what to do on Windows when go build trips
on the CGo SQLite driver.
Now covers prerequisites, MinGW-w64 install on Windows (niXman builds
or MSYS2), one-shot first-time setup, two frontend dev workflows with
the XUI_DEBUG asset-cache gotcha called out, the architecture and
conventions of the Vue side, a project-layout map, useful env vars,
and the PR checklist.
---------
2026-05-19 10:16:42 +00:00
2026-05-19 11:09:35 +00:00
echo -e " ${ green } x-ui ${ tag_version } ${ plain } installation finished, it is running now... "
2023-02-09 19:18:06 +00:00
echo -e ""
2024-12-20 17:33:27 +00:00
echo -e " ┌───────────────────────────────────────────────────────┐
│ ${ blue } x-ui control menu usages ( subcommands) :${ plain } │
│ │
│ ${ blue } x-ui${ plain } - Admin Management Script │
│ ${ blue } x-ui start${ plain } - Start │
│ ${ blue } x-ui stop${ plain } - Stop │
│ ${ blue } x-ui restart${ plain } - Restart │
│ ${ blue } x-ui status${ plain } - Current Status │
│ ${ blue } x-ui settings${ plain } - Current Settings │
│ ${ blue } x-ui enable${ plain } - Enable Autostart on OS Startup │
│ ${ blue } x-ui disable${ plain } - Disable Autostart on OS Startup │
│ ${ blue } x-ui log${ plain } - Check logs │
│ ${ blue } x-ui banlog${ plain } - Check Fail2ban ban logs │
│ ${ blue } x-ui update${ plain } - Update │
2025-11-07 18:26:43 +00:00
│ ${ blue } x-ui legacy${ plain } - Legacy version │
2024-12-20 17:33:27 +00:00
│ ${ blue } x-ui install${ plain } - Install │
│ ${ blue } x-ui uninstall${ plain } - Uninstall │
2025-12-03 23:05:21 +00:00
└───────────────────────────────────────────────────────┘"
2023-02-09 19:18:06 +00:00
}
echo -e " ${ green } Running... ${ plain } "
install_base
2026-05-19 11:09:35 +00:00
install_x-ui $1