Compare commits

...

73 Commits

Author SHA1 Message Date
MHSanaei 5e9606aa4d fix(script): stop logging an error when Enter accepts the default ACME port
Pressing Enter at the 'Please choose which port to use (default is 80)' prompt left WebPort empty, and bash arithmetic treats an empty string as 0, so the out-of-range branch fired and printed 'Your input is invalid' even though the default was correctly applied. Handle empty input as accepting the default silently, and validate real input with a digits-only regex so non-numeric entries like '8x' get the invalid-input message instead of a bash arithmetic error. Applied to the identical prompt in x-ui.sh, install.sh, and update.sh.

Fixes #5829
2026-07-06 12:44:37 +02:00
MHSanaei f36f481e02 feat(db): add pgclient command to install or upgrade PostgreSQL client tools
Restoring a panel backup made by a newer pg_dump fails when the host's
pg_restore is older, and the existing pg_ensure_client only installs the
distribution package when the tools are missing - it can never upgrade,
and distribution repositories often cap below the required major.

Add pg_upgrade_client to x-ui.sh, exposed as 'x-ui pgclient [major]' and
as a PostgreSQL menu entry: it checks the installed pg_restore major,
tries the distribution package for the exact requested major first, and
falls back to the official PostgreSQL repository (apt on Debian/Ubuntu,
yum/dnf on Enterprise Linux, with a /usr/pgsql PATH symlink fallback);
Arch, Alpine and openSUSE install their current package. The panel's
dump-version mismatch error now names the ready-to-copy command with
the exact major parsed from the dump header.
2026-07-06 09:24:18 +02:00
MHSanaei de70ecb026 fix(db): probe dump readability before PostgreSQL import
pg_restore cannot read archives newer than itself, so importing a dump
made by pg_dump from PostgreSQL 17+ into a panel with an older
postgresql-client failed with a raw 'unsupported version (1.16) in file
header' - and only after Xray had already been stopped for the restore.

Probe the uploaded file with pg_restore --list first, which reads only
the archive TOC without touching the database, so an unreadable dump is
rejected before Xray is interrupted. When the failure is a dump-format
version mismatch, translate it into a message naming the PostgreSQL
version that produced the dump and the client version to install.
2026-07-06 09:01:19 +02:00
MHSanaei ed66209e38 feat(outbound): add real-delay connection test mode
The HTTP probe reports the warm per-request round-trip, which reads
lower than the delay figure client apps show for the same server. Add a
third "real" test mode that reuses the temp-instance HTTP probe but
reports the cold request's full elapsed time - tunnel establishment
included - and skips the warm request. UDP-transport outbounds forced
out of the TCP lane still report "http"; in real mode they report
"real". The mode joins the TCP/HTTP toggle on the outbounds tab, with
the label translated in all 13 locales.
2026-07-06 08:35:48 +02:00
MHSanaei 5a7b3b7370 fix(client): stop duplicate client entries accumulating in inbound settings
Adding a user to multi-node inbounds could leave 3-6 identical entries
in one inbound's settings.clients array: addInboundClient appended
incoming clients unconditionally, and the duplicate-email precheck
exempts a matching subId (so one identity can span several inbounds),
so a retried or raced add of the same client re-appended it to an
inbound that already carried it - on the master and, since nodes run
the same code, on every node, whose snapshot adoption then copied the
duplicates back verbatim. The normalized clients/client_inbounds tables
stayed clean (unique constraints), which is why the phantom rows only
showed in settings-driven views like the Detach clients modal, where
duplicate React keys also broke the selection counter.

Three layers: addInboundClient now skips incoming clients whose email
is already on the target inbound (idempotent re-adds instead of
duplication), node snapshot adoption collapses duplicate emails before
writing the central row, and an idempotent startup repair rewrites any
inbound whose settings still carry duplicates from older builds.

Closes #5770
2026-07-05 21:17:25 +02:00
MHSanaei 9d1a21b484 fix(ui): keep an explicit zero happy-eyeballs delay across the round trip
Follow-up found in review: the wire normalizer still stripped
tryDelayMs when it equaled 0, but with the schema default now 250 a
reload rehydrates the missing field as 250 - a user who explicitly set
0 ("disabled", per the field's own placeholder) would see 250 and any
subsequent save would silently enable a delay they turned off. Keep
tryDelayMs on the wire unconditionally; it is the one happy-eyeballs
field whose presence changes xray's behavior.

Refs #5780
2026-07-05 21:17:12 +02:00
MHSanaei 0753f5ee83 fix(link): reject non-finite and clamp out-of-range quicParams from fm=
Follow-up hardening of the fm= sanitizer found in review. ParseFloat
accepts "inf"/"NaN", and a non-finite float64 makes json.Marshal fail
later - the subscription refresh discards that error and blanks the
stored outbound set, so one poisoned link could wipe a subscription's
outbounds. Values that coerce fine but sit outside xray-core's accepted
ranges (keepAlivePeriod 0 or 2-60, maxIdleTimeout 0 or 4-120,
maxIncomingStreams 0 or >= 8) still killed the config load, and huge
magnitudes serialize in exponent notation that xray's integer fields
reject. Coerced values are now stored as integers, clamped into the
accepted ranges, and dropped when negative, non-finite, or absurdly
large; the TS import parser mirrors the same rules.

Refs #5783
2026-07-05 21:16:56 +02:00
MHSanaei 837cf5f24e fix(db): clamp traffic counters below int64 max and repair overflowed rows
A counter pushed past int64 (multi-node setups hit this via historic
delta-compounding bugs) makes SQLite silently promote the INTEGER cell
to REAL. From then on the column no longer scans into the Go int64
field and every reader of client_traffics fails at once: the inbounds
page, xray restarts, and node traffic sync all return "converting
driver.Value type float64 to int64".

Two-part fix: every unbounded "up = up + ?" add (local traffic, node
delta merge, inbound counters, plus the Go-side outbound accumulation)
now saturates at TrafficMax, a cap safely below math.MaxInt64 so one
more delta cannot overflow; and a startup repair casts REAL-promoted
cells back to INTEGER and clamps all traffic counters into
[0, TrafficMax] across client_traffics, inbounds, outbound_traffics
and node_client_traffics, restoring access to already-corrupted panels
without manual sqlite surgery.

Closes #5762
2026-07-05 20:33:09 +02:00
MHSanaei b1fa76f9b6 fix(node): fully delete clients on nodes instead of only detaching them
Deleting a client on the master propagated to nodes via the detach
endpoint, which removes the client from that one inbound's settings but
deliberately keeps the client record. The node ended up with an
orphaned record that kept showing in its Clients view; the master and
node could never converge on a delete.

Full-delete and detach intent now travel separately: the Runtime
interface gains DeleteClient, which on Remote hits the node's
panel/api/clients/del endpoint (record, attachments, traffic; repeat
calls for a client on several inbounds of the same node are swallowed
as idempotent "not found"). Delete/DeleteByEmail/BulkDelete use it for
node inbounds, while Detach/BulkDetach keep the inbound-scoped detach
RPC so removing a client from one inbound never wipes it node-wide
(the #5543 guarantee is preserved and covered by tests). Bulk deletes
above the fold threshold still converge membership via reconcile; their
leftover node records can be cleaned with the node's delete-orphans
action.

Closes #5797
2026-07-05 20:28:26 +02:00
MHSanaei b6873c7a73 fix(outbound): measure HTTP test delay on a warm connection
Since the batched prober replaced the single tester, the reported delay
came from one cold request with keep-alives disabled, so it stacked the
SOCKS handshake, proxy dial, proxy TLS, target TCP and target TLS on top
of the round-trip. Users upgrading from v2.9.4 - whose tester warmed the
connection first and timed a second request - saw several times the real
connection time.

The cold request still proves reachability and supplies the HTTP status
plus the connect/TLS/TTFB breakdown; the delay is now re-measured on a
second request over the kept-alive connection, falling back to the cold
total when the warm request fails. Bodies are drained (bounded) so the
connection returns to the pool, and the batch test asserts both requests
of a probe share one connection.
2026-07-05 20:19:25 +02:00
MHSanaei b6183271da fix(tgbot): find clients by tgId regardless of settings JSON formatting
The Telegram-bot usage lookup prefiltered inbounds with
settings LIKE '%"tgId": N%', which requires the exact space the panel's
MarshalIndent happens to emit. Inbounds whose settings were serialized
compactly (node sync, imports, external edits) never matched, so the
bot reported no configuration even though the client and traffic rows
exist. Replace the string match with the driver-portable JSON helpers
already used by GetAllEmails, which read the actual clients array on
SQLite and Postgres alike.

Closes #5805
2026-07-05 20:18:59 +02:00
MHSanaei 11e45e81b6 fix(link): sanitize numeric quicParams taken from a share link's fm= param
The fm= finalmask blob was JSON-decoded and attached to streamSettings
verbatim, both by the Go parser (outbound subscriptions) and the
frontend import. Some providers emit duration strings for the strictly
integer quicParams fields (e.g. keepAlivePeriod "10s"), and xray-core
then refuses to load the whole config at startup - one bad subscription
entry took the panel's Xray down on the next refresh. Coerce numeric
strings, convert duration strings to whole seconds, and drop values
that cannot be represented as integers; genuinely string-typed fields
(congestion, bbrProfile, brutalUp/Down, udpHop) pass through untouched.

Closes #5783
2026-07-05 20:16:57 +02:00
MHSanaei 579a9daaa0 fix(ui): make the Happy Eyeballs toggle produce a config xray actually enables
Toggling Happy Eyeballs on filled the object with schema defaults, and
tryDelayMs defaulted to 0. That broke the feature twice over: xray-core
treats tryDelayMs=0 as happy-eyeballs-off, and the wire normalizer
strips every field that equals its default, leaving an empty object it
then deletes - so the switch silently flipped back off on reopen (the
"disabled when Prefer IPv6 is off" symptom; prioritizeIPv6=true was the
one non-default that let the object survive). Default tryDelayMs to the
recommended 250ms so an enabled config survives serialization and is
functional in the core.

Closes #5780
2026-07-05 20:12:34 +02:00
MHSanaei 0add63984f fix(ui): align the subUpdates limit with the backend and show the range
The hand-written settings schema capped subUpdates at 168 while the
backend (and the generated schema mirrored from it) accepts 0-525600.
Anyone upgrading from 2.x with a stored value above 168 could no longer
save any settings tab: the whole settings object is validated on every
save, so the stale field blocked everything with an unexplained
"Invalid input". Match the backend bounds and put them on the input so
the limit is discoverable.

Closes #5821
2026-07-05 20:12:21 +02:00
MHSanaei b6d1caf95d fix(script): rename the Xray binary to xray-linux-arm32 on 32-bit ARM
The panel maps GOARCH=arm to "arm32" and launches bin/xray-linux-arm32,
but install.sh/update.sh renamed the release tarball's binary
(xray-linux-armv5/v6/v7) to xray-linux-arm. On armv7 boxes every update
downloaded a fresh Xray core into a name the panel never executes, so an
old correctly-named binary kept running forever, and a brand-new install
had no launchable Xray binary at all. Rename to arm32 to match the panel
(mtg stays plain "arm", matching internal/mtproto), and drop the stale
misnamed xray-linux-arm during updates like the existing amd64 cleanup.

Closes #5788
2026-07-05 20:08:10 +02:00
MHSanaei 1bf9e5d544 fix(script): make local PostgreSQL and fail2ban setup work on RHEL-family distros
Fresh installs on Rocky/Alma/RHEL/Oracle failed twice (#5806):

- postgresql-setup --initdb ships a pg_hba.conf whose TCP rules use ident
  auth, which matches the OS username against the Postgres role and always
  rejects the randomly generated panel role, so the panel could never
  connect ("Ident authentication failed"). Prepend password-auth rules
  scoped to the panel database (first match wins; md5 also accepts
  scram-stored verifiers) and reload, in both install.sh and the x-ui.sh
  mirror.

- fail2ban only exists in EPEL on the RHEL family, but only the CentOS 7
  branch enabled EPEL, so IP Limit setup failed with "No match for
  argument: fail2ban". Enable epel-release (with the dl.fedoraproject.org
  package as fallback for RHEL proper) before installing; Fedora ships
  fail2ban in its own repos and is skipped.

Closes #5806
2026-07-05 20:06:08 +02:00
MHSanaei 26e88c7b10 fix(script): stop running full system upgrades via pacman -Syu on Arch
Installing or updating the panel on Arch/Manjaro/Parch performed a full
system upgrade (pacman -Syu) instead of only refreshing the package
database and installing the needed packages, unlike every other distro
branch (apt-get update, dnf makecache, zypper refresh, apk update).
Unrequested full upgrades can pull in kernel and system updates the
user never asked for. Align all pacman calls on the -Sy --noconfirm
form already used elsewhere in these scripts.

Closes #5810
2026-07-05 20:03:11 +02:00
MHSanaei a0989e0f4d fix(node): stop client edits from tearing down node inbounds and harden reconcile fingerprints
A client save on the master always stamped a fresh updated_at, marked
the node dirty, and let the 5s sync push a full inbounds/update to the
node, where applying it removes and re-adds the Xray handler - killing
live traffic on every edit, including no-op saves (open the editor,
click Save). Nodes stayed online with Xray running while forwarding
nothing until a manual Xray restart.

- No-op client saves preserve the client's updated_at and return before
  any DB write, runtime RPC, or node dirty mark when the effective
  settings did not change.
- Successful per-client add/update/delete pushes advance the node's
  reconcile-skip fingerprint only when the recorded fingerprint proves
  the node held the exact pre-edit payload and every push in the edit
  succeeded (Remote.AdvancePushedInbound). Anything unproven keeps the
  stale fingerprint so the dirty reconcile still sends the full inbound.
  Unconditional stamping would certify folded bulk changes (threshold,
  flow change, offline edit) or partially failed batches as delivered:
  a folded 41->6 bulk delete followed by one live edit left the node
  permanently serving all 41 clients in end-to-end testing, with the
  snapshot adoption then resurrecting the deleted clients on the master.
- DeleteUser treats only an envelope-level not-found as already deleted;
  an HTTP 404 from an old node build without the detach endpoint
  surfaces as an error instead of certifying an undelivered delete.
  cacheDel drops the fingerprint alongside the id cache so DelInbound
  and tag renames leave no stale skip entry.
- Adopting the node's own settings serialization into the master row now
  also stamps the fingerprint (RecordAdoptedInbound). Without it the
  serialization round-trip invalidated the fingerprint one sync tick
  after every push, so each edit degraded back to a full teardown push.
- UpdateInboundClient applies the Shadowsocks method normalization
  before the no-op comparison (real method changes bump updated_at, SS
  no-op edits are detected) and syncs the generated subId into the
  pushed client so the node cannot mint a different one.

Verified with a two-panel docker deployment: no-op saves produce zero
node requests, real edits send one lightweight clients/update RPC with
zero full inbound updates and zero handler teardowns, and folded bulk
deletes still converge.

Based on PR #5778 by @rqzbeh.

Closes #5764
Closes #5771
2026-07-05 02:06:58 +02:00
alaningtrump 07d66aa6dc refactor: use the built-in max/min to simplify the code (#5751)
Signed-off-by: alaningtrump <alaningtrump@outlook.com>
2026-07-05 01:58:18 +03:00
Nikan Zeyaei b177e30714 feat(ui): client-realtime-speed (#5687)
* refactor(inbounds): extract TRAFFIC_POLL_INTERVAL_S to shared util

* feat(clients): derive per-client live speed from traffic WebSocket deltas

* feat(clients): render speed column and mobile card line

* i18n(clients): add pages.clients.speed key to all 13 locales
2026-07-05 01:57:03 +03:00
lxk955 e11e587c60 fix(script): correct hardcoded menu option numbers in x-ui.sh (#5787)
* fix(script): correct hardcoded menu option numbers in x-ui.sh

The error messages referenced option 19 for SSL Certificate Management
and option 16 for Logs Management, but the actual positions in show_menu
are 20 and 17 respectively.

* Update x-ui.sh
2026-07-04 23:09:56 +02:00
MHSanaei 5c725df702 fix(ci): pin the tag smoke test to the release under test
The v3.4.2 tag push triggered the smoke workflow immediately, but
install.sh with no arguments resolves releases/latest, which still pointed
at v3.4.1 while release.yml was uploading the new assets. The green smoke
run therefore validated the previous release (#5756). A paths filter alone
cannot exclude tag pushes because a brand-new tag ref has no diff base.

Restrict the push trigger to branches so tag pushes no longer start the
unpinned job, and add a workflow_run job that fires after the release
workflow completes for a v* tag: it checks out the tagged commit, passes
the tag through smoke-noninteractive.sh into install.sh's explicit-version
path, and asserts the installed binary reports exactly that version.

Closes #5756
2026-07-03 10:21:46 +02:00
MHSanaei d105b2741c fix(node): stop one rejected inbound from starving a node's traffic sync
A legacy socks inbound (predating the socks-to-mixed protocol rename) fails the node's request validation when pushed. ReconcileNode aborted on the first failed inbound and syncOne then skipped the traffic snapshot entirely and never cleared ConfigDirty, so the whole node re-failed every tick and the master stopped deducting traffic for every client on that node, exactly as reported in #5685.

Three-part fix: ReconcileNode now pushes every inbound and runs the delete sweep even past individual failures, returning the failures joined; syncOne logs a failed reconcile but continues with the traffic pull (dirty stays set, so reconcile retries and the merge stays in its conservative mode); and a migration renames legacy socks inbounds to mixed, which has an identical settings shape, removing the known trigger.

Closes #5685
2026-07-03 09:47:30 +02:00
MHSanaei 05cb70d8a8 feat(frontend): add text search to the inbound list
The v2.x panel could filter inbounds but the list page only had the node dropdown. Add a search box next to it matching on remark, port, and protocol, composed with the node filter; the dataset is already client-side, so no API change.

Closes #5267
2026-07-03 09:40:04 +02:00
MHSanaei 323cf09d10 feat(sub): show the announcement on the subscription info page
The subAnnounce setting was only emitted as a base64 Announce response header, which most client apps ignore and browsers never see. Pass it into the sub page view-model and render it as an info alert at the top of the card; custom themes get the announce key for free.

Closes #5276
2026-07-03 09:38:37 +02:00
MHSanaei 1f04912b6f feat(tgbot): register usage, inbound, restart and clearall in the bot command menu
The Telegram command menu listed only start/help/status/id although usage, inbound and restart were already handled, and resetting all traffic was reachable only through inline keyboards. Register all handled commands with localized descriptions and add an admin-gated /clearall command that reuses the existing reset-all confirmation keyboard, so nothing destructive runs without an explicit confirm.

Closes #5307
2026-07-03 09:36:53 +02:00
MHSanaei 220dcb1579 feat(tgbot): show inbound remark alongside email in the online clients list
Online-client buttons showed only the email, which is ambiguous when the same usernames exist across inbounds. Label each button email - remark via the canonical GetClientInboundByEmail lookup (first matching inbound for multi-inbound clients); the callback payload stays the bare email.

Closes #5318
2026-07-03 09:33:29 +02:00
MHSanaei a13a79b230 fix(docker): start crond and persist acme.sh state so cert renewal works
The image shipped busybox crond but the entrypoint never started it, and the acme.sh crontab entry vanished on every container recreation, so certificates issued via the panel's SSL menu silently expired after 90 days. The entrypoint now re-registers the acme.sh cron job and starts crond when acme.sh is installed, and docker-compose gains an acme volume so renewal state survives recreation.

Closes #5116
2026-07-03 09:32:28 +02:00
MHSanaei ff3bd63656 feat(sub): serve the HTML info page for browser requests on JSON and Clash URLs
Opening the /json or /clash subscription URL in a browser dumped raw JSON/YAML while the base64 URL rendered the info page. Extract the browser-detection and page-rendering branch from subs into maybeServeSubPage and run it first in all three handlers, so every subscription URL shows the same info page in a browser while client apps keep receiving the raw body.

Closes #5348
2026-07-03 09:31:00 +02:00
MHSanaei 052dd85ad3 feat(clients): hide disabled inbounds in the client form selector
The attach-inbounds select in the client add/edit modal listed every inbound, so panels with many disabled inbounds had to scroll past dead entries. InboundOption now carries the inbound's enable flag and the form drops disabled inbounds from the options, keeping ones the client is already attached to so edit mode still renders existing assignments.

Closes #5645
2026-07-03 09:26:06 +02:00
MHSanaei b2ceb854f5 feat(tgbot): include hostname in backup and ban-log messages
Backup and ban-log pushes carried no server identity, so admins running the bot against several panels could not tell which server a backup came from. Prepend the same hostname line the periodic report and event notifications already use; the tgbot.messages.hostname key exists in all locales, so no new i18n keys are needed.

Closes #5387
2026-07-03 09:23:07 +02:00
MHSanaei dd4f55f690 feat(frontend): add text search to node select components
Typing in the Deploy To select of the inbound form and the node filter select on the inbound list now filters nodes by label, matching the showSearch convention used elsewhere (NodeFormModal, HostFormModal). With 20+ nodes, scrolling was the only way to find one.

Closes #5743
2026-07-03 09:14:40 +02:00
Grigoriy f90e4a6962 fix(panel): use the hosting node address for WireGuard client configs (#5679)
* fix(panel): use the hosting node address for WireGuard client configs

The clients page rendered a node-managed WireGuard inbound's config with the
master panel's host in Endpoint instead of the hosting node's address, so the
copied/QR config pointed at the wrong server. The subscription path already
resolves this via resolveInboundAddress; the UI generator did not.

Expose the share-host resolution inputs (node address, listen, share-address
strategy/address) on InboundOption and route buildWireguardClientConfig through
the same canonical resolver the inbounds-page share links use, extracted as
resolveShareHost. This also brings local inbounds with a shareable listen or a
listen/custom share strategy into parity with the subscription Endpoint; the
common listen=0.0.0.0 case still falls back to the panel host.

* fix(frontend): keep a raw fallback host and refresh node-fed inbound options

Code review of the WireGuard node-endpoint change surfaced two gaps.
resolveShareHost normalized its last-resort fallbackHostname, so a panel
reached via a hostname the share-host grammar rejects (underscore label,
trailing-dot FQDN) emitted a broken 'Endpoint = :51820'; the fallback now
stays verbatim when normalization empties it. Node mutations only
invalidated the nodes query, leaving the staleTime-Infinity inbound
options cache serving an edited node address until the sync job
broadcast (never, for disabled/offline nodes); they now invalidate the
options key too.

Also folds the ShareHostFields projections into direct structural passes,
elides the default node shareAddrStrategy so omitempty drops it, and
replaces the nullable node-address scan with COALESCE.

---------

Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-07-03 01:12:32 +02:00
Nebulosa dbdecda03f Env vars example file update (#5678)
* Update .env.example

* Update .env.example

* Update .env.example

* Update .env.example
2026-07-03 00:28:13 +02:00
Volov Vyacheslav 6e0067fca3 docs(settings): clarify Sub Port/Sub Domain double as subscription-link fallback (#5721)
* docs(settings): clarify Sub Port/Sub Domain double as subscription-link fallback

subPort/subDomain are documented purely as the subscription service's own
listen address, but when "Reverse Proxy URI" is empty, GetDefaultSettings
silently reuses them (with the admin API request's own Host header as the
domain fallback) to build the subscription link/QR shown in the panel.
Behind a reverse proxy where the sub service listens on an internal port
and is exposed externally on a different port/domain, this produces a
broken link even though "Reverse Proxy URI" already solves it - nothing
in the UI text pointed to it. Clarify all locales.

* docs(settings): fix wording nits from review (punctuation, CJK parens, es-ES field name)

- en-US/id-ID/pt-BR/tr-TR/uk-UA/ar-EG: add terminating punctuation before
  the appended sentence so it doesn't run on directly after the closing
  parenthesis.
- zh-CN/zh-TW/ja-JP: restore full-width CJK parentheses around the
  pre-existing parenthetical, matching the rest of each file.
- es-ES: subURIDesc referenced "Dominio/Puerto de escucha", but the
  actual field labels in this locale are "Dominio de Escucha" and
  "Puerto de Suscripción".

---------

Co-authored-by: Volov <volovdata@google.com>
2026-07-03 00:03:35 +02:00
Vitaliy Pavlov ed95acdd47 fix(scripts): avoid rpm package upgrades before installs (#5750) 2026-07-03 00:01:54 +02:00
MHSanaei 1afab47f04 feat(frontend): show client group in the client info modal
The group label was already on ClientRecord but the info modal never
displayed it. Add a conditional row next to the comment, rendered as a
geekblue tag to match the group column in the clients table.
2026-07-02 23:58:58 +02:00
MHSanaei 258d8b7344 feat(frontend): add targetStrategy field to the outbound editor
Xray-core added a top-level targetStrategy to OutboundObject that
controls how the destination domain is resolved before dialing
(AsIs/UseIP*/ForceIP*, any protocol). The panel neither offered a
control for it nor preserved the key across the modal's JSON round
trip, so hand-written values were silently dropped on save.

The form now carries targetStrategy next to sendThrough as a select
of the 11 canonical values; the adapter normalizes wire values to
canonical case (the core matches case-insensitively) and omits the
key when unset. Freedom settings additionally read the new
settings-level targetStrategy with domainStrategy as fallback,
mirroring the core, while still emitting the legacy domainStrategy
key so configs keep working on older cores.
2026-07-02 23:03:43 +02:00
MHSanaei 9f760cf0fa fix(frontend): stop group modals clearing selection on background refetch
The reset effect in GroupAddClientsModal and GroupRemoveClientsModal
depended on the memoized rows, which are rebuilt whenever GroupsPage
re-renders because candidates/members are inline-filtered arrays. The
5s client-list poll re-renders the page, so any selection made in the
modal was wiped a few seconds later. Reset only when the modal opens.
2026-07-02 23:00:04 +02:00
MHSanaei 1bf6f606bc refactor(sub): drop unused subReq parameter from genHy
genHy reads inbound settings directly via json.Unmarshal and never
touched subReq; the parameter was only added for signature uniformity
with genVless/genServer in 7c12700c.
2026-07-02 22:01:42 +02:00
dependabot[bot] ccd56a56a8 chore(deps): bump github.com/klauspost/compress from 1.18.6 to 1.19.0 (#5731)
Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.18.6 to 1.19.0.
- [Release notes](https://github.com/klauspost/compress/releases)
- [Commits](https://github.com/klauspost/compress/compare/v1.18.6...v1.19.0)

---
updated-dependencies:
- dependency-name: github.com/klauspost/compress
  dependency-version: 1.19.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-02 18:27:34 +02:00
dependabot[bot] 7a844682b3 chore(deps): bump github.com/shirou/gopsutil/v4 from 4.26.5 to 4.26.6 (#5730)
Bumps [github.com/shirou/gopsutil/v4](https://github.com/shirou/gopsutil) from 4.26.5 to 4.26.6.
- [Release notes](https://github.com/shirou/gopsutil/releases)
- [Commits](https://github.com/shirou/gopsutil/compare/v4.26.5...v4.26.6)

---
updated-dependencies:
- dependency-name: github.com/shirou/gopsutil/v4
  dependency-version: 4.26.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-02 18:26:39 +02:00
dependabot[bot] 6626bf4a07 chore(deps): bump google.golang.org/grpc from 1.81.1 to 1.82.0 (#5729)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.81.1 to 1.82.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.81.1...v1.82.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-version: 1.82.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-02 18:26:13 +02:00
MHSanaei c0df365524 chore(frontend): bump minor npm deps
Update frontend dependencies to newer patch/minor versions in package.json and refresh package-lock accordingly. This includes runtime libraries (i18next, react-router-dom, recharts) and tooling updates (typescript-eslint, vite) to keep the frontend stack current and aligned.
2026-07-02 18:24:09 +02:00
Vitaliy Pavlov 5361b56e5e fix(update): avoid full dnf system upgrade (#5717) 2026-07-02 18:20:15 +02:00
nima1024m 9e13b32c34 fix: make all self-managed file downloads/installs atomic, with real completion status (#5711)
* fix(script): download the live x-ui.sh script atomically before replacing it

update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote
/usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same
inode a currently-running x-ui process may still be reading from. A
network hiccup or slow write during that overwrite leaves a
half-old/half-new script on disk, which then fails with bogus syntax
errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into
place instead, matching the atomic pattern install.sh already uses.

Also fixes update_menu() checking chmod's exit code instead of curl's,
which meant a failed download could still report "Update successful."

* fix(script): close remaining gaps in the atomic script-update path

Code review of the previous commit found the atomic mv fix was itself
incomplete:

- None of the mv -f calls checked their exit status, so a failed move
  fell through to chmod and "success" messaging while /usr/bin/x-ui
  stayed on the old file.
- update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z
  got a 304, nothing to do" from "a stale temp file survived an
  earlier crashed run" -- the latter could get moved into place with
  no freshness check.
- update_menu(), update_shell(), and update_x-ui() all hardcoded the
  same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a
  cron auto-update racing an interactive menu update) could collide.
- update.sh's update_x-ui() was missing the non-empty-file guard
  update_shell() already had.

x-ui.sh's update_menu() and update_shell() now share a
replace_xui_script() helper that uses a PID-suffixed temp path
(/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and
checks the exit status of curl, the non-empty test, and mv before
treating the update as successful. update.sh's update_x-ui() gets the
same sequence inlined (it's fetched as a standalone script and can't
call x-ui.sh's function), closing the missing-guard gap and using its
own unique temp path.

* fix(script,panel): harden the remaining self-update download paths

install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two
already-fixed scripts had: no exit-status check on mv, and a fixed temp
name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it
its own PID-suffixed temp path, an empty-file guard, and an mv
exit-status check, matching the pattern used there.

Audited the web dashboard's Go-native updater (panel.go) for the same
bug class: it already uses os.CreateTemp for a genuinely unique temp
file and cleans up via both a deferred Remove and a shell EXIT trap, so
it was never exposed to the fixed-path race. It was missing a check
for a zero-byte download (a 200 OK with an empty body would chmod +x
and exec an empty script) -- added that alongside the existing size
cap.

Not addressed here: once startUpdate()'s child process starts, the Go
service releases it and returns success immediately. If update.sh
fails partway through, the still-running old panel keeps answering
/status, so the frontend's poll can report success with no update
having happened. Fixing that needs update.sh to signal completion
status back and the frontend to check it -- a separate follow-up.

* feat(panel): report real completion status for the web self-update

Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once
startUpdate() launches update.sh detached, the Go service had no way to
learn whether it actually succeeded. If update.sh failed partway
(network drop, disk full, permission denied), the still-running old
panel kept answering /status, so the frontend's poll reported success
with nothing having changed.

update.sh now writes its outcome to a small JSON status file
(/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which
covers every exit path in the script -- including the two bare `exit 1`
call sites that don't go through the existing _fail() helper. The Go
service generates a run ID before launching, passes it and the status
path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a
new GET /panel/api/server/getUpdateStatus endpoint reports it back. The
frontend now polls that instead of blindly trusting HTTP reachability,
and shows a distinct error or "couldn't confirm" message instead of
silently reloading into a false success.

Adversarial review of this surfaced three more issues, fixed here:
- No lock stopped two concurrent /updatePanel calls from launching two
  update.sh runs that would race each other on the actual update work
  (tar extraction, service unit swap). Added an in-memory guard with a
  5-minute self-expiring window, so a run that never reaches a terminal
  state doesn't lock out retries indefinitely.
- XUI_UPDATE_RUN_ID is read from the environment and was interpolated
  unquoted into the status JSON; a malformed value would produce
  invalid JSON. Now validated as digits-only before use.
- The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON
  number it would lose precision in JavaScript (past
  Number.MAX_SAFE_INTEGER), letting two different runs round to the
  same value on the wire and defeat the whole comparison. It's now a
  decimal string end to end (Go, the status file, and the generated
  frontend type).

install.sh's equivalent temp-file/mv path and the Go-native
downloadPanelUpdater() path were audited for the same bug classes
during this work; findings from that audit were addressed separately.

* fix(panel): release the update lock as soon as the run finishes

An exhaustive multi-angle review of the whole branch (12 finder angles,
3-vote adversarial verification, a fresh-eyes sweep) surfaced a real
bug in the concurrency guard added in the previous commit, plus several
smaller issues; this fixes what's actionable now.

The bug: acquireUpdateSlot only ever released on the 5-minute stale
timeout or if launching itself failed. If update.sh launched fine but
failed fast (bad GitHub API response, "x-ui not installed", any of its
early exit paths), the status file correctly reported "failed" within
seconds, but a retry was still rejected with "a panel update is
already in progress" for up to 5 more minutes -- the guard never
looked at the very status file this branch built to know a run was
done. It now tracks which run ID currently holds the slot and checks
that run's own status before falling back to the timeout, so a fast
failure clears the way for an immediate retry. Added a regression test
for this, plus one confirming a stale, unrelated runID can't be
mistaken for the current run finishing.

Also:
- Added a genuinely concurrent test for the guard: 200 goroutines
  racing acquireUpdateSlot, asserting exactly one wins. The previous
  tests only ever called it from one goroutine, so they gave no signal
  if the mutex's check-then-set were silently broken -- verified this
  by temporarily removing the lock and confirming the old tests still
  passed while the new one caught it immediately under -race.
- Removed the redundant upfront "pending" status write: GetUpdateStatus
  already defaults a missing/stale file to pending, and the frontend
  matches by run ID regardless, so the write changed no observable
  behavior. Deleted writeUpdateStatus entirely since that was its only
  caller.
- Renamed replace_xui_script()'s unclear "conditional" parameter to
  use_if_modified_since, matching what it actually controls.
- Added HTTP-level tests for the new getUpdateStatus endpoint,
  including a regression test that the runId wire format is a JSON
  string (decoding into a Go string field fails outright if it were
  ever a bare number). updatePanel's actual launch path is not
  covered: on a Linux test runner it would make a real network call
  and could exec a real update.sh, so only its non-Linux guard path is
  safely testable without mocking.

Not fixed here, tracked separately: the same unsafe-overwrite pattern
this branch eliminated for /usr/bin/x-ui is still present for the
systemd unit file install in update.sh and install.sh (lower severity
since systemd only reads it on daemon-reload, not continuously); and
startUpdate's systemd-run-vs-detached-fallback branching has no test
coverage since testing it safely needs dependency injection this fix
doesn't warrant bundling in.

* fix(script): make systemd unit file installation atomic

Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every
site that lands the systemd unit at ${xui_service}/x-ui.service --
copying it from the extracted release tarball, or falling back to a
GitHub download per distro family -- wrote straight onto the live
path via cp/curl, no temp file, no verification. A network drop
mid-download or an interrupted cp leaves the unit file truncated;
systemd then fails to parse it on the next daemon-reload/start,
leaving the panel unable to come up until an operator manually
re-copies a good unit file.

Lower severity than the /usr/bin/x-ui case (systemd only reads this
file on demand at daemon-reload time, not continuously the way bash
interprets a running script line by line), but it's the identical
gap, just left uncovered when that fix landed.

Added a small shared helper in both update.sh and install.sh --
_install_xui_service_unit() -- covering both source types (cp from
the tarball, curl from GitHub): write to a PID-suffixed temp file,
verify the copy/download succeeded and the result is non-empty, then
mv -f into place and check that exit status too, matching the pattern
already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl
fallback in each file now go through it; verified no other site
writes new content to the unit path (the remaining ${xui_service}
references are a pre-install existence check, an rm during old-version
cleanup, and the chown/chmod that already ran after the file is safely
in place -- none of those need atomicity).

Verified with bash -n on both files, plus a standalone scratch test
exercising cp-success, cp-with-missing-source, cp-with-empty-source,
and curl-failure paths: on every failure the previous, good unit file
content is left untouched and no temp file is leaked behind.

* fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment

A final maximum-rigor review of the whole PR (12 finder angles including
a repo-wide sweep for any remaining instance of the bug class this PR
fixes) found two more real issues:

- Alpine's /etc/init.d/x-ui startup script is downloaded via a bare
  `curl -fLRo` straight onto the live path in both update.sh and
  install.sh -- the exact same unguarded-overwrite pattern already
  fixed for /usr/bin/x-ui and the systemd unit file, just left
  uncovered on the OpenRC side. A network drop mid-download truncates
  the live init script; OpenRC then fails to source/execute it on the
  next start, leaving the panel unable to come up. Fixed with the same
  temp-file + non-empty check + mv -f (with its own exit-status check)
  pattern used everywhere else in this PR. Verified with bash -n and a
  standalone scratch-script test covering success, empty-download, and
  destination-preserved-on-failure paths.

- internal/web/service/panel/panel_test.go had one line-level `//`
  comment on a call site, which the root CLAUDE.md's hard rule ("No //
  line comments in committed Go/TS... rename instead of annotating")
  explicitly prohibits. The comment duplicated context already stated
  in the test's own doc comment two lines above, so it's simply
  removed rather than reworded.

Also flagged, deliberately not bundled here since it's a different
subsystem: x-ui.sh's update_geofiles() downloads Xray's live
geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked
as its own follow-up.

* fix(script): make geo-data file downloads atomic

Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the
Alpine init script fixed in prior PRs: update_geofiles() downloaded
Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl
writing straight onto the exact path Xray reads at runtime
(internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp
file, no verification. The existing check only inspected the reported
HTTP status via -w '%{http_code}', not file integrity, so a network
drop mid-download could leave a truncated .dat file on disk that
passes the status check. Xray then fails to parse it on the next
restart/reload, breaking any routing rules that reference geoip:/
geosite:.

The -z conditional-GET usage needed care here: the original code
pointed both -z and -o at the same live path. Fixed by pointing -z at
the live file (to keep the "already current" freshness check) while
-o writes to a PID-suffixed temp file, matching the pattern already
proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP
server that a 304 response leaves the temp file untouched/nonexistent
(so the existing "already up to date" branch still works unchanged),
and added a non-empty check plus a checked mv -f before treating a
download as installed.

Verified with bash -n and an end-to-end scratch test against a local
server covering: fresh download, 304-not-modified, empty response
body, and a 404 -- confirming a failure at any stage leaves the
previous good .dat file completely untouched and no temp file behind.

* fix(script): verify the release tarball extraction, not just the download

The final maximum-rigor review found the most significant remaining gap
in this whole effort: update.sh and install.sh check the tarball
download's exit status, but never check tar's exit status, and never
verify the extracted x-ui binary actually exists before continuing.
Worse, by the time extraction runs, the previous installation has
already been stopped and deleted -- there's no rollback. A truncated
download that still passes curl's own check, or a tar failure (disk
full, killed process), left the panel silently in a broken half-state:
chmod/config/service-install all continued to run against a missing or
empty binary, with no error surfaced anywhere. This is the same bug
class as everything else in this PR (unverified write to a path
something then depends on), just for the tarball itself rather than a
single file -- and it also covers the geo-data files this PR already
fixed once for the interactive/cron path, since they ship inside this
same tarball on every panel update.

Added: a non-empty check on the downloaded archive (both files, both
install.sh call sites) and a check that tar succeeded and produced a
non-empty x-ui binary before proceeding, failing loudly with a message
that explicitly says the previous install is already gone, since
silently continuing here is worse than anywhere else in this PR.

This doesn't make the multi-file extraction fully atomic (that would
mean extracting to a temp directory and atomically swapping the whole
install tree into place, a materially larger restructuring than
anything else in this PR) -- but it closes the "fails silently, user
discovers it days later when Xray can't start" gap, which was the
actual reported problem this whole effort traces back to.

Also fixed, all much smaller:
- replace_xui_script() in x-ui.sh implicitly returned chmod's exit
  status instead of success, so a successful atomic install could be
  reported as failed if chmod transiently failed after the mv already
  landed the new script. Added an explicit `return 0`.
- update_geofiles() had no default case branch; an unrecognized
  argument would silently reuse whatever dat_files/dat_source values a
  previous call left in the un-scoped globals instead of failing.
  Currently unreachable (all three call sites pass fixed literals) but
  cheap, defensive, and worth having.
- internal/web/controller/server.go's updatePanel has one branch (an
  unparseable "dev" form value) that's both untested and safe to test
  on any platform, since it's rejected before any real exec/network
  call. Added the missing test case.

Verified: bash -n on all three scripts; an empirical scratch test
covering an empty downloaded archive, a corrupt (non-gzip) archive,
and a successfully-extracting-but-empty archive, confirming each is
caught before the script proceeds; full go build/vet/test -race
across the whole module; frontend generation confirmed still in sync.

* fix(panel): base the update-slot staleness fallback on process liveness

Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711).

Blocking finding: acquireUpdateSlot's staleness fallback freed the
update slot purely on elapsed wall-clock time (5 minutes), with no
check on whether the update.sh process it launched was actually still
running. update.sh runs install_base() (apt-get/dnf/pacman update and
install) before update_x-ui even starts, plus several GitHub
downloads (release tarball, x-ui.sh, and possibly a service unit or
x-ui.rc) -- on a slow or throttled host, a small VPS being the typical
deployment target for this project, that alone can plausibly exceed 5
minutes with nothing wrong. A second /updatePanel call arriving in
that window (an admin retrying after the frontend's 90s poll times
out, or overlapping master-node bulk-update calls) would launch a
second update.sh, racing the exact rm/tar/mv/systemctl sequence this
whole PR exists to make safe.

Fixed by recording the launched process's PID (detached-fallback path
only; the systemd-run path's own process has already exited by the
time startUpdate returns, so it never learns update.sh's real PID) and
checking it via the standard POSIX kill(pid, 0) liveness probe before
treating a run as stale, following the existing panel_unix.go /
panel_other.go platform-split pattern already used for
setDetachedProcess. A confirmed-alive process now keeps the slot held
past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline
for the systemd-run path, which still has no way to check liveness
directly). updateHardCeiling (2 hours) is an absolute backstop so a
genuinely wedged run can never lock out retries permanently even on
the PID-tracked path.

Added two regression tests exercising the new logic (gated to Linux,
since processAlive is a no-op stub elsewhere): a live PID keeps the
slot held past the stale window, and the hard ceiling overrides
liveness. Traced both by hand against the new acquireUpdateSlot logic;
could not execute-verify processAlive itself on this Windows dev
machine (no WSL distro installed, and installing one felt
disproportionate to validate kill(pid, 0), an extremely well-established
POSIX primitive), but cross-compiled clean for linux/amd64 and this
repo's CI runs the real test suite on Linux.

Also fixed, both suggestions from the same review:
- install.sh: two failure paths right after tarball extraction were
  exiting without cleaning up the already-downloaded x-ui.sh temp file
  (xui_script_temp), leaving it behind. Every other new failure branch
  in this PR removes its temp file before exiting; these two now do
  too.
- frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry
  did not reflect that a successful response now carries an obj with
  runId. Added an inline response example matching the existing
  pattern used for other ad hoc (non-schema-backed) responses like
  getWebCertFiles.

Verified: go build/vet clean on both windows (native) and a linux/amd64
cross-compile; full go test ./... clean; go test -race on the panel
and controller packages; bash -n on all three shell scripts; npm run
gen confirms the openapi.json diff is exactly the new response example
with no stray changes to src/generated; TestAPIRoutesDocumented still
passes.
2026-07-02 18:19:33 +02:00
nima1024m ade74eb321 fix(balancers): keep mixed strategies on one observer (#5674)
* fix(balancers): keep mixed strategies on one observer

Xray resolves Observatory and Burst Observatory through the same global observer feature. When any burst-required strategy is present, keep all observer-backed balancer selectors on burstObservatory and remove the regular observatory so mixed leastPing configs cannot generate two competing observer blocks.

* test(balancers): cover observer strategy combinations

Exercise the observer sync matrix for random, round-robin, leastPing, and leastLoad balancers. Include mixed and stale-observer cases so the panel keeps only the observer type that Xray should consume.

* fix(balancers): clarify observer empty state

Update the Observatory tab empty hint to describe the actual auto-managed cases. Least Ping, Least Load, and fallback Random or Round-robin balancers now explain why an observer is added before the balancer can choose a target.

* fix(balancers): remove mixed observer switch

Show only the observer settings panel that matches the current balancer requirements. Legacy configs that still contain both observatory blocks now display a warning instead of a tab switch, since saving balancers normalizes the config back to one global observer.

* test(balancers): cover observer cleanup on deletion

Add direct balancer deletion and outbound cascade cases for leastLoad, fallback, and mixed leastPing scenarios. These tests pin that the final unneeded observer is removed, burst switches back to regular observatory when only leastPing remains, and burst remains when a burst-required balancer survives.
2026-07-02 18:18:30 +02:00
MHSanaei 97e2c9e7ba fix(web): sync the VLESS generate-key dropdown with the encryption field
The auth-kind dropdown in the VLESS "Generate Key" block was hardcoded to
x25519 on mount, while the "Already selected" text next to it was derived
independently from settings.encryption. Editing an inbound whose encryption
uses another kind (e.g. ML-KEM-768) showed a mismatched dropdown, and
clicking Generate without noticing would produce a keypair of the wrong
kind for the inbound.

Extract the encryption-string parsing into a shared pure helper
(lib/xray/vless-encryption), use it both for the selected-auth label and to
initialize/sync the dropdown, so the two can no longer diverge. When the
encryption is none or unparseable the dropdown keeps its x25519 default.

Closes #5744
2026-07-02 17:37:04 +02:00
MHSanaei 5e8327e728 fix(settings): include savePayload in the category body memo deps
react-hooks/exhaustive-deps flagged the omission; a stale closure could
hand SecurityTab an outdated save callback after a mutation state change.
2026-07-02 17:16:12 +02:00
MHSanaei 7c12700c7d fix(sub): resolve subscription clients and stats from normalized tables
A subscription fetch inside a large inbound cost seconds because every
layer re-parsed the inbound's full settings JSON: getInboundsBySubId
preloaded the whole client_traffics table of each matched inbound,
matchingClients parsed all clients to filter by subId, and then every
per-protocol generator (raw links, JSON outbounds, Clash proxies) parsed
the blob again per link — once to find the client by email and once for
inbound-level fields like encryption or method. At 500k clients in one
inbound that was 13s per raw fetch and 8.5s per JSON fetch; at 100k,
2.6s/1.7s. After this change both cost ~70ms at 100k.

matchingClients now resolves through the indexed clients/client_inbounds
tables (ListForInboundBySubId, ordered by clients.id like ListForInbound
— the same source the running Xray users are built from), and the
per-request SubService carries two caches: clientsByInbound, primed by
matchingClients/inboundLinks so clientForLink resolves a client without
parsing settings (with the old full-parse as fallback, which also fixes
the export-all-links path that re-parsed the blob once per client), and
settingsByInbound, a once-per-request shallow decode that skips
materializing the clients array entirely. The ClientStats preload is
replaced by loading only the subscriber's traffic rows (indexed
clients.sub_id); statsForClient's per-email DB fallback (#5567) covers
any miss, and the case-insensitive email dedupe keeps the #5134
guarantee for case-differing duplicate rows.
2026-07-02 16:58:00 +02:00
MHSanaei c0d17e132d fix(job): batch ip-limit per-email lookups and persistence
processObserved paid four round-trips per observed email every 10s scan:
an inbound-resolving join, a tracking-row read, an autocommit Save (one
fsync each under synchronous=FULL), and — worst of all — a full JSON
parse of the owning inbound's settings blob just to read that one
client's limitIp. On a big single inbound that parse alone made a scan
cost ~1.5s per online client.

The scan now front-loads three chunked batch queries (clients.limit_ip,
email->inbound through the client_inbounds relation keeping the lowest
inbound id like the old First(), and the tracking rows) and writes every
inbound_client_ips change inside one transaction, so M observed emails
cost a handful of queries and a single fsync. The per-email LIKE fallback
remains for emails missing from the relation, preserving the #4963
stale-email cleanup. limitIp now comes from the clients table (same
source B3 gates on) instead of the settings blob, and xray disconnects
for banned clients run after the commit so their network round-trips
never extend the write transaction node syncs contend with.
2026-07-02 16:39:31 +02:00
MHSanaei fc5be5b9e4 feat(web): broadcast delta client stats above a snapshot threshold
Both 5s broadcasters (the local traffic poll and the node traffic sync)
shipped the complete client_traffics table on every cycle while a browser
was connected. At 500k clients that is a 1.7s full-table read plus an
86MB marshal per job per poll — and the hub drops any payload over 10MB
and sends an invalidate the frontend ignores for these message types, so
past ~55k clients all of it was pure waste and the UI got nothing.

Installs at or below 5000 clients (clientStatsSnapshotMaxClients) keep
the exact full-snapshot behavior — it exists because a pure delta feed
left UI rows stale when nothing moved in a cycle (see GetAllClientTraffics)
— and the payload now carries snapshot=true. Above the threshold the jobs
send only this cycle's active rows (the xray poll's active emails, or the
emails online on the synced nodes) with snapshot=false, and scope the
last-online map to those rows; the initial full map still arrives over
REST and the clients page refetches every 5s.

GetActiveClientTraffics gains the overlayGlobalTraffic pass so delta rows
carry the same cross-panel usage as snapshot rows. The node job also
stops reading the full last-online map before the has-clients gate, which
was a wasted full-table read on every tick with no dashboard open.

Frontend: useClients keeps its live summary strictly snapshot-driven
(snapshot=false payloads skip the allClientStats replace and the summary
falls back to the server-computed one); the per-row page merge and the
inbounds-page merges already handle deltas.
2026-07-02 16:34:01 +02:00
MHSanaei c3cc8b4374 fix(job): gate ip-limit scan on clients.limit_ip instead of parsing all settings
hasLimitIp ran settings LIKE '%limitIp%' and JSON-parsed every matching
inbound's settings blob — and since clients marshal limitIp without
omitempty, every inbound matched, so each 10s scan loaded and parsed
every settings blob in the database (~75MB of JSON at 500k clients) just
to decide whether any limit exists.

It now probes the normalized clients table (limit_ip > 0, Limit(1) count
like depletedCond does), which SyncInbound and the legacy seeder keep in
sync with the settings JSON. Semantics note: a limitIp that exists only
in settings JSON with no clients row no longer enables enforcement — the
enforcement path itself already resolves clients through the same
normalized tables.
2026-07-02 16:24:18 +02:00
MHSanaei 97588dd0b9 fix(traffic): disable depleted clients by id instead of a second full scan
disableInvalidClients evaluated the depleted predicate twice per poll:
once to SELECT the rows (for xray removal and settings sync) and again in
the UPDATE that flips enable off — each a full client_traffics scan, the
second also re-running the cross-panel EXISTS subquery when global rows
exist.

The UPDATE now flips the already-collected rows by primary key in
sqlInChunk batches, sorted for stable lock order. Same rows, same
RowsAffected, half the scan cost; id-based matching also stays correct
for rows with empty emails.
2026-07-02 16:24:18 +02:00
MHSanaei fb1d055b06 fix(traffic): persist delayed-start expiry only for converted clients
addClientTraffic's second pass wrote expiry_time for every polled row via
UPDATE ... WHERE expiry_time < 0 — a no-op statement per active client on
every 5s poll, since almost all rows carry a positive expiry. At 10k
active clients that was 10k pointless indexed UPDATEs per poll.

adjustTraffics now returns the emails it actually converted this tick and
the persistence pass writes exactly those, in sorted order to keep
concurrent writers lock-compatible on Postgres. Behavior is unchanged:
unconverted rows never matched the WHERE clause anyway.
2026-07-02 16:24:18 +02:00
MHSanaei 4fc301682f test(scale): cover traffic poll, ws payloads, ip-limit job, sub and xray config at 500k
The paths that run continuously in production had no scale coverage: the
5s traffic poll (AddTraffic with its auto-renew and depleted scans), the
websocket snapshot the job broadcasts while a browser is connected, the
10s ip-limit job (hasLimitIp LIKE scan + per-email settings parse), a
subscription fetch inside a huge inbound, and the full Xray config build.

New benchmarks reuse the XUI_SCALE_TEST / XUI_DB_TYPE gating and stay
log-only. Sizes default to 10k/100k; XUI_SCALE_SIZES=500000 raises the
ladder without editing code. seedScaleDataset writes inbounds, clients,
client_inbounds and client_traffics directly in one transaction instead
of SyncInbound, so a 500k seed takes seconds. XUI_SCALE_DB_PATH persists
the seeded SQLite file for manual smoke runs against a live panel.
2026-07-02 16:12:46 +02:00
MHSanaei 28f7690224 docs: move architecture map into docs/ and refresh it against the live tree
The architecture/code map previously lived in .claude/CLAUDE.md, which was
gitignored (local-only) and auto-loaded into every agent session alongside
the root CLAUDE.md. Track it in docs/architecture.md instead and reference
it from CLAUDE.md so it is read on demand.

While moving it, fact-check the whole map against the current tree:
- add the missing internal/eventbus and internal/tunnelmonitor packages,
  the service/email subpackage, and util/wirecodec
- document node mTLS (tls_client.go, node_mtls.go, setting_mtls.go) and the
  fourth TLS verify mode
- add the Host, ClientExternalLink, NodeClientIp and ClientGlobalTraffic
  models plus their symptom-index rows
- correct the cron table (check_cpu_usage is 1m not 10s; add
  check_memory_usage and free_os_memory), the middleware chain
  (MaxBodyBytes, ConfigEnvelope, CSRF) and the controller route prefixes
- refresh the sub/ and service/ file listings, frontend pages (hosts/,
  index/), CI workflow list, and replace stale exact line counts with
  rounded sizes
2026-07-02 14:21:21 +02:00
MHSanaei 92303094fd feat(settings): let users clear stored secrets from the UI
Redacted secrets (SMTP password, Telegram bot token, LDAP password) are
always served blank to the browser, so the update path treats a blank
submission as "unchanged" and silently restores the stored value. That
made a once-set secret impossible to remove without editing the database
— e.g. switching to a passwordless localhost SMTP relay kept sending the
old credentials forever.

Blank stays "unchanged"; clearing is now its own signal. The update
request carries explicit clear flags (request-scoped fields on the
controller form, so they are never persisted as settings rows), and
preserveRedactedSecrets skips the restore for a flagged secret. Each
secret field gets a Clear/Undo button that arms the flag; typing a new
value disarms it. The 2FA token keeps its existing behavior: it is
already clearable by disabling 2FA.

Closes #5724
2026-07-02 13:57:34 +02:00
MHSanaei fb3a1559b2 fix(sub): default https:// for scheme-less support and profile URLs
A support URL saved without a scheme (e.g. "t.me/handle") is served
verbatim in the subscription Support-Url header and page data, and client
apps resolve it relative to the subscription domain — clicking it lands
on "https://panel.example/t.me/handle". Same hazard for the profile URL.

Default the scheme to https:// when none is present, both when saving the
settings and when reading already-stored values, so existing databases are
covered without a migration. Deliberate non-http schemes (tg://, mailto:,
tel:) pass through untouched, which is why these two fields don't go
through SanitizeHTTPURL's http(s)-only validation.

Closes #5738
2026-07-02 13:47:10 +02:00
MHSanaei a335456cd3 fix(settings): repair legacy path settings that block every settings save
A subJsonPath (or subPath/subClashPath/webBasePath) stored without its
leading/trailing slash — written before the slash rules existed, or
restored from an old backup — fails the frontend's whole-form validation,
so every save on the Settings page is rejected client-side. The backend's
CheckValid would normalize the value, but a save request never reaches it,
leaving the panel wedged until someone edits the database by hand.

Normalize the stored path rows at startup, mirroring CheckValid's slash
rules. The pass is idempotent and not seeder-gated, since a restored
backup can reintroduce bad values at any time.

Also add the missing pages.settings.validation.pathLeadingSlash key to
all 13 locales — the validation error used to render as its raw key.

Closes #5726
2026-07-02 13:42:03 +02:00
MHSanaei 9a3a12b260 fix(node): stop Postgres deadlocks and deleted-client resurrection in node sync
Two defects in the node traffic sync, both hit hard on busy
master+multi-node Postgres deployments:

Client-IP merges deadlocked. Each node syncs on its own goroutine and
shared clients appear in several nodes' reports, but MergeInboundClientIps
and upsertNodeClientIps locked rows in whatever order each node's report
arrived. Two concurrent merges taking the same rows in opposite order is
exactly what Postgres aborts with SQLSTATE 40P01 ("merge client ips from
<node> failed: deadlock detected"). Both merges now process emails in
sorted order so every transaction acquires row locks in one global order.

Deleted clients resurrected with zeroed traffic. A snapshot fetched just
before a deletion still names the deleted email; applying it after the
delete committed re-added the client. The delete tombstone existed for
precisely this race but only zeroed the seed counters: the sync still
recreated the client_traffics row, and worse, adopted the node's stale
settings JSON wholesale, putting the client back in the central inbound
as if it were brand new with 0 traffic. Snapshot application now skips
row creation for tombstoned emails on known inbounds and strips
tombstoned clients from adopted settings; fresh node-adoption semantics
(rows seeded at zero) are unchanged.

The mass-disconnect part of the report is the forced node restart on
auto-disable, removed separately in 4d6f2ddd.

Closes #5739
2026-07-02 13:37:06 +02:00
MHSanaei 4d6f2ddd97 fix(node): stop force-restarting a node's Xray when its clients auto-disable
When a depleted or expired client lived on a node, the master pushed the
updated inbound (client flipped off) to the node and then also told the
node to fully restart Xray. The push alone already applies the disable:
the node updates that one inbound on its running core. The extra restart
dropped every live connection on the node each time any of its clients
crossed a quota or expiry, and a restart that failed to come back left
the node forwarding nothing until someone restarted Xray by hand.

This mirrors e5b56c94, which removed the same forced restart from the
local auto-disable path; remote nodes now get the same graceful
reconcile-by-push treatment.

Closes #5740
2026-07-02 13:27:36 +02:00
MHSanaei 62f303905e fix(scripts): pass --force to acme.sh --installcert so it survives sudo
acme.sh guards every non-install command behind _checkSudo: when a
non-root user runs the panel scripts via sudo, it prints the sudo wiki
warning and exits before doing anything, unless FORCE is set. All our
--issue calls already pass --force and were unaffected, but none of the
--installcert calls did, so issuance succeeded and installation then
aborted silently, ending in "Certificate files not found after
installation". FORCE has no other effect on the installcert path, so
mirror the --issue calls and pass --force everywhere we install certs.

Closes #5741
2026-07-02 13:20:31 +02:00
MHSanaei c8ef1b1f68 feat(reality): derive a stable per-client spiderX for shared links
The inbound's spiderX now acts as a per-client seed: exports emit
sha256(seed|subKey) truncated to a 15-hex "/path", so a client's spx no
longer changes on every subscription fetch (#5718) while different
clients stop sharing one fingerprintable value. The form gains a
regenerate button that rotates every client's path at once.

The frontend link builders derive through the same function
(lib/xray/spider-x.ts, @noble/hashes) keyed on subId-then-email like
the Go subKey, so panel QR/copy links and subscription output agree —
cross-language vector tests lock both sides byte-for-byte. streamData
now tolerates malformed stored stream settings (unparseable JSON, null
tls/reality settings) instead of panicking the subscription request.
2026-07-02 12:53:08 +02:00
MHSanaei 64c306037f feat(wireguard): make client allowedIPs editable with validation
The WireGuard peer address was allocated server-side and shown read-only
in the client editor, so changing it required hand-editing the inbound's
raw settings JSON (#5715). The backend add/update paths already honored a
submitted allowedIPs; only the form withheld it.

Make the field editable (comma-separated, empty still auto-assigns) and
validate submissions server-side: entries must parse as an IP or CIDR,
bare addresses normalize to single-host prefixes, and an address already
used by another peer on the inbound is rejected.

Closes #5715
2026-07-02 09:45:54 +02:00
MHSanaei 8dd3b31ee8 fix(node): show the activated first-use deadline on the Clients page
With "start after first use" on a node inbound, the node activates the
absolute deadline and the master adopts it into client_traffics via the
sync CASE merge — but the client record (what the Clients page reads) was
only refreshed by SyncInbound from the snapshot's settings JSON. A node
whose JSON still carried the negative duration (stale conversion, older
node build, or a mixed local+node attachment) kept rewriting the record
back to "not started" even though the DB held the real deadline (#5714).

Lift the activated deadline from client_traffics onto still-negative
client records at the end of every node sync, after SyncInbound has run.
Intentional resets back to delayed start are unaffected: editing a client
also resets client_traffics to the negative duration, so the lift's
expiry_time > 0 guard never matches.

Closes #5714
2026-07-02 09:36:07 +02:00
MHSanaei e5b56c9444 fix(xray): reconcile client auto-disable through the API instead of a forced restart
When a client expired or hit its traffic limit, XrayTrafficJob called
RestartXray(true), stopping the whole process and dropping every live
connection on every inbound (#5712 reported this as XHTTP on 443 dying) —
even though disableInvalidClients had already removed the user from the
running core over gRPC. The force restart existed only to re-sync the
process's config snapshot.

Switch the job to a non-forced restart and teach ComputeHotDiff to express
a client-only inbound change as per-user AlterInbound operations for
vless/vmess/trojan, so the reconcile is a no-op RemoveUser plus a snapshot
update rather than a handler swap that would still blip that inbound's
listener. Anything beyond the clients list still falls back to handler
replacement or a full restart as before.

Closes #5712
2026-07-02 09:26:53 +02:00
MHSanaei 1153d5db8c fix(groups): keep group traffic totals stable across client resets and deletes
ListGroups displays live_sum(client_traffics) minus the group's stored
reset baseline, but only ResetGroupTraffic ever moved the baseline. Any
client-level operation that zeroed or deleted traffic rows (single/bulk
reset, client delete, removing a client's last inbound) shrank the live
sum and silently subtracted that client's history from the group total.

Shift the baseline down by the removed counters inside the same
transaction, so group totals only change through group reset. Derived
groups without a stored row get one with a negative baseline, which the
existing clamp handles.

Closes #5675
2026-07-02 09:17:47 +02:00
MHSanaei 539bcc897c fix(inbounds): apply the legacy xhttp session-key migration when editing
rawInboundToFormValues injected the stored xhttpSettings blob into the form
store without running it through XHttpStreamSettingsSchema, so the
sessionPlacement/sessionKey -> sessionIDPlacement/sessionIDKey rename from
xray-core v26.6.22 (and the v3.4.0 field defaults) never applied on the
edit path. Inbounds saved before the rename opened with blank session
fields, and the stale keys could ride back on save even though the core no
longer reads them. Parse the sub-object through the schema on load, and
lift any stale legacy keys in normalizeXhttpForWire as a backstop.

Closes #5621
2026-07-01 23:11:58 +02:00
MHSanaei 273f88721e fix(database): stop noisy per-startup errors in the Postgres server log
Two statements failed server-side on every panel start after a SQLite to
Postgres migration, flooding the postgres log even though the Go side
suppressed them:

- resyncPostgresSequences issued SELECT MAX(id) against client_inbounds,
  whose composite primary key has no id column; Postgres validates the
  SELECT list at parse time, so the WHERE pg_get_serial_sequence(...) guard
  never got a chance to no-op it. Skip models whose GORM schema maps no id
  column before issuing the statement.

- AutoMigrate detects existing columns via information_schema filtered by
  table_catalog = CURRENT_DATABASE(), which misdetects on some setups and
  re-issues ALTER TABLE ... ADD for columns that already exist. HasColumn/
  HasIndex query without that filter and are reliable (the existing
  duplicate-column suppressor depends on exactly that), so skip AutoMigrate
  outright when the table, every column, and every index already exist.

Closes #5665
2026-07-01 23:07:05 +02:00
MHSanaei 1f2e3e1447 fix(sub): use configured spiderX instead of always randomizing
applyShareRealityParams and SubJsonService.realityData generated a fresh
random spx on every export, so share links, "export all links", and JSON
subscriptions never matched a spiderX configured on the inbound and two
exports of the same client disagreed with each other. Read the value from
realitySettings.settings like pbk/fp/pqv and keep the random value only as
a fallback when none is configured.

Closes #5718
2026-07-01 23:07:05 +02:00
MHSanaei 49773c18de fix(xray): force full restart for inbounds with a VLESS reverse client
Hot-applying an inbound change swaps it via DelInbound+AddInbound on
the running core. That unregisters any client's reverse.tag handler
on the xray-core side without closing the bridge's already-established
connection, so the reverse tunnel is silently orphaned until someone
manually restarts xray. diffInbounds now bails out of the hot-apply
path whenever the old or new inbound carries a reverse-tagged client,
falling back to a full restart, which actually drops the socket and
lets the bridge redial on its own.

Also scope the .claude ignore rule to its contents (.claude/*) instead
of the whole directory, so individual files under .claude/ can be
tracked selectively.
2026-07-01 14:02:13 +02:00
MHSanaei 427613b308 chore(ci): upgrade claude-bot to Sonnet 5 and set explicit effort levels
Sonnet 5 reaches near-Opus quality on coding/agentic work at lower cost;
pin effort explicitly (xhigh/max) instead of relying on model defaults.
2026-07-01 00:43:27 +02:00
189 changed files with 8945 additions and 1156 deletions
+166 -8
View File
@@ -1,19 +1,177 @@
# This file serves a dual purpose:
# 1. Developer Bootstrap: The active (uncommented) variables directly below
# configure a safe, unprivileged local environment for 'go run .'.
# This allows 'cp .env.example .env' to work out-of-the-box without root.
# 2. Production Reference: All available XUI_* configuration options are
# documented and commented out in the reference section further below.
#
# 3x-ui reads its runtime configuration from XUI_* environment variables.
# On a script install, the installer writes them to the service environment file
# (/etc/default/x-ui, /etc/conf.d/x-ui, or /etc/sysconfig/x-ui depending on the distro).
# For Docker, you set them in docker-compose.yml or via 'docker run -e'.
#
# Defaults are sensible — set only what you need to change, then restart:
# systemctl restart x-ui
# ------------------------------------------------------------------------------
# LOCAL DEVELOPMENT OVERRIDES (ACTIVE BY DEFAULT)
# ------------------------------------------------------------------------------
XUI_DEBUG=true XUI_DEBUG=true
XUI_DB_FOLDER=x-ui XUI_DB_FOLDER=x-ui
XUI_LOG_FOLDER=x-ui XUI_LOG_FOLDER=x-ui
XUI_BIN_FOLDER=x-ui XUI_BIN_FOLDER=x-ui
XUI_INIT_WEB_BASE_PATH=/ XUI_INIT_WEB_BASE_PATH=/
# XUI_PORT=8080
# Optional tunnel health monitor (disabled by default). It periodically probes a # ==============================================================================
# URL and restarts xray-core after repeated failures. Point XUI_TUNNEL_HEALTH_PROXY # REFERENCE CONFIGURATION (ALL OPTIONS)
# at a local xray inbound so the probe tests the tunnel; without it the probe only # ==============================================================================
# checks host connectivity and a restart will not fix host network issues. A restart
# drops every connected client. # ------------------------------------------------------------------------------
# XUI_TUNNEL_HEALTH_MONITOR=true # Database
# XUI_TUNNEL_HEALTH_PROXY=socks5://127.0.0.1:1080 # ------------------------------------------------------------------------------
# Backend database type: sqlite, or postgres (also accepts postgresql / pg)
# Default: sqlite
#XUI_DB_TYPE=sqlite
# Folder for the SQLite database file (x-ui.db)
# Default: /etc/x-ui (Overridden to 'x-ui' in the development block above)
#XUI_DB_FOLDER=/etc/x-ui
# PostgreSQL connection string (used when XUI_DB_TYPE=postgres)
# Example: postgres://user:password@localhost:5432/dbname?sslmode=disable
#XUI_DB_DSN=
# Max open connections in the PostgreSQL pool
#XUI_DB_MAX_OPEN_CONNS=
# Max idle connections in the PostgreSQL pool
#XUI_DB_MAX_IDLE_CONNS=
# PostgreSQL Docker Container Settings
# Default credentials used if you are running PostgreSQL via docker-compose
#POSTGRES_USER=xui
#POSTGRES_PASSWORD=xui
#POSTGRES_DB=xui
# ------------------------------------------------------------------------------
# Panel
# ------------------------------------------------------------------------------
# Override the panel port (1–65535). Takes precedence over the stored setting.
#XUI_PORT=
# Initial web base path on FIRST launch (e.g., /panel)
# Default: /
#XUI_INIT_WEB_BASE_PATH=/
# Enable Fail2ban-based IP-limit enforcement
# Default: true
#XUI_ENABLE_FAIL2BAN=true
# Skip the HSTS header — set true when TLS is terminated by a reverse proxy
# Default: false
#XUI_SKIP_HSTS=false
# ------------------------------------------------------------------------------
# Logging & binaries
# ------------------------------------------------------------------------------
# Logging level: debug, info, notice, warning, or error
# Default: info
#XUI_LOG_LEVEL=info
# Debug mode. Forces log level to debug, enables Gin debug mode,
# and ensures frontend assets are served directly from disk (see CLAUDE.md).
# Default: false (Overridden to 'true' in the development block at the top)
#XUI_DEBUG=false
# Log output directory
# Default: /var/log/x-ui (Overridden to 'x-ui' in the development block above)
#XUI_LOG_FOLDER=/var/log/x-ui
# Folder for the Xray-core binary and geosite/geoip files
# Default: bin (Overridden to 'x-ui' in the development block above)
#XUI_BIN_FOLDER=bin
# Legacy Path Settings
# Main installation folder (Default: /usr/local/x-ui for Linux, /app for Docker)
#XUI_MAIN_FOLDER=/usr/local/x-ui
# Path to the systemd service file (Default: /etc/systemd/system)
#XUI_SERVICE=/etc/systemd/system
# ------------------------------------------------------------------------------
# Memory & profiling
# ------------------------------------------------------------------------------
# Go GC target percentage; lower = less RAM, slightly more CPU.
# Default: 75
#XUI_GOGC=
# Minutes between FreeOSMemory calls; 0 disables.
# Default: 10
#XUI_MEMORY_RELEASE_INTERVAL=
# Go soft memory limit in MiB
#XUI_MEMORY_LIMIT=
# Go-syntax soft limit (e.g., 400MiB); takes precedence over XUI_MEMORY_LIMIT
#GOMEMLIMIT=
# Expose pprof profiling on 127.0.0.1:6060
# Default: false
#XUI_PPROF=false
# Automatically set to 'true' inside the official Docker image.
# Consumed by internal scripts (x-ui.sh) to detect the environment.
# There is normally no need to set or toggle this variable manually.
# Default: false (automatically 'true' in Docker environments)
#XUI_IN_DOCKER=false
# ------------------------------------------------------------------------------
# Xray
# ------------------------------------------------------------------------------
# Force VMess AEAD
# Default: false
#XRAY_VMESS_AEAD_FORCED=false
# ------------------------------------------------------------------------------
# Tunnel health monitor
# ------------------------------------------------------------------------------
# Optional watchdog: probes a URL (optionally through a local Xray inbound)
# and restarts Xray after repeated failures. A restart drops all connected clients.
# Default: false
#XUI_TUNNEL_HEALTH_MONITOR=false
# Proxy to send the probe through, e.g., socks5://127.0.0.1:1080
# Empty = only checks host connectivity
#XUI_TUNNEL_HEALTH_PROXY=
# URL to probe
# Default: https://www.cloudflare.com/cdn-cgi/trace
#XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace #XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
# Interval between probes
# Default: 30s
#XUI_TUNNEL_HEALTH_INTERVAL=30s #XUI_TUNNEL_HEALTH_INTERVAL=30s
# Per-probe timeout
# Default: 10s
#XUI_TUNNEL_HEALTH_TIMEOUT=10s #XUI_TUNNEL_HEALTH_TIMEOUT=10s
# Consecutive failures before a restart
# Default: 3
#XUI_TUNNEL_HEALTH_FAILURES=3 #XUI_TUNNEL_HEALTH_FAILURES=3
# Minimum delay between restarts
# Default: 5m
#XUI_TUNNEL_HEALTH_COOLDOWN=5m #XUI_TUNNEL_HEALTH_COOLDOWN=5m
# ------------------------------------------------------------------------------
# Unattended install
# ------------------------------------------------------------------------------
# Set to 1 (or run with no TTY) to install with zero prompts.
# Generated credentials will be written to /etc/x-ui/install-result.env
#XUI_NONINTERACTIVE=1
+6 -3
View File
@@ -30,7 +30,8 @@ jobs:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
allowed_non_write_users: "*" allowed_non_write_users: "*"
claude_args: | claude_args: |
--model claude-sonnet-4-6 --model claude-sonnet-5
--effort xhigh
--max-turns 300 --max-turns 300
--allowedTools "Bash(gh:*),Read,Glob,Grep" --allowedTools "Bash(gh:*),Read,Glob,Grep"
prompt: | prompt: |
@@ -282,7 +283,8 @@ jobs:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
allowed_non_write_users: "*" allowed_non_write_users: "*"
claude_args: | claude_args: |
--model claude-opus-4-8 --model claude-sonnet-5
--effort max
--max-turns 250 --max-turns 250
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep" --allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep"
prompt: | prompt: |
@@ -500,7 +502,8 @@ jobs:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
claude_args: | claude_args: |
--model claude-opus-4-8 --model claude-sonnet-5
--effort max
--max-turns 250 --max-turns 250
--allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep,Edit,Write" --allowedTools "Bash(gh:*),Bash(git:*),Read,Glob,Grep,Edit,Write"
--append-system-prompt "You are replying to an @claude mention in the MHSanaei/3x-ui repository, an open-source web panel for managing Xray-core servers. The full repo source is checked out in the working directory; use Read, Glob and Grep to open and verify the relevant files before stating any default, path, flag, option name, or behavior. --append-system-prompt "You are replying to an @claude mention in the MHSanaei/3x-ui repository, an open-source web panel for managing Xray-core servers. The full repo source is checked out in the working directory; use Read, Glob and Grep to open and verify the relevant files before stating any default, path, flag, option name, or behavior.
+35 -1
View File
@@ -1,10 +1,18 @@
name: Deploy Smoke Tests name: Deploy Smoke Tests
# Container smoke test for the unattended (cloud-init) install path. # Container smoke test for the unattended (cloud-init) install path.
# Runs only when the install/deploy assets change. # Runs when the install/deploy assets change on a branch push or PR, and
# again after a release-tag build finishes uploading its assets — pinned to
# that tag, so the green result verifies the release actually being shipped.
# Tag pushes must NOT trigger the unpinned job directly: at that moment
# releases/latest still points at the previous release (#5756), and a `paths`
# filter alone cannot exclude them because a brand-new tag ref has no diff
# base, so it runs on every tag push.
on: on:
push: push:
branches:
- "**"
paths: paths:
- "install.sh" - "install.sh"
- "deploy/**" - "deploy/**"
@@ -14,12 +22,16 @@ on:
- "install.sh" - "install.sh"
- "deploy/**" - "deploy/**"
- ".github/workflows/smoke.yml" - ".github/workflows/smoke.yml"
workflow_run:
workflows: ["Release 3X-UI"]
types: [completed]
permissions: permissions:
contents: read contents: read
jobs: jobs:
noninteractive-install: noninteractive-install:
if: github.event_name != 'workflow_run'
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -30,3 +42,25 @@ jobs:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- name: Non-interactive install smoke test - name: Non-interactive install smoke test
run: bash deploy/test/smoke-noninteractive.sh run: bash deploy/test/smoke-noninteractive.sh
release-tag-install:
if: >-
github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
startsWith(github.event.workflow_run.head_branch, 'v') &&
contains(github.event.workflow_run.head_branch, '.')
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.workflow_run.head_sha }}
- name: Pinned release install smoke test
env:
XUI_SMOKE_VERSION: ${{ github.event.workflow_run.head_branch }}
run: bash deploy/test/smoke-noninteractive.sh "$XUI_SMOKE_VERSION"
+1 -1
View File
@@ -2,7 +2,7 @@
.idea/ .idea/
.vscode/ .vscode/
.cursor/ .cursor/
.claude/ .claude/*
.cache/ .cache/
.sync* .sync*
+3
View File
@@ -3,6 +3,9 @@
Operational guide for AI agents working in this repo. Long-form human docs: Operational guide for AI agents working in this repo. Long-form human docs:
`CONTRIBUTING.md` (setup, testing philosophy) and `frontend/README.md`. `CONTRIBUTING.md` (setup, testing philosophy) and `frontend/README.md`.
Read those before large changes. This file is the short, must-follow version. Read those before large changes. This file is the short, must-follow version.
For a deep navigation map (request lifecycle, cron-job table, symptom → file
index, layering rules), read `docs/architecture.md` on demand — do not guess
file locations when it can answer in one hop.
## Stack ## Stack
- Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM. - Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
+9
View File
@@ -69,5 +69,14 @@ EOF
fail2ban-client -x start fail2ban-client -x start
fi fi
# Certificate auto-renewal: acme.sh (installed by the panel's SSL menu) relies
# on a root crontab entry, but the crontab is lost when the container is
# recreated and crond was never started. Re-register the job and run crond so
# renewals actually fire; mount /root/.acme.sh as a volume to keep acme state.
if [ -f /root/.acme.sh/acme.sh ]; then
/root/.acme.sh/acme.sh --install-cronjob >/dev/null 2>&1
crond
fi
# Run x-ui # Run x-ui
exec /app/x-ui exec /app/x-ui
+19 -3
View File
@@ -7,35 +7,51 @@
# * /etc/x-ui/install-result.env exists (mode 600) with random, non-default creds # * /etc/x-ui/install-result.env exists (mode 600) with random, non-default creds
# * the panel reports hasDefaultCredential: false (no admin/admin remains) # * the panel reports hasDefaultCredential: false (no admin/admin remains)
# * the panel HTTP server actually serves on the generated port/base path # * the panel HTTP server actually serves on the generated port/base path
# * with a [version] argument: the installed binary reports exactly that version
# #
# Requires Docker and network access (install.sh downloads the released binary). # Requires Docker and network access (install.sh downloads the released binary).
# Usage: bash deploy/test/smoke-noninteractive.sh # Usage: bash deploy/test/smoke-noninteractive.sh [version]
# With no argument install.sh resolves releases/latest. Pass an explicit tag
# (e.g. v3.4.2) to verify that exact release — the tag-triggered CI run does
# this so it cannot silently validate the previous release (#5756).
set -euo pipefail set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}" IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
XUI_SMOKE_VERSION="${1:-}"
if ! command -v docker > /dev/null 2>&1; then if ! command -v docker > /dev/null 2>&1; then
echo "ERROR: docker is required for this smoke test." >&2 echo "ERROR: docker is required for this smoke test." >&2
exit 1 exit 1
fi fi
echo "== non-interactive install smoke test (image: $IMAGE) ==" echo "== non-interactive install smoke test (image: $IMAGE, version: ${XUI_SMOKE_VERSION:-latest}) =="
docker run --rm \ docker run --rm \
-v "${REPO_ROOT}/install.sh:/root/install.sh:ro" \ -v "${REPO_ROOT}/install.sh:/root/install.sh:ro" \
-e XUI_NONINTERACTIVE=1 \ -e XUI_NONINTERACTIVE=1 \
-e XUI_SSL_MODE=none \ -e XUI_SSL_MODE=none \
-e XUI_SMOKE_VERSION="$XUI_SMOKE_VERSION" \
-e DEBIAN_FRONTEND=noninteractive \ -e DEBIAN_FRONTEND=noninteractive \
"$IMAGE" bash -euo pipefail -c ' "$IMAGE" bash -euo pipefail -c '
apt-get update -qq apt-get update -qq
apt-get install -y -qq curl tar openssl ca-certificates > /dev/null apt-get install -y -qq curl tar openssl ca-certificates > /dev/null
echo "--- running install.sh piped (no TTY) ---" echo "--- running install.sh piped (no TTY), version: ${XUI_SMOKE_VERSION:-latest} ---"
# Piping guarantees stdin is not a TTY, exercising the auto non-interactive path. # Piping guarantees stdin is not a TTY, exercising the auto non-interactive path.
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
cat /root/install.sh | bash -s -- "$XUI_SMOKE_VERSION"
else
cat /root/install.sh | bash cat /root/install.sh | bash
fi
echo "--- assertions ---" echo "--- assertions ---"
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
installed=$(/usr/local/x-ui/x-ui -v)
[ "$installed" = "${XUI_SMOKE_VERSION#v}" ] \
|| { echo "FAIL: installed version $installed, want ${XUI_SMOKE_VERSION#v}"; exit 1; }
fi
RESULT=/etc/x-ui/install-result.env RESULT=/etc/x-ui/install-result.env
test -f "$RESULT" || { echo "FAIL: $RESULT missing"; exit 1; } test -f "$RESULT" || { echo "FAIL: $RESULT missing"; exit 1; }
+3
View File
@@ -18,6 +18,9 @@ services:
volumes: volumes:
- $PWD/db/:/etc/x-ui/ - $PWD/db/:/etc/x-ui/
- $PWD/cert/:/root/cert/ - $PWD/cert/:/root/cert/
# Persists acme.sh state so certificate auto-renewal survives container
# recreation (the entrypoint re-registers the renewal cron job from it).
- $PWD/acme/:/root/.acme.sh/
environment: environment:
XRAY_VMESS_AEAD_FORCED: "false" XRAY_VMESS_AEAD_FORCED: "false"
XUI_ENABLE_FAIL2BAN: "true" XUI_ENABLE_FAIL2BAN: "true"
+581
View File
@@ -0,0 +1,581 @@
# 3x-ui — Architecture & Code Map
> Navigation map for contributors and AI coding agents (referenced from `CLAUDE.md`).
> Goal: jump to the right file in one hop instead of grepping the whole tree.
> Tracks the `main` branch — paths reflect the latest changes, so verify against the live
> tree rather than a pinned release (Go module `github.com/mhsanaei/3x-ui/v3`).
>
> **How to use this file:** read "Mental model" + "Request lifecycle" first, then
> use the **Symptom → File index** to locate work. Respect the **Layering rules**
> when adding code. Verify with the commands in **Build / Test / Lint**.
---
## 1. Mental model (the 30-second version)
3x-ui is a **web control panel for [Xray-core](https://github.com/XTLS/Xray-core)**. The Go
backend is the source of truth: it stores inbounds/clients/settings in a DB, renders an
Xray JSON config from that state, supervises the Xray child process, and exposes a REST +
WebSocket API. A React SPA (built by Vite, embedded into the Go binary) is the UI. A second,
separate HTTP server serves **subscription links** to end users.
The panel supervises **two managed child processes**: Xray-core itself and — when MTProto
inbounds exist — the `mtg` Telegram-proxy binary (`internal/mtproto/`).
Servers and processes, all launched from `main.go`:
| Server / process | Package | Purpose | Default port |
|---|---|---|---|
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
| **mtg** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds | per inbound |
Two key ideas that explain most of the complexity:
1. **The DB → Xray config pipeline.** Inbounds/clients live in the DB. On every change the
backend regenerates the Xray config and applies it — preferring a *hot diff* (live gRPC
API mutation) over a full process restart. See §5.1.
2. **The Runtime abstraction (multi-node).** A panel can manage remote "nodes" (other 3x-ui
instances). Every state-changing inbound/client operation is dispatched through a
`runtime.Runtime` interface that is either **`Local`** (this box's Xray gRPC API) or
**`Remote`** (HTTPS call to a child node, with `verify`/`skip`/`pin`/`mtls` TLS modes).
This is the single most important abstraction in the project. See §5.2.
---
## 2. Tech stack
**Backend (Go 1.26):**
- Web framework: **Gin** (`gin-gonic/gin`) + sessions (cookie store), gzip.
- ORM: **GORM** with **SQLite** (default) or **PostgreSQL** (`XUI_DB_TYPE=postgres`).
- Scheduler: **robfig/cron/v3** (seconds-precision) for all background jobs.
- Xray: **xtls/xray-core** vendored as a library; the panel talks to the running core over
its **gRPC API** and also shells out to manage the process.
- Telegram bot: **mymmrac/telego**. i18n: **nicksnyder/go-i18n**.
- Misc: gorilla/websocket, gopsutil (system stats), go-qrcode, gotp (2FA TOTP).
**Frontend (`frontend/`):**
- **React 19** + **Ant Design 6** + **Vite 8** + **TypeScript**.
- Data layer: **TanStack Query** (`@tanstack/react-query`) over **axios**; **Zod 4** schemas.
- Router: **react-router-dom 7**. Charts: **recharts**. Editor: **CodeMirror 6**.
- **Build output goes to `internal/web/dist/`** (see `vite.config.js` → `outDir`) and is
embedded into the Go binary with `go:embed`. Three HTML entries: `index.html` (panel SPA),
`login.html`, `subpage.html`. The Go server serves the SPA; there is no separate frontend
deployment.
**Important:** the legacy Go-template UI and `web/assets/` are **gone**. All HTML/JS comes
from the embedded Vite `dist/`. Don't look for `.html` templates in `internal/web`.
---
## 3. Request lifecycle (follow the data)
### 3.1 Admin API request (e.g. "add a client")
```
Browser (React, axios)
→ POST {basePath}/panel/api/...
→ Gin engine (internal/web/web.go: initRouter)
→ middleware chain: SecurityHeaders → MaxBodyBytes (10 MiB; importDB exempt)
→ [DomainValidator, if webDomain set] → gzip → sessions("3x-ui")
→ base-path/cache-control context → Localizer
→ API routes add: ConfigEnvelope (zstd + SHA-256) → CSRF
→ Controller (internal/web/controller/*.go) // HTTP concerns only: bind, validate, respond
→ Service (internal/web/service/*.go) // business logic + transactions
→ GORM → DB (internal/database) // persistence
→ runtime.Runtime dispatch // apply to Xray (Local) or node (Remote)
→ Local: internal/xray (gRPC API or config regen + restart)
→ Remote: internal/web/runtime/remote.go → HTTPS → child node's API
```
The controller layer is thin. **Business logic lives in services.** When something is wrong
with *behavior*, the bug is almost always in a service file, not a controller.
### 3.2 Subscription request (end-user fetching their config)
```
End user → GET {subPath}/{subId} (separate server, internal/sub)
→ internal/sub/controller.go (routes: raw / JSON / Clash variants, feature-flagged)
→ internal/sub/service.go (~2.5k lines — the link/config builder)
→ reads inbounds+clients+hosts from DB, renders per-protocol share links /
Clash YAML / JSON (Host rows can override address/SNI/path per inbound)
```
### 3.3 Background work (cron jobs)
Scheduled in `internal/web/web.go` → `startTask()`. Each job is a struct in
`internal/web/job/`. Examples: poll Xray traffic every 5s, check client IP limits every 10s,
node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly). See §5.4.
---
## 4. Directory map (what lives where)
```
3x-ui/
├── main.go # Entry point: CLI (run / migrate / migrate-db / setting / cert),
│ # bootstrap, signal handling, restart loop
├── go.mod / go.sum # Go deps (module path ends in /v3)
│
├── internal/ # ALL backend Go code (private packages)
│ ├── config/ # Env-var config: paths, DB kind/DSN, log level, version
│ │ # Every XUI_* env var is read here (config.go)
│ ├── database/
│ │ ├── db.go # InitDB: connect, AutoMigrate, seeders (~1.4k lines). DB hotspot.
│ │ ├── migrate_data.go # Data migrations (seeders/normalizers beyond AutoMigrate)
│ │ ├── dialect.go # SQLite vs Postgres SQL differences
│ │ ├── dump_sqlite.go # DB export/backup
│ │ └── model/ # **ALL GORM models** (model.go ~1.1k lines + siblings:
│ │ # node_client_traffic.go, node_client_ip.go,
│ │ # client_global_traffic.go). ⭐ Start here for data shape.
│ ├── eventbus/ # In-process pub/sub (buffered channel): outbound.down|up,
│ │ # xray.crash, node.down|up, cpu.high, memory.high, login.attempt
│ ├── tunnelmonitor/ # Optional tunnel health probe (XUI_TUNNEL_HEALTH_* env vars):
│ │ # HTTP probe (default Cloudflare trace); repeated failures
│ │ # trigger an Xray restart hook. Independent of panel settings.
│ ├── xray/ # Xray-core integration (the proxy engine wrapper)
│ │ ├── process.go # Spawn/supervise the Xray child process (~750 lines)
│ │ ├── api.go # gRPC client to a running Xray (add/remove user, stats) (~800 lines)
│ │ ├── hot_diff.go # ⭐ Compute minimal live changes to avoid full restart (~500 lines)
│ │ ├── config.go # Xray config object model
│ │ ├── inbound.go # Inbound JSON shaping
│ │ ├── client_traffic.go # ClientTraffic model (persisted as client_traffics)
│ │ ├── traffic.go # Traffic type helpers
│ │ └── log_writer.go # Pipe Xray stdout/stderr into the panel logger
│ │
│ ├── web/ # The panel server
│ │ ├── web.go # ⭐ Server bootstrap: initRouter (all routes) + startTask (all cron jobs)
│ │ ├── controller/ # HTTP handlers (thin). One file per resource:
│ │ │ ├── inbound.go # /panel/api/inbounds
│ │ │ ├── client.go # /panel/api/clients (CRUD + bulk + ips + onlines)
│ │ │ ├── group.go # client-group endpoints
│ │ │ ├── node.go # /panel/api/nodes (multi-node management)
│ │ │ ├── host.go # /panel/api/hosts (per-inbound subscription host overrides)
│ │ │ ├── server.go # /panel/api/server (status, xray version, certs, logs, DB import/export)
│ │ │ ├── setting.go # /panel/api/setting (settings + API tokens)
│ │ │ ├── xray_setting.go # /panel/api/xray (raw Xray config editor, WARP/Nord)
│ │ │ ├── api.go # /panel/api gateway (token auth, envelope + CSRF wiring)
│ │ │ ├── index.go # login/logout/csrf/2FA
│ │ │ ├── spa.go # SPA fallback for /panel UI routes
│ │ │ └── websocket.go # WS upgrade endpoint
│ │ ├── service/ # ⭐⭐ Business logic. This is where most real work happens.
│ │ │ ├── inbound.go # Inbound CRUD core (~1.4k lines)
│ │ │ ├── inbound_node.go # ⭐ Node sync for inbounds: reconcile, traffic merge (~1.1k lines)
│ │ │ ├── inbound_traffic.go # Per-client traffic accounting (~1.1k lines)
│ │ │ ├── inbound_clients.go # Client-within-inbound operations
│ │ │ ├── inbound_sublink.go # Inbound-level subscription link helpers
│ │ │ ├── inbound_migration.go # Inbound schema/format migrations
│ │ │ ├── client_crud.go # Client create/read/update/delete
│ │ │ ├── client_bulk.go # Bulk client ops (~1.6k lines)
│ │ │ ├── client_inbound_apply.go # ⭐ Apply client changes to runtime (Local/Remote) (~1.2k lines)
│ │ │ ├── client_groups.go # Client grouping
│ │ │ ├── client_link.go # Per-client share-link generation
│ │ │ ├── client_external_link.go # External links attached to clients
│ │ │ ├── client_wireguard.go # WireGuard client specifics
│ │ │ ├── client_paging.go # Server-side pagination/sort/filter for client lists
│ │ │ ├── node.go # ⭐ NodeService: CRUD, probe, heartbeat, dirty-tracking (~1.1k lines)
│ │ │ ├── node_mtls.go # Node mTLS certificate management (master side)
│ │ │ ├── node_tree.go # Node hierarchy / descendants
│ │ │ ├── host.go # Host rows (subscription output overrides)
│ │ │ ├── server.go # ServerService: status, certs, xray install, DB ops (~2.2k lines)
│ │ │ ├── setting.go # SettingService: all panel settings + defaults (~1.3k lines)
│ │ │ ├── setting_mtls.go # mTLS settings (node hardening)
│ │ │ ├── traffic_writer.go # Batched persistence of traffic deltas to the DB
│ │ │ ├── xray.go # ⭐ XrayService: config gen + restart/hot-apply (~1.2k lines)
│ │ │ ├── xray_setting.go # Raw Xray config persistence
│ │ │ ├── xray_metrics.go # Xray observability metrics
│ │ │ ├── metric_history.go # Historical system/xray metrics
│ │ │ ├── reality_scan.go # REALITY target scanner
│ │ │ ├── url_safety.go # Outbound URL validation (SSRF guards)
│ │ │ ├── outbound_subscription.go# Outbound subscription (e.g. Warp/Nord provider configs)
│ │ │ ├── port_conflict.go # Detect inbound port collisions
│ │ │ ├── fallback.go # Xray fallback (SNI/ALPN routing on shared port)
│ │ │ ├── email/ # Email notification service (SMTP)
│ │ │ ├── integration/ # External providers: warp.go (Cloudflare WARP), nord.go (NordVPN)
│ │ │ ├── outbound/ # Outbound config service
│ │ │ ├── panel/ # Cross-cutting panel services:
│ │ │ │ ├── panel.go # panel-level helpers
│ │ │ │ ├── user.go # admin user auth (bcrypt)
│ │ │ │ ├── api_token.go # API token CRUD (SHA-256 hashed)
│ │ │ │ └── websocket.go # WS hub / push service
│ │ │ └── tgbot/ # Telegram bot command handlers
│ │ ├── runtime/ # ⭐⭐ The Local/Remote node abstraction (see §5.2)
│ │ │ ├── runtime.go # the Runtime interface (the contract)
│ │ │ ├── local.go # Local impl → this box's Xray gRPC API
│ │ │ ├── remote.go # Remote impl → HTTPS calls to a child node
│ │ │ ├── tls_client.go # per-node HTTP client: verify / skip / pin / mtls
│ │ │ └── manager.go # RuntimeFor(nodeID) → picks Local or Remote
│ │ ├── job/ # Cron job structs (one file per job — see §5.4)
│ │ ├── middleware/ # Gin middleware: security.go (headers/HSTS), bodylimit.go,
│ │ │ # domainValidator.go, validate.go (CSRF), config_envelope.go
│ │ ├── global/ # Global singletons: web server + sub server handles, restart hook
│ │ ├── network/ # Custom net listeners (e.g. proxy-protocol aware)
│ │ ├── session/ # Session/cookie helpers
│ │ ├── websocket/ # WS hub implementation
│ │ ├── locale/ + translation/ # i18n middleware + 13 locale JSON catalogs
│ │ ├── entity/ # Shared request/response DTOs
│ │ └── dist/ # ⚠️ Vite build output, embedded via go:embed (generated — do not hand-edit)
│ │
│ ├── sub/ # The subscription server (separate from panel)
│ │ ├── sub.go # server bootstrap
│ │ ├── controller.go # routes for raw / JSON / Clash subscription formats
│ │ ├── service.go # ⭐ The link/config builder (~2.5k lines — share-link logic lives here)
│ │ ├── json_service.go # JSON subscription format
│ │ ├── clash_service.go # Clash/Mihomo YAML format
│ │ ├── clash_external.go # external Clash config integration
│ │ ├── external_subscription.go / external_config.go # external sub import/aggregation
│ │ ├── host_sub.go # Host-row overrides applied to subscription output
│ │ ├── endpoint.go # subscription endpoint configuration
│ │ ├── vless_route.go # VLESS route shaping
│ │ ├── remark_vars.go # remark variable expansion
│ │ └── links.go # link helpers
│ │
│ ├── mtproto/ # Embedded MTProto (Telegram) proxy: manager.go + per-OS
│ │ # process supervision + orphan cleanup
│ ├── logger/ # App logger (op/go-logging + lumberjack rotation)
│ └── util/ # Leaf helpers (no business logic):
│ ├── common/ # errors, misc
│ ├── crypto/ # key/cert generation (x25519, ML-KEM/ML-DSA, ECH)
│ ├── link/ # outbound share-link building primitives
│ ├── wirecodec/ + wireguard/ # WireGuard codec + integration helpers
│ └── random/, json_util/, reflect_util/, sys/, netproxy/, netsafe/, ldap/
│
├── frontend/ # React SPA (built into internal/web/dist)
│ ├── vite.config.js # ⭐ Build config: outDir → ../internal/web/dist, dev on :5173
│ │ # (strict) proxying to :2053, entries index/login/subpage.html
│ ├── package.json # scripts: dev / build / preview / lint / typecheck / test / gen
│ └── src/
│ ├── main.tsx / routes.tsx / queryClient.ts # SPA entry, router, query client
│ ├── entries/ # Extra HTML entry points: login.tsx, subpage.tsx
│ ├── pages/ # ⭐ Route screens. Mirrors the panel's feature areas:
│ │ ├── inbounds/ # inbound list + the big inbound form (protocols/security/transport)
│ │ ├── clients/ # client management screens
│ │ ├── nodes/ # multi-node UI
│ │ ├── hosts/ # subscription host-override UI
│ │ ├── xray/ # raw Xray config UI (routing, dns, outbounds, balancers, overrides)
│ │ ├── index/ # dashboard/home
│ │ └── settings/, groups/, sub/, login/, api-docs/
│ ├── api/ # ⭐ Data layer: axios-init, QueryProvider, queryKeys, websocket bridge
│ │ └── queries/ # TanStack Query hooks (useNodesQuery, useStatusQuery, …)
│ ├── schemas/ # Zod schemas: protocols, forms, api, primitives
│ ├── generated/ # ⚠️ GENERATED from Go (see §5.5): schemas.ts, types.ts, zod.ts, examples.ts
│ ├── components/ # Reusable UI (clients/ form/ ui/ viz/ feedback/ utility/)
│ ├── lib/ # Frontend domain logic (xray/ inbounds/ clients/)
│ ├── hooks/, models/, layouts/, i18n/, utils/, styles/
│ └── test/ # Vitest + golden fixtures (config-generation snapshot tests)
│
├── tools/openapigen/ # ⭐ Go program that emits frontend/src/generated/* from Go types (§5.5)
├── docs/ # Markdown docs (this file, custom-subscription-templates.md, …)
├── media/ # README images
│
├── Dockerfile / docker-compose.yml / DockerEntrypoint.sh / DockerInit.sh # Container build/run
├── install.sh / update.sh / x-ui.sh # VPS install + management CLI
├── x-ui.service.* / x-ui.rc # systemd units (debian/rhel/arch) + rc script
├── windows_files/ # Windows service support
└── .github/workflows/ # CI: ci.yml, codeql.yml, docker.yml, release.yml, smoke.yml,
# mutation.yml, cleanup_caches.yml, claude-bot.yml
```
---
## 5. Cross-cutting subsystems (the parts that span many files)
### 5.1 DB → Xray config pipeline (config generation & application)
The panel never edits Xray's running config directly from controllers. The flow is:
1. A service mutates DB state (inbound/client/setting).
2. `XrayService` (`service/xray.go`) builds a fresh `xray.Config` from DB state
(`GetXrayConfig`).
3. It tries a **hot apply** (`tryHotApply` → `xray/hot_diff.go`): diff old vs new config and
push only the deltas over the Xray gRPC API (add/remove inbound, add/remove user) — **no
process restart**, so live connections survive.
4. If the diff isn't hot-applicable (structural change), it falls back to a **full restart**
of the Xray process (`xray/process.go`).
Restart is debounced via an atomic "need restart" flag (`SetToNeedRestart` /
`IsNeedRestartAndSetFalse`), consumed by a `@every 30s` cron task registered in `startTask()`
— any number of mutations inside the window causes at most one restart.
**Key files:** `service/xray.go` (orchestration), `xray/hot_diff.go` (the diff algorithm),
`xray/process.go` (process lifecycle), `xray/api.go` (gRPC calls), `xray/config.go` (config model).
### 5.2 Runtime abstraction — Local vs Remote (multi-node) ⭐ most important
A "node" (`model.Node`) is another 3x-ui instance this panel controls. Every state-changing
inbound/client operation goes through the `runtime.Runtime` interface so the *same service
code* works whether the target is the local Xray or a remote node.
- **Interface:** `internal/web/runtime/runtime.go` — `Name`, `AddInbound`, `DelInbound`,
`UpdateInbound`, `AddUser`, `RemoveUser`, `UpdateUser`, `DeleteUser`, `AddClient`,
`RestartXray`, `ResetClientTraffic`, `ResetInboundTraffic`, `ResetAllTraffics`.
- **`Local`** (`local.go`): calls this box's Xray gRPC API directly.
- **`Remote`** (`remote.go`): serializes the operation and sends it over HTTPS to the child
node's API.
- **TLS modes** (`tls_client.go`, per-node `TlsVerifyMode`):
`verify` (system CAs, default) / `skip` (no validation) / `pin` (leaf cert SHA-256 must
match `PinnedCertSha256`) / `mtls` (master presents a client certificate; node cert checked
against system roots; API token optional). Master-side cert management:
`service/node_mtls.go` + `service/setting_mtls.go`.
- **Dispatch:** `manager.go` → `Manager.RuntimeFor(nodeID *int)`; `nil` nodeID → `Local`,
otherwise a cached/lazy-loaded `Remote`. `InvalidateNode(id)` drops a cached remote client.
**Node identity & attribution (the hard part).** Inbounds carry a `NodeID` *and* an
`OriginNodeGuid`. Because inbounds can be pushed across hops, the panel attributes traffic and
online clients back to the originating panel using **stable GUIDs** rather than local IDs.
Relevant logic: `service/inbound_node.go` (`ReconcileNode`, `SetRemoteTraffic`, GUID merge,
`synthNodeGuid`, `panelGuid`) and `service/node.go` (`effectiveNodeGuid`, heartbeat, dirty
tracking). Node "dirty" flags drive an **anti-entropy reconciliation** so an offline node's
inbound edits converge once it reconnects.
**Where to look for node bugs:**
- Operation not reaching a node → `runtime/remote.go` + `runtime/manager.go`.
- Wrong traffic/online attribution across hops → `service/inbound_node.go` (GUID merge paths).
- Node shown offline / stale status → `job/node_heartbeat_job.go` + `service/node.go` (`Probe`, `UpdateHeartbeat`).
- Edits to an offline node not applying on reconnect → dirty/reconcile logic in `service/inbound_node.go` + `service/node.go` (`MarkNodeDirty`/`ClearNodeDirty`/`NodeSyncState`).
- TLS/mTLS handshake failures → `runtime/tls_client.go`, `service/node_mtls.go`, `service/node.go` (`FetchCertFingerprint`).
### 5.3 Traffic accounting
Per-client and per-inbound up/down counters originate from Xray's stats API and are persisted
to the DB. The Xray traffic job polls the core; node traffic is pulled from child nodes and
merged with GUID-based baselines to avoid double counting after resets.
**Key files:** `service/inbound_traffic.go`, `service/traffic_writer.go`,
`job/xray_traffic_job.go`, `job/node_traffic_sync_job.go`, `service/inbound_node.go`
(`SetRemoteTraffic` / `upsertNodeBaseline`), models `xray.ClientTraffic`,
`model.NodeClientTraffic`, `model.ClientGlobalTraffic` (cross-master totals).
Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.TrafficReset`).
### 5.4 Background jobs (cron)
All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` method in `internal/web/job/`:
| Schedule | Job | Purpose / condition |
|---|---|---|
| `@every 1s` | `check_xray_running_job` | Restart Xray if it died (2 consecutive down checks) |
| `@every 30s` | (inline func in `startTask`) | Debounced Xray restart — consumes the "need restart" flag (§5.1) |
| `@every 5s` | `xray_traffic_job` | Pull traffic stats from Xray (5s start delay) |
| `@every 5s` | `node_heartbeat_job` | Probe child nodes (online/offline) |
| `@every 5s` | `node_traffic_sync_job` | Pull + merge node traffic; push reconciliation |
| `@every 10s` | `check_client_ip_job` | Enforce per-client IP limits |
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")` | Log cleanup; resets |
| `@weekly` / `@monthly` | `periodic_traffic_reset_job(...)` | Weekly/monthly traffic resets |
| default `@every 1m` | `ldap_sync_job` | Only if LDAP enabled; schedule configurable |
| default `@daily` | `stats_notify_job` | Only if TG bot enabled; schedule configurable |
| `@every 2m` | `check_hash_storage` | Only if TG bot enabled; expires bot callback hashes |
| `@every 1m` | `check_cpu_usage` | Only if a CPU alarm is configured (TG or email); publishes `cpu.high` |
| `@every 1m` | `check_memory_usage` | Only if a memory alarm is configured; publishes `memory.high` |
| configurable | `free_os_memory` | Only if `sys.MemoryReleaseIntervalMinutes() > 0`; returns heap to OS |
To change *when* something runs, edit `startTask()`. To change *what* it does, edit the job file.
### 5.5 Type generation (Go → TypeScript) ⚠️ don't hand-edit generated files
The Go backend is the schema source of truth. `tools/openapigen` (a Go program, with a
`StructAllow` allowlist of exported types) emits
`frontend/src/generated/{schemas,types,zod,examples}.ts`. The frontend build runs this first:
- `npm run gen:zod` → `go run ./tools/openapigen` (regenerate from Go)
- `npm run gen:api` → builds the OpenAPI doc (`scripts/build-openapi.mjs`, driven by the
hand-maintained endpoint registry `src/pages/api-docs/endpoints.ts`)
- `npm run build` runs `gen:api` then `vite build`.
**Implication:** if you change a Go model/DTO that crosses the API boundary, regenerate the
frontend types (`cd frontend && npm run gen`) instead of editing `src/generated/` by hand.
### 5.6 Share-link / subscription generation
Two distinct code paths produce client configs:
- **Per-client links in the panel** (the "copy link" / QR in the UI): `service/client_link.go`
+ `util/link/outbound.go`.
- **Subscription endpoint** (what a client app polls): `internal/sub/service.go` (raw links),
`internal/sub/json_service.go` (JSON), `internal/sub/clash_service.go` (Clash YAML).
**`Host` rows** (`model.Host`, edited under /panel/api/hosts) override address/SNI/path/
security per inbound in subscription output — applied in `sub/host_sub.go`.
Both paths must agree per protocol. A malformed link for a specific protocol/transport combo
(e.g. XHTTP + Reality) is usually a field-lookup mismatch in **`internal/sub/service.go`** (and
its tests `service_test.go` / golden fixtures), or in `util/link/outbound.go`. The frontend
also has protocol schemas under `frontend/src/schemas/protocols/` and `frontend/src/lib/xray/`.
### 5.7 Event bus (in-process pub/sub)
`internal/eventbus/` is a minimal buffered-channel pub/sub. Producers call a non-blocking
`Publish(Event)`; all subscribers receive every event. Event types: `outbound.down|up`,
`xray.crash`, `node.down|up`, `cpu.high`, `memory.high`, `login.attempt`, with structured
payloads (OutboundHealthData, NodeHealthData, LoginEventData, SystemMetricData). Producers
include the CPU/memory jobs, node heartbeat, and login handling; consumers include the
Telegram bot and the email notifier (`service/email/`). Use it for cross-cutting
notifications instead of importing notification services into producers.
### 5.8 Tunnel health monitor
`internal/tunnelmonitor/` is an optional watchdog configured **only via env vars**
(`XUI_TUNNEL_HEALTH_*`, read in `internal/config/`), deliberately independent of panel
settings so it can be enabled from a systemd `EnvironmentFile` even when the panel is
unreachable. It periodically probes an HTTP URL (default: Cloudflare trace endpoint) through
the tunnel; after N successive failures (default 3) it fires a recovery callback wired to an
Xray restart.
---
## 6. Data model cheat-sheet
GORM models in `internal/database/model/` (main file `model.go` + siblings); all registered
for AutoMigrate in `internal/database/db.go`.
| Model | Table role | Notable fields |
|---|---|---|
| `User` | Admin login | bcrypt password, `LoginEpoch` (invalidates sessions) |
| `Inbound` | An Xray inbound | `Tag` (unique), `Port`, `Protocol`, `Settings`/`StreamSettings`/`Sniffing` (JSON), `Enable`, `TrafficReset`, `NodeID`, **`OriginNodeGuid`**, `ClientStats` (assoc) |
| `Client` | In-memory client view | UUID/email/flow/limits (parsed from inbound JSON; not persisted) |
| `ClientRecord` | Persisted client (`clients`) | `Email` (unique), `SubID`, `UUID`, `TotalGB`, `ExpiryTime`, `LimitIP`, `Group`, `Reset` |
| `ClientGroup` / `ClientInbound` | Grouping + client↔inbound join | many-to-many wiring, `FlowOverride` |
| `ClientExternalLink` | Extra links attached to a client | `Kind`, `Value`, `Remark`, `SortIndex` |
| `Host` | Subscription host overrides (per inbound) | `Address`, `Port`, `Sni`, `Path`, `Security`, `Fingerprint`, `SortOrder`, visibility/exclusion flags |
| `Node` | A managed child panel | `Guid`, `Address`, `Status`, `TlsVerifyMode`, `PinnedCertSha256`, `ConfigDirty`, version/heartbeat/metric fields |
| `NodeClientTraffic` | Per-node client traffic baseline | cross-node merge (anti-double-count) |
| `NodeClientIp` | Per-node client IP attribution | `NodeGuid`, `Email`, `Ips` |
| `ClientGlobalTraffic` | Cross-master usage totals | `MasterGuid`, `Email`, `Up`, `Down` |
| `xray.ClientTraffic` | Per-client counters (`client_traffics`) | `Email`, `Up`, `Down`, `Total`, `ExpiryTime`, `LastOnline` |
| `InboundClientIps` | IP set per client email | drives IP-limit enforcement |
| `OutboundTraffics` | Outbound counters | per outbound tag |
| `OutboundSubscription` | External provider subs | Warp/Nord style |
| `Setting` | Key/value panel settings | everything configurable |
| `ApiToken` | REST API tokens | SHA-256 hash (plaintext shown once) |
| `InboundFallback` | Fallback routing on a shared port | SNI/ALPN/path → dest |
| `HistoryOfSeeders` | Seeder bookkeeping | prevents re-running one-off migrations |
---
## 7. Symptom → File index (start here when debugging)
| Symptom / task | Primary file(s) | Then check |
|---|---|---|
| Add/modify an **API endpoint** | `controller/<resource>.go` (route registration at top of each file) | corresponding `service/*.go`, `frontend/src/pages/api-docs/endpoints.ts` |
| **Inbound** create/update/delete behavior | `service/inbound.go`, `service/inbound_clients.go` | `runtime/*`, `service/xray.go` |
| **Client** CRUD / limits / expiry | `service/client_crud.go`, `service/client_inbound_apply.go` | model `ClientRecord`, `service/inbound_traffic.go` |
| **Bulk** client operations slow/wrong | `service/client_bulk.go` | `service/client_paging.go` |
| Xray **won't apply** a config change | `service/xray.go` (`RestartXray`, `tryHotApply`) | `xray/hot_diff.go`, `xray/process.go` |
| Xray **restarts when it shouldn't** (kills connections) | `xray/hot_diff.go` (diff not classified as hot) | `service/xray.go` |
| **Traffic** counts wrong / reset behavior | `service/inbound_traffic.go`, `job/xray_traffic_job.go` | `service/traffic_writer.go`, `job/periodic_traffic_reset_job.go` |
| **Node** operation not propagating | `runtime/remote.go`, `runtime/manager.go` | `service/inbound_node.go` |
| **Multi-hop / cross-node attribution** (traffic or online clients on wrong panel) | `service/inbound_node.go` (GUID merge, `synthNodeGuid`, `effectiveNodeGuid`) | `service/node.go`, model `OriginNodeGuid`/`Node.Guid` |
| Node stuck **offline / stale** | `job/node_heartbeat_job.go`, `service/node.go` (`Probe`, `UpdateHeartbeat`) | `runtime/tls_client.go` (TLS verify) |
| Node **TLS / mTLS** auth failures | `runtime/tls_client.go`, `service/node_mtls.go`, `service/setting_mtls.go` | `service/node.go` (`FetchCertFingerprint`) |
| Offline node edits **not reconciling** on reconnect | `service/inbound_node.go` (`ReconcileNode`, dirty flags) | `service/node.go` (`MarkNodeDirty`/`NodeSyncState`) |
| **Share link / QR** malformed (per protocol) | `service/client_link.go`, `util/link/outbound.go` | `frontend/src/lib/xray/`, `frontend/src/schemas/protocols/` |
| **Subscription** output wrong (raw/JSON/Clash) | `internal/sub/service.go` | `sub/json_service.go`, `sub/clash_service.go`, sub golden tests |
| Subscription **host overrides** not applied | `service/host.go`, `sub/host_sub.go` | model `Host`, `frontend/src/pages/hosts/` |
| **External subscription** import/aggregation | `sub/external_subscription.go`, `sub/external_config.go` | `sub/clash_external.go` |
| **Settings** not saving / defaults | `service/setting.go`, `controller/setting.go` | model `Setting` |
| **Login / 2FA / sessions / CSRF** | `controller/index.go`, `service/panel/user.go`, `middleware/` | `session/` |
| **API tokens** | `service/panel/api_token.go`, `controller/setting.go` | model `ApiToken` |
| **Port conflict** on inbound add | `service/port_conflict.go` | `controller/inbound.go` |
| **Fallbacks** (shared 443, SNI routing) | `service/fallback.go`, `controller/inbound.go` | model `InboundFallback` |
| **Telegram bot** commands | `service/tgbot/` | `job/stats_notify_job.go` |
| **Email notifications** | `service/email/` | `internal/eventbus/` (consumers) |
| **CPU / memory alerts** not firing | `job/check_cpu_usage.go`, `job/check_memory_usage.go` | `internal/eventbus/`, notifier settings in `service/setting.go` |
| Xray auto-restart on **dead tunnel** | `internal/tunnelmonitor/` | `XUI_TUNNEL_HEALTH_*` in `internal/config/` |
| **WARP / Nord** outbound integration | `service/integration/warp.go` / `nord.go` | `service/outbound_subscription.go` |
| **MTProto** proxy issues | `internal/mtproto/manager.go`, `mtproto/process*.go` | `job/mtproto_job.go` |
| **DB migration** / new column | `internal/database/db.go` (AutoMigrate list), `migrate_data.go` | `model/model.go` |
| **Cron schedule** changes | `web.go` → `startTask()` | the specific `job/*.go` |
| **CORS / security headers / HTTPS** | `middleware/`, `web.go` (`initRouter`, TLS setup) | `config/` (env) |
| **Env vars / paths / DB type** | `internal/config/config.go` | `.env.example` |
| **Frontend route / screen** | `frontend/src/pages/<area>/`, `frontend/src/routes.tsx` | `frontend/src/api/queries/` |
| **Frontend ↔ backend type mismatch** | regenerate: `cd frontend && npm run gen` (`tools/openapigen`) | `frontend/src/generated/` |
| **System status / CPU / metrics** | `service/server.go`, `service/xray_metrics.go`, `service/metric_history.go` | `controller/server.go`, gopsutil |
---
## 8. Layering rules (where new code belongs)
1. **Controllers are thin.** Only: bind/validate input, call one service, shape the HTTP
response. No DB queries, no Xray calls, no business rules in `controller/`.
2. **Services own the logic and transactions.** All business rules, DB access, and decisions
about applying changes live in `service/`. If you're tempted to query GORM from a
controller, move it to a service.
3. **Never touch Xray's running state from a controller or job directly.** Go through
`XrayService` / the `runtime.Runtime` interface so local vs node dispatch stays correct.
4. **Any state-changing inbound/client op must dispatch through `runtime.Runtime`**, not
straight to `xray/api.go` — otherwise node deployments silently break.
5. **`internal/util/*` is leaf-only** (no imports of `service`/`controller`/`database`). Keep
helpers pure.
6. **Don't hand-edit generated files:** `frontend/src/generated/*` and `internal/web/dist/*`.
Regenerate instead.
7. **Models are the contract.** Changing a model field that crosses the API boundary means:
update `model.go` → handle migration in `db.go`/`migrate_data.go` → regenerate frontend types.
8. **Two servers, two concerns.** Admin features go in `internal/web`; anything an *end user*
fetches goes in `internal/sub`. Don't blur them.
9. **Cross-cutting notifications go through `internal/eventbus/`** — publish an event instead
of importing the Telegram/email services into producers.
---
## 9. Build / Test / Lint (verify your changes)
The canonical gate is the **Makefile** (mirrors CI): `make verify`. Also: `make gen`
(regenerate Zod/OpenAPI), `make lint` (Go + frontend), `make test` (Go `-shuffle=on` +
frontend), `make race`, `make build`. Run `make help` for everything. Raw commands:
**Backend (Go):**
```bash
go build ./... # compile everything
go test ./... # run all Go tests (many *_test.go alongside sources)
go test ./internal/web/service/... # focused: service-layer tests
go test ./internal/xray/... # hot-diff / process / api tests
go test ./internal/sub/... # subscription + golden link tests
go vet ./... # static checks
golangci-lint run # full lint (gofumpt + goimports formatting)
go run main.go # run the panel locally (serves embedded dist if built)
```
**Frontend (`cd frontend`, Node ≥ 22):**
```bash
npm install
npm run dev # Vite dev server on :5173; proxies API to Go backend on :2053 (run `go run main.go` too)
npm run typecheck # tsc --noEmit
npm run lint # eslint src
npm run test # vitest (incl. golden config-generation snapshots)
npm run gen # regenerate src/generated/* from Go (gen:zod + gen:api)
npm run build # gen:api + vite build → outputs to internal/web/dist (then rebuild Go binary to embed)
```
**Full local loop:** `cd frontend && npm run build` (refresh embedded `dist/`) → back to repo
root → `go build ./...` / `go run main.go`.
**Docker:** `docker compose up -d` (uses `Dockerfile` + `DockerEntrypoint.sh`).
**CI** (`.github/workflows/`): `ci.yml` (build/test/lint), `codeql.yml` (security scan),
`smoke.yml` (smoke tests), `mutation.yml` (mutation testing), `docker.yml` + `release.yml`
(multi-arch image + release builds), `cleanup_caches.yml`, `claude-bot.yml` (issue bot).
---
## 10. Gotchas & conventions
- **Module path is `.../v3`.** Internal imports use `github.com/mhsanaei/3x-ui/v3/internal/...`.
- **SQLite vs Postgres.** Default is SQLite at `{XUI_DB_FOLDER}/x-ui.db`. Postgres via
`XUI_DB_TYPE=postgres` + `XUI_DB_DSN`. Some SQL paths are dialect-aware (`database/dialect.go`);
test both when touching raw queries (there are `*_scale_postgres_test.go` suites).
- **`Inbound.Settings` / `StreamSettings` / `Sniffing` are raw JSON strings**, not structured
columns. Parsing/validation happens in services and the `xray` package, not in GORM.
- **Hot-reload is the default; full restart is the fallback.** Changes that look config-only
but cause a restart usually mean the diff in `xray/hot_diff.go` didn't recognize them as hot.
- **Node TLS:** remote calls honor `TlsVerifyMode` (`verify`/`skip`/`pin`/`mtls`). "Works on
skip, fails on verify/pin/mtls" → cert/fingerprint handling in `service/node.go`
(`FetchCertFingerprint`), `service/node_mtls.go`, and `runtime/tls_client.go`.
- **Restart is signal-driven.** `main.go` traps SIGHUP to restart panel+sub servers; the
in-process restart hook (`global.SetRestartHook`) funnels into the same path.
- **i18n:** backend catalogs in `internal/web/translation/` (13 locales, shared with the
frontend); frontend wiring in `frontend/src/i18n/`. Persian (`fa_IR`) is a first-class
locale (Jalali calendar via `persian-calendar-suite`).
- **Tests live next to code** (`foo.go` ↔ `foo_test.go`), plus golden snapshots in
`frontend/src/test/golden/fixtures/` for config generation — update fixtures intentionally,
not blindly, when output changes.
+168 -177
View File
@@ -11,21 +11,22 @@
"@ant-design/icons": "^6.3.2", "@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2", "@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3", "@codemirror/theme-one-dark": "^6.1.3",
"@noble/hashes": "^2.2.0",
"@tanstack/react-query": "^5.101.2", "@tanstack/react-query": "^5.101.2",
"@tanstack/react-query-devtools": "^5.101.2", "@tanstack/react-query-devtools": "^5.101.2",
"antd": "^6.5.0", "antd": "^6.5.0",
"axios": "^1.18.1", "axios": "^1.18.1",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"dayjs": "^1.11.21", "dayjs": "^1.11.21",
"i18next": "^26.3.3", "i18next": "^26.3.4",
"otpauth": "^9.5.1", "otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.5", "persian-calendar-suite": "^1.5.5",
"qs": "^6.15.3", "qs": "^6.15.3",
"react": "^19.2.7", "react": "^19.2.7",
"react-dom": "^19.2.7", "react-dom": "^19.2.7",
"react-i18next": "^17.0.8", "react-i18next": "^17.0.8",
"react-router-dom": "^7.18.0", "react-router-dom": "^7.18.1",
"recharts": "^3.9.0", "recharts": "^3.9.1",
"swagger-ui-react": "^5.32.8", "swagger-ui-react": "^5.32.8",
"zod": "^4.4.3" "zod": "^4.4.3"
}, },
@@ -44,8 +45,8 @@
"globals": "^17.7.0", "globals": "^17.7.0",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.62.0", "typescript-eslint": "^8.62.1",
"vite": "8.1.0", "vite": "8.1.3",
"vitest": "^4.1.9" "vitest": "^4.1.9"
}, },
"engines": { "engines": {
@@ -1105,9 +1106,9 @@
} }
}, },
"node_modules/@oxc-project/types": { "node_modules/@oxc-project/types": {
"version": "0.137.0", "version": "0.138.0",
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.137.0.tgz", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.138.0.tgz",
"integrity": "sha512-WT+Gb24i8hmvo85AIv2oEYouEXkRlKAlT9WaCa3TfLgNCN+GhrJOGZuIlMouAh38Qe4QOx26eUOVsq70qXrywA==", "integrity": "sha512-1a7ZKmrRTCoN1XMZ4L0PyyqrMnrNlLyPuOkdSX2MZg7IiIGRUyurNhAm73ptDOraoBcIordsIGKNPKUzy3ZmfA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"funding": { "funding": {
@@ -1843,20 +1844,10 @@
} }
} }
}, },
"node_modules/@reduxjs/toolkit/node_modules/immer": {
"version": "11.1.8",
"resolved": "https://registry.npmjs.org/immer/-/immer-11.1.8.tgz",
"integrity": "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/@rolldown/binding-android-arm64": { "node_modules/@rolldown/binding-android-arm64": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.4.tgz",
"integrity": "sha512-DT6Z3PhvioeHMvxo+xHc3KtqggrI7CCTXCmC2h/5zUlp5jVitv7XEy+9q5/7v8IolhlioawpMo8Kg0EEBy7J0g==", "integrity": "sha512-EZLpf/8y7GXkkra90ML47kzik/GMP3EMcE9bPyHmRfxLC6z9+aW5A8poCsoxjrT5GfEcNAAvWwUHjvP1pUQkfw==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1871,9 +1862,9 @@
} }
}, },
"node_modules/@rolldown/binding-darwin-arm64": { "node_modules/@rolldown/binding-darwin-arm64": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.1.4.tgz",
"integrity": "sha512-0NwgwsjM7LrsuVnXMK3koTpagBNOhloc/BNjKqZjv4V5zI5r13qx69uVhRx+o5Z0yy4Hzq+lpy7TAgUG/ocvrw==", "integrity": "sha512-aUi+HBvmYb7j8krl1+qJgkG8C17fO79gk3c+jPw4S8glRFc1DTija9S3EyaTSQUm5GJXYKDAsugBEhFHH2vYiQ==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1888,9 +1879,9 @@
} }
}, },
"node_modules/@rolldown/binding-darwin-x64": { "node_modules/@rolldown/binding-darwin-x64": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.1.4.tgz",
"integrity": "sha512-YtiBp4disu6V560loT6PjMdiRaWmVvDNrUunAalbiFx2ggeJwxdAsgZMcoGP17uyAsTwAj5V1niksxlHnVQ1Sw==", "integrity": "sha512-F7hHC3gwY11+vByKPRWqwGbeXWVgKmL+pTGCinaEhdihzBV2aQ0fvZOch9cXYUOKuKKq429HeYXOqQLc7wFCEg==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1905,9 +1896,9 @@
} }
}, },
"node_modules/@rolldown/binding-freebsd-x64": { "node_modules/@rolldown/binding-freebsd-x64": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.1.4.tgz",
"integrity": "sha512-yD3EkEdXk2LypPxnf/kSZHirarsI8gcPzc62SukhR9VJTyvV+F9Q/GxWNuCojc7sXyuVC4DxRGhdDK4X8VSsbw==", "integrity": "sha512-sI5yw+7s92SK6odiEhD5lKCBlWcpjHS5qyqpVQbZAJ0fIzEUXrmbl3DH2ybR3PZogulNJF+COLtmA8hUfvkCCQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -1922,9 +1913,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-arm-gnueabihf": { "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.1.4.tgz",
"integrity": "sha512-c+8vieQbsD7HNAHKIA34w0GJ9FedFFuJGD+7E6vz7Q3uqAIugL5p45fhlsj4UaAsHpcmlqugBWMhA0/j7o0sIg==", "integrity": "sha512-mCi0OKgEieFircrtVYmQAFGszRtMnZ6fpZAXrxanXAu7lqZcsK1E1RAaZNG0uKAnxox3B1f4EyQNnoyMfN1vAA==",
"cpu": [ "cpu": [
"arm" "arm"
], ],
@@ -1939,9 +1930,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-arm64-gnu": { "node_modules/@rolldown/binding-linux-arm64-gnu": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.1.4.tgz",
"integrity": "sha512-50jD0uUwLvur7Zz9LHz17kaAdTPjn5wN93hEgjvmYFRZwiR7ZJYovTd5ipyWJDAnXKvZ+wgc+/Ika6dwSF5OcA==", "integrity": "sha512-B9Ial3Kv5sh0SHnB1g/QWcUQCEvCF6QKGAl4zXypYj65mVI+B4AhFBwPtSN7pDrJeIx8Z7zdy4ntx+wQABom7w==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1959,9 +1950,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-arm64-musl": { "node_modules/@rolldown/binding-linux-arm64-musl": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.1.4.tgz",
"integrity": "sha512-BO9+oPL8K9poZJBfYPsXNtYjPE5uM3qeehT3aFcW4LITOl+iSqhp0abzjR2nWBUNjIZeKXjAEWBZ64WjNoHd6w==", "integrity": "sha512-lZVym0PuHE1KZ22gmFTC15lAkrg9iTszR617oYRB/iPY1A56ywoJzVKOJBKaot5RiikCObmur6pogpse3gRcng==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -1979,9 +1970,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-ppc64-gnu": { "node_modules/@rolldown/binding-linux-ppc64-gnu": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.1.4.tgz",
"integrity": "sha512-f3VpLB1vQ0Eo6ecr/6cekLnvYMFF4YBFoVGkfkvPLq1bAkbAwHYQPZKoAmG6OJyTcxxoC+AvezGx/S1obNC0Mw==", "integrity": "sha512-t2DNiLJWNTbnEHyUzTumldML6ET4/g16467LZoDDJ3tSxGvguL5/NyC2lCsNKuyRycg9XeDQF5SSv+TNOhQEXg==",
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
@@ -1999,9 +1990,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-s390x-gnu": { "node_modules/@rolldown/binding-linux-s390x-gnu": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.1.4.tgz",
"integrity": "sha512-AmurZ26Pqx/RI9N1gzEOCklkKXl927yjfXWUUS0O7Puh8ARM/Ob8qfrD3qnWksScdw6cSrW5PSHE9DyLu7+PtA==", "integrity": "sha512-0WIRnL1Uw4BvTZRLQt+PVgo6ZKTJadlC2btP+/EOXv2f/DWbY0rEgl+y834mIVwP1FkTlWVTrGGJXf12lru7EQ==",
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
@@ -2019,9 +2010,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-x64-gnu": { "node_modules/@rolldown/binding-linux-x64-gnu": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.1.4.tgz",
"integrity": "sha512-JJpqs8bRGITDOdbkNKnlojzBabbOHrqjSvDr0IVsZObE1lBcPjxItUEY9eWIDbxaJ3cGrXPWGfGkIxFijg/URg==", "integrity": "sha512-JWtGshGfX+oENAKonoNkqEJX+7hC8yfhi9GUyPX1VX4mdh1y5r+ZiJLR5XzAB0aoP6s/PcILsGjKq8O0mm24bw==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -2039,9 +2030,9 @@
} }
}, },
"node_modules/@rolldown/binding-linux-x64-musl": { "node_modules/@rolldown/binding-linux-x64-musl": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.1.4.tgz",
"integrity": "sha512-rSJcdjPxzA/by/6/rYs+v+bXU7UjvnbUWz8MJb6kh6+knqB1dCrtHg0uu7C/4haqJvqdkYHQ5IGn+tCH9GLW/g==", "integrity": "sha512-rT6yQcxUuXs4CnbofqwHRRV0iem349rLMYpTjkgQGLjrY4ado/eDzwPZPTCgTOlF6Nkp8NEv70yLMTn6qkWxsQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -2059,9 +2050,9 @@
} }
}, },
"node_modules/@rolldown/binding-openharmony-arm64": { "node_modules/@rolldown/binding-openharmony-arm64": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.1.4.tgz",
"integrity": "sha512-hQ3/PYkDJICgevvyNcVrihVeqq7k1Pp3VZ9lY+dauAYUJKO+auqApvANhvR1An9BhmqYKvW2Mu1F9u4DXSMLxQ==", "integrity": "sha512-KXMGoboq5cyaCQjDA4GLuRiOwBQ0EyFnJoVViLeZ45/3rFItRODEr+NdsBcVpll40hhNArlm/speWGRvj08LzA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -2076,9 +2067,9 @@
} }
}, },
"node_modules/@rolldown/binding-wasm32-wasi": { "node_modules/@rolldown/binding-wasm32-wasi": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.1.4.tgz",
"integrity": "sha512-Elcv/BtML9lXrV6JuKITc/grN2kYV9gjsQpW8Jfw4ioK0TOkjBjye0nnyqQNy9STNaI20lXNaQBRrD5gSgR0Yg==", "integrity": "sha512-5K83rb36oJiY7BCyE9zLZtGcPV4g5wvq+xwdO0XPIwDVZI8cyB/AUjkNXGb92/rnmezEkjMOpgY61rtwjQtFwg==",
"cpu": [ "cpu": [
"wasm32" "wasm32"
], ],
@@ -2095,9 +2086,9 @@
} }
}, },
"node_modules/@rolldown/binding-win32-arm64-msvc": { "node_modules/@rolldown/binding-win32-arm64-msvc": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.1.4.tgz",
"integrity": "sha512-2DrEfhluH9yhiaFApmsjsjwrSYbNcY1oFTzYSP1a535jDbV98zCFanA/96TBUd0iDFcxGmw9QRExwGCXz3U+/g==", "integrity": "sha512-PnWBtw3TV5KOg69HQQDR0mnQuyCmSGR2pAB4DC1rPF808fgKeTUMj2EOEyKATpgiuxuR5APQmiDO7PDgEjTFSA==",
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
@@ -2112,9 +2103,9 @@
} }
}, },
"node_modules/@rolldown/binding-win32-x64-msvc": { "node_modules/@rolldown/binding-win32-x64-msvc": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.3.tgz", "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.1.4.tgz",
"integrity": "sha512-OL4OMk7UPXOeVGGd3qo5zJyPIljf4AFgk5QAkPPS+OoLuOOozhuaQGC18MxVTnw/06q93gShAJzlwnSCY9YtqA==", "integrity": "sha512-M1lpniBePobTfsa7Ks9a199e1akxsXn+GYBUKsEzv3YFzOm1HJAMNwKI3qr0Zq+mxwx9gOZoTdP1yXRYsZUocQ==",
"cpu": [ "cpu": [
"x64" "x64"
], ],
@@ -3108,17 +3099,17 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@typescript-eslint/eslint-plugin": { "node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.62.1.tgz",
"integrity": "sha512-o+mpz7EYiMzXoySXiKmzlabIvTVqUuK5yLrAedRPRDA0IpPFMUV1IXt6OqljIxX/kumN6EjUYp41Hqelh6p/Dw==", "integrity": "sha512-4EQM77WgVNxj7OkL/5b/D/xZsw00G577+UriYTC7JF5opcF3T2AuoeY7ueLaZgSVjSgCS6yOAJB5bRGLPSJUzA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.12.2", "@eslint-community/regexpp": "^4.12.2",
"@typescript-eslint/scope-manager": "8.62.0", "@typescript-eslint/scope-manager": "8.62.1",
"@typescript-eslint/type-utils": "8.62.0", "@typescript-eslint/type-utils": "8.62.1",
"@typescript-eslint/utils": "8.62.0", "@typescript-eslint/utils": "8.62.1",
"@typescript-eslint/visitor-keys": "8.62.0", "@typescript-eslint/visitor-keys": "8.62.1",
"ignore": "^7.0.5", "ignore": "^7.0.5",
"natural-compare": "^1.4.0", "natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0" "ts-api-utils": "^2.5.0"
@@ -3131,7 +3122,7 @@
"url": "https://opencollective.com/typescript-eslint" "url": "https://opencollective.com/typescript-eslint"
}, },
"peerDependencies": { "peerDependencies": {
"@typescript-eslint/parser": "^8.62.0", "@typescript-eslint/parser": "^8.62.1",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0" "typescript": ">=4.8.4 <6.1.0"
} }
@@ -3147,16 +3138,16 @@
} }
}, },
"node_modules/@typescript-eslint/parser": { "node_modules/@typescript-eslint/parser": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.62.1.tgz",
"integrity": "sha512-dzHeT2gySzZtLDsuqxU9AkYgIsQoHAHtRBpOqM+Ofzx1Bwrd2RcCjQJ+6iQbsHOIR6NS33bF2W1k3blN1zLDrA==", "integrity": "sha512-sPhE4iHuJDSvoAiec+Ro8JyXw8f0ql13HFR82P99nCm9GwTEKG0KYLvDe6REk8BCXuit6vJAv/Yxg5ABaNS2rA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.62.0", "@typescript-eslint/scope-manager": "8.62.1",
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"@typescript-eslint/typescript-estree": "8.62.0", "@typescript-eslint/typescript-estree": "8.62.1",
"@typescript-eslint/visitor-keys": "8.62.0", "@typescript-eslint/visitor-keys": "8.62.1",
"debug": "^4.4.3" "debug": "^4.4.3"
}, },
"engines": { "engines": {
@@ -3172,14 +3163,14 @@
} }
}, },
"node_modules/@typescript-eslint/project-service": { "node_modules/@typescript-eslint/project-service": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.62.1.tgz",
"integrity": "sha512-wexnCqiTg7BOGtbLDftYpRWlmLq4xfoMd7BKFR6Y75sZS3QmRKLdN3yWLhmIYgqMmP/OXWpj3H8odkb5nGURCQ==", "integrity": "sha512-yQ3RgY5RkSBpsNS1Bx/JQEcA24FOSdfGktoyprAr5u18390UQdtVcfnEv4nIrIshNnavlVyZBKxQwT1fIAE6cg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.62.0", "@typescript-eslint/tsconfig-utils": "^8.62.1",
"@typescript-eslint/types": "^8.62.0", "@typescript-eslint/types": "^8.62.1",
"debug": "^4.4.3" "debug": "^4.4.3"
}, },
"engines": { "engines": {
@@ -3194,14 +3185,14 @@
} }
}, },
"node_modules/@typescript-eslint/scope-manager": { "node_modules/@typescript-eslint/scope-manager": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.62.1.tgz",
"integrity": "sha512-1lX38kNxXIRb8mEc3lbq5mdHq1Pf2+U0nFU65KfT18mtPxxl0fvjuEE92mHuXPuCtElJhOrddOpyMlM3Z0umEA==", "integrity": "sha512-r4d249KbQ1SFdpeStvob8Ih6aPPIzfqllPVOtvhve6ZcpuVcYo5/7zUWckKpHE7StASX4kTKZTLf0WQm/wPkcg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"@typescript-eslint/visitor-keys": "8.62.0" "@typescript-eslint/visitor-keys": "8.62.1"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -3212,9 +3203,9 @@
} }
}, },
"node_modules/@typescript-eslint/tsconfig-utils": { "node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.62.1.tgz",
"integrity": "sha512-y2GAdB6ykaXUvuspbYnizQc4oDDz0Tz/Yc7iWrXf9mx8vm/L/0vLHCe0tS2boG96Zy+DivnVDQ9ZUEWoHqqx1g==", "integrity": "sha512-xadytJqX9vJVQ2fdQjkcIVigwaOJNWkpjdLt6cEQ+xPnrI1fkp+/jZE/I97k9KUjqtpd25i0HeyZf3T6dutv2g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -3229,15 +3220,15 @@
} }
}, },
"node_modules/@typescript-eslint/type-utils": { "node_modules/@typescript-eslint/type-utils": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.62.1.tgz",
"integrity": "sha512-+g5O3j0w2ldzC86Pv6fvbO/xhAonbJFIdf/MKQ1d30gndlsVzUOE83ldfSE15Qrl9fhFjK6AovHs5Wpp6vx86w==", "integrity": "sha512-aXM5xlqXiTxPibXB93cLAURfT3rlizf7uMXISCXy66Isr/9hISJx3yDsKl0L7lKa51b8JpFuNKby0/O0pEm9jg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"@typescript-eslint/typescript-estree": "8.62.0", "@typescript-eslint/typescript-estree": "8.62.1",
"@typescript-eslint/utils": "8.62.0", "@typescript-eslint/utils": "8.62.1",
"debug": "^4.4.3", "debug": "^4.4.3",
"ts-api-utils": "^2.5.0" "ts-api-utils": "^2.5.0"
}, },
@@ -3254,9 +3245,9 @@
} }
}, },
"node_modules/@typescript-eslint/types": { "node_modules/@typescript-eslint/types": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.62.1.tgz",
"integrity": "sha512-KvAclkktORPvM54TgLgA4z9HIV1M8zOgw9ZVNXl9f/8dLYfXYX1wkMXP7qmabpijQRV5bHJLOmoyGQbLMaUYeg==", "integrity": "sha512-ooCzJFaf+Hg+uG6fA3NRFGuFjlfNlDhBthbv4ZPU/0elCAFUfnyXUvf/WOpHz/jYwSmvU2GkR2LtyUfy1AxZ1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -3268,16 +3259,16 @@
} }
}, },
"node_modules/@typescript-eslint/typescript-estree": { "node_modules/@typescript-eslint/typescript-estree": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.62.1.tgz",
"integrity": "sha512-+hVbNxtW64pIcZWDPGbyaKF7vp2IBTVY5ma1blwwksrjdsbdqqEKvJWMGbBofei4F6Dovx1M0RJgoFeNu2279A==", "integrity": "sha512-xMcW9oP9u7fAMXYs9A65CVmtLQe2r//oXINHfi8HV+oiqhih17sbLdhXr4540YWlgpDKQdY854OL5ZrdCiQsAA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/project-service": "8.62.0", "@typescript-eslint/project-service": "8.62.1",
"@typescript-eslint/tsconfig-utils": "8.62.0", "@typescript-eslint/tsconfig-utils": "8.62.1",
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"@typescript-eslint/visitor-keys": "8.62.0", "@typescript-eslint/visitor-keys": "8.62.1",
"debug": "^4.4.3", "debug": "^4.4.3",
"minimatch": "^10.2.2", "minimatch": "^10.2.2",
"semver": "^7.7.3", "semver": "^7.7.3",
@@ -3309,16 +3300,16 @@
} }
}, },
"node_modules/@typescript-eslint/utils": { "node_modules/@typescript-eslint/utils": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.62.1.tgz",
"integrity": "sha512-82r66fi9zYwZ+mTq3vKgwjbZ1PVk/DJzrXFLpG6RnBbdvH8TEGVHIs9H4d2drhkOzf0syZuD/OZvvlu6GDbP4g==", "integrity": "sha512-sHtbPfuKNZCG+ih8SyjjucqRntSVmp8XgL5u6o9mAhiSn8ds5o/M/XdM0abweme2Tln3szOstOrZ9OXitvPh0g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.9.1", "@eslint-community/eslint-utils": "^4.9.1",
"@typescript-eslint/scope-manager": "8.62.0", "@typescript-eslint/scope-manager": "8.62.1",
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"@typescript-eslint/typescript-estree": "8.62.0" "@typescript-eslint/typescript-estree": "8.62.1"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -3333,13 +3324,13 @@
} }
}, },
"node_modules/@typescript-eslint/visitor-keys": { "node_modules/@typescript-eslint/visitor-keys": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.62.0.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.62.1.tgz",
"integrity": "sha512-CY3uyFSRbcQv3nnSv8S0+lDftMVz6P963PoRlxrV7ew/Md564g9ut60PYzdLM5qW4jFn93GBF+Soi90ISAN+GQ==", "integrity": "sha512-4g3BLxfdTMy8iZG0MaBkadnlRrCJ74cQiFbyEVMrkwIoqdyaXXQM22cotDvrl4x28wgIZ9rEJRoM+mmhSJpJ1g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.62.0", "@typescript-eslint/types": "8.62.1",
"eslint-visitor-keys": "^5.0.0" "eslint-visitor-keys": "^5.0.0"
}, },
"engines": { "engines": {
@@ -3918,9 +3909,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/baseline-browser-mapping": { "node_modules/baseline-browser-mapping": {
"version": "2.10.40", "version": "2.10.41",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.40.tgz", "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.41.tgz",
"integrity": "sha512-BSSLZ9/Cjjv7Gtj5B68ZzXcXUg8iOf3fme+FCuh8rC/Go+Kmh8cox7M3A8dolou16s64QjLPOSdngh7GxXvkSw==", "integrity": "sha512-WwS7MHhqGHHlaVsqRZnhvCEMS0owDX+SxRlve7JkuH7My1Ara3ZriTmCQupPfYjxMZ8I/tgxtJYr2t7taHaH4A==",
"dev": true, "dev": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"bin": { "bin": {
@@ -4058,9 +4049,9 @@
} }
}, },
"node_modules/caniuse-lite": { "node_modules/caniuse-lite": {
"version": "1.0.30001799", "version": "1.0.30001800",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001799.tgz", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001800.tgz",
"integrity": "sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==", "integrity": "sha512-MMHtuAz9Ys840zAY5F4k6fV5GaivZ9sPk+nz0mY+GYVzRBnYkN0mpqkSR92oWRQ19yQWo4HvBV/FnC16AJX8MA==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -4644,9 +4635,9 @@
} }
}, },
"node_modules/electron-to-chromium": { "node_modules/electron-to-chromium": {
"version": "1.5.381", "version": "1.5.384",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.381.tgz", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.384.tgz",
"integrity": "sha512-n9Wa6yB+vDsGuA8AKbl/0z7HbvWqt5jxIdvr1IUicd0ryPrk7/xzwqLv8D9AbbvZ6avVNtXYLTfmgFHkwkyelg==", "integrity": "sha512-g6KAKY1vkYsADvSPWvdJsuYT0ixdcu6lUtD9P/wJKGBEDlZVXh2AX42j1mPqqaQPDluWjara9ziQ7xqAeXCt5A==",
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
@@ -4777,9 +4768,9 @@
} }
}, },
"node_modules/es-module-lexer": { "node_modules/es-module-lexer": {
"version": "2.2.0", "version": "2.3.0",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.2.0.tgz", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",
"integrity": "sha512-3lGxdTXCLfe1MYfTz1y2ksAAUM4NAOP6rPEjxGJVKO7TZ5+tvHCaQWGpC4Y3IXvW3ece0Cz1cIP4FWBxOnGCTQ==", "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
@@ -5700,9 +5691,9 @@
} }
}, },
"node_modules/i18next": { "node_modules/i18next": {
"version": "26.3.3", "version": "26.3.4",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.3.tgz", "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.4.tgz",
"integrity": "sha512-aYVegyBdXSO93CMMihvr47jI7GHSOcIahMpJX+qzUXDzW4xDJf2uenIA+45vDU+YhiVdcfsql70AC9RVdMNrHg==", "integrity": "sha512-pa7m0d7pBDqGHZxljT+WPFeyFgQ7P7SciPPo1tTqYuO0z4sqADYhwnBESmmGp/wEof1inwdls/k8ZgTg8rxFHA==",
"funding": [ "funding": [
{ {
"type": "individual", "type": "individual",
@@ -5758,9 +5749,9 @@
} }
}, },
"node_modules/immer": { "node_modules/immer": {
"version": "10.2.0", "version": "11.1.9",
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz", "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.9.tgz",
"integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==", "integrity": "sha512-sc/z0Cyti70bZa0ZU4sWfAElfovFb9Ni8tArJZLuklYWxegPiK3pDOql1Rq5H0FIRAW9LSQRG6OX4KqBldbhBA==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"type": "opencollective", "type": "opencollective",
@@ -7690,9 +7681,9 @@
} }
}, },
"node_modules/react-router": { "node_modules/react-router": {
"version": "7.18.0", "version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.0.tgz", "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
"integrity": "sha512-pTTGt8J+ji1NOmYnjzT+bAJy/1zD+Jp4ziO6cL7T3ZLvXKtusO7BpFqlRXitqpcPVqllsIXFHRMt+2/k3Xn6HQ==", "integrity": "sha512-GDLgg3i3uM0aeJO3Fm+TCS+sDQ7gu12T6x0qdTEzcwqEfleci7JwugVNIF3U//0FWKnJT7ptG+20B2jfDqnZAg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"cookie": "^1.0.1", "cookie": "^1.0.1",
@@ -7712,12 +7703,12 @@
} }
}, },
"node_modules/react-router-dom": { "node_modules/react-router-dom": {
"version": "7.18.0", "version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.0.tgz", "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.1.tgz",
"integrity": "sha512-Fi0yY6kgtKae/Th2xibdWK0KSdYZ4B53Gyf6wRtomOKWgpNm7H7+DyfDhncdz9FKbpS+1jmDhg3F4WoGJ+yFOA==", "integrity": "sha512-KaZh+X/6UtEp28x51AUYZDMg9NGoz2ja3dNHa+ta/tk40vCzKhQ/RypCWBMLbmDr6//E24Vv5uPsrqXFozdkAg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"react-router": "7.18.0" "react-router": "7.18.1"
}, },
"engines": { "engines": {
"node": ">=20.0.0" "node": ">=20.0.0"
@@ -7748,9 +7739,9 @@
} }
}, },
"node_modules/recharts": { "node_modules/recharts": {
"version": "3.9.0", "version": "3.9.1",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-3.9.0.tgz", "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.9.1.tgz",
"integrity": "sha512-dCEcE9y20c8H2tkVeByrAXhhnBJk6/QLbxKmn+dJUptOfc5NMjwRh1jo0vZPRLD+5dMrHrP+hPEsfbGBMfnf5Q==", "integrity": "sha512-WMcwlXcB7l+BbxiEdyClkG+1sxrMHNZpzT577LEvU4+rXPd8oTAy1wXk72hnk2KOOmxuLvw3z5DtXT7HEAydtg==",
"license": "MIT", "license": "MIT",
"workspaces": [ "workspaces": [
"www" "www"
@@ -7761,7 +7752,7 @@
"decimal.js-light": "^2.5.1", "decimal.js-light": "^2.5.1",
"es-toolkit": "^1.39.3", "es-toolkit": "^1.39.3",
"eventemitter3": "^5.0.1", "eventemitter3": "^5.0.1",
"immer": "^10.1.1", "immer": "^11.1.8",
"react-redux": "8.x.x || 9.x.x", "react-redux": "8.x.x || 9.x.x",
"reselect": "5.2.0", "reselect": "5.2.0",
"tiny-invariant": "^1.3.3", "tiny-invariant": "^1.3.3",
@@ -7927,13 +7918,13 @@
} }
}, },
"node_modules/rolldown": { "node_modules/rolldown": {
"version": "1.1.3", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.3.tgz", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.4.tgz",
"integrity": "sha512-1F1eEtUBtFvcGm1HQ9TiUIUHPQG7mSAODrhIzjxoUEFuo8OcbrGLiVLkevNgj84TE4lnHvnumwFjhJO5Eu135g==", "integrity": "sha512-IjZYiLxZwpnhwhdBH2ugdTGVSdhCQUmLxLoqyjiL0JxYjyRst+5a0P3xfrTxJ5F638j4Mvvw5FAX5XE6eHpXbA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@oxc-project/types": "=0.137.0", "@oxc-project/types": "=0.138.0",
"@rolldown/pluginutils": "^1.0.0" "@rolldown/pluginutils": "^1.0.0"
}, },
"bin": { "bin": {
@@ -7943,21 +7934,21 @@
"node": "^20.19.0 || >=22.12.0" "node": "^20.19.0 || >=22.12.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"@rolldown/binding-android-arm64": "1.1.3", "@rolldown/binding-android-arm64": "1.1.4",
"@rolldown/binding-darwin-arm64": "1.1.3", "@rolldown/binding-darwin-arm64": "1.1.4",
"@rolldown/binding-darwin-x64": "1.1.3", "@rolldown/binding-darwin-x64": "1.1.4",
"@rolldown/binding-freebsd-x64": "1.1.3", "@rolldown/binding-freebsd-x64": "1.1.4",
"@rolldown/binding-linux-arm-gnueabihf": "1.1.3", "@rolldown/binding-linux-arm-gnueabihf": "1.1.4",
"@rolldown/binding-linux-arm64-gnu": "1.1.3", "@rolldown/binding-linux-arm64-gnu": "1.1.4",
"@rolldown/binding-linux-arm64-musl": "1.1.3", "@rolldown/binding-linux-arm64-musl": "1.1.4",
"@rolldown/binding-linux-ppc64-gnu": "1.1.3", "@rolldown/binding-linux-ppc64-gnu": "1.1.4",
"@rolldown/binding-linux-s390x-gnu": "1.1.3", "@rolldown/binding-linux-s390x-gnu": "1.1.4",
"@rolldown/binding-linux-x64-gnu": "1.1.3", "@rolldown/binding-linux-x64-gnu": "1.1.4",
"@rolldown/binding-linux-x64-musl": "1.1.3", "@rolldown/binding-linux-x64-musl": "1.1.4",
"@rolldown/binding-openharmony-arm64": "1.1.3", "@rolldown/binding-openharmony-arm64": "1.1.4",
"@rolldown/binding-wasm32-wasi": "1.1.3", "@rolldown/binding-wasm32-wasi": "1.1.4",
"@rolldown/binding-win32-arm64-msvc": "1.1.3", "@rolldown/binding-win32-arm64-msvc": "1.1.4",
"@rolldown/binding-win32-x64-msvc": "1.1.3" "@rolldown/binding-win32-x64-msvc": "1.1.4"
} }
}, },
"node_modules/safe-array-concat": { "node_modules/safe-array-concat": {
@@ -8830,16 +8821,16 @@
} }
}, },
"node_modules/typescript-eslint": { "node_modules/typescript-eslint": {
"version": "8.62.0", "version": "8.62.1",
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.62.0.tgz", "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.62.1.tgz",
"integrity": "sha512-8QxXi+ZACKX0kaqO4gY8kn0RSD9gFfaHDWwjqtEN48aWCBkX4MJaufWN+c3BzlrXLOxfywDL8CaoqUwcRq4j4Q==", "integrity": "sha512-vymnnM5g0AKQDSAyfP12nMIBvgwgA42syg74kkuZ4x1VuTzwQKwc5h9rGxeShCjny5o+zWAb6OEoz7XLgrIkIw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@typescript-eslint/eslint-plugin": "8.62.0", "@typescript-eslint/eslint-plugin": "8.62.1",
"@typescript-eslint/parser": "8.62.0", "@typescript-eslint/parser": "8.62.1",
"@typescript-eslint/typescript-estree": "8.62.0", "@typescript-eslint/typescript-estree": "8.62.1",
"@typescript-eslint/utils": "8.62.0" "@typescript-eslint/utils": "8.62.1"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -8971,16 +8962,16 @@
} }
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "8.1.0", "version": "8.1.3",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.1.0.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-8.1.3.tgz",
"integrity": "sha512-BuJcQK/56NQTWDGn4ABea3q4SSBdNPWwNZKTkkUpcMPnLoquSYH8llRtSUIgoL1KSCpHt5eghLShn50mH36y7Q==", "integrity": "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"lightningcss": "^1.32.0", "lightningcss": "^1.32.0",
"picomatch": "^4.0.4", "picomatch": "^4.0.4",
"postcss": "^8.5.15", "postcss": "^8.5.16",
"rolldown": "~1.1.2", "rolldown": "~1.1.3",
"tinyglobby": "^0.2.17" "tinyglobby": "^0.2.17"
}, },
"bin": { "bin": {
+6 -5
View File
@@ -24,21 +24,22 @@
"@ant-design/icons": "^6.3.2", "@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2", "@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3", "@codemirror/theme-one-dark": "^6.1.3",
"@noble/hashes": "^2.2.0",
"@tanstack/react-query": "^5.101.2", "@tanstack/react-query": "^5.101.2",
"@tanstack/react-query-devtools": "^5.101.2", "@tanstack/react-query-devtools": "^5.101.2",
"antd": "^6.5.0", "antd": "^6.5.0",
"axios": "^1.18.1", "axios": "^1.18.1",
"codemirror": "^6.0.2", "codemirror": "^6.0.2",
"dayjs": "^1.11.21", "dayjs": "^1.11.21",
"i18next": "^26.3.3", "i18next": "^26.3.4",
"otpauth": "^9.5.1", "otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.5", "persian-calendar-suite": "^1.5.5",
"qs": "^6.15.3", "qs": "^6.15.3",
"react": "^19.2.7", "react": "^19.2.7",
"react-dom": "^19.2.7", "react-dom": "^19.2.7",
"react-i18next": "^17.0.8", "react-i18next": "^17.0.8",
"react-router-dom": "^7.18.0", "react-router-dom": "^7.18.1",
"recharts": "^3.9.0", "recharts": "^3.9.1",
"swagger-ui-react": "^5.32.8", "swagger-ui-react": "^5.32.8",
"zod": "^4.4.3" "zod": "^4.4.3"
}, },
@@ -57,8 +58,8 @@
"globals": "^17.7.0", "globals": "^17.7.0",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.62.0", "typescript-eslint": "^8.62.1",
"vite": "8.1.0", "vite": "8.1.3",
"vitest": "^4.1.9" "vitest": "^4.1.9"
}, },
"overrides": { "overrides": {
+98
View File
@@ -1824,10 +1824,21 @@
}, },
"InboundOption": { "InboundOption": {
"properties": { "properties": {
"enable": {
"example": true,
"type": "boolean"
},
"id": { "id": {
"example": 1, "example": 1,
"type": "integer" "type": "integer"
}, },
"listen": {
"type": "string"
},
"nodeAddress": {
"description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
"type": "string"
},
"nodeId": { "nodeId": {
"description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).", "description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).",
"nullable": true, "nullable": true,
@@ -1845,6 +1856,12 @@
"example": "VLESS-443", "example": "VLESS-443",
"type": "string" "type": "string"
}, },
"shareAddr": {
"type": "string"
},
"shareAddrStrategy": {
"type": "string"
},
"ssMethod": { "ssMethod": {
"type": "string" "type": "string"
}, },
@@ -1867,6 +1884,7 @@
} }
}, },
"required": [ "required": [
"enable",
"id", "id",
"port", "port",
"protocol", "protocol",
@@ -2147,6 +2165,34 @@
], ],
"type": "object" "type": "object"
}, },
"PanelUpdateStatus": {
"description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.",
"properties": {
"exitCode": {
"example": 0,
"type": "integer"
},
"finishedAt": {
"example": 1735689612,
"type": "integer"
},
"runId": {
"example": "1735689600123456789",
"type": "string"
},
"state": {
"example": "success",
"type": "string"
}
},
"required": [
"exitCode",
"finishedAt",
"runId",
"state"
],
"type": "object"
},
"ProbeResultUI": { "ProbeResultUI": {
"properties": { "properties": {
"cpuPct": { "cpuPct": {
@@ -2754,11 +2800,16 @@
"success": true, "success": true,
"obj": [ "obj": [
{ {
"enable": true,
"id": 1, "id": 1,
"listen": "",
"nodeAddress": "",
"nodeId": null, "nodeId": null,
"port": 443, "port": 443,
"protocol": "vless", "protocol": "vless",
"remark": "VLESS-443", "remark": "VLESS-443",
"shareAddr": "",
"shareAddrStrategy": "",
"ssMethod": "", "ssMethod": "",
"tag": "in-443-tcp", "tag": "in-443-tcp",
"tlsFlowCapable": true, "tlsFlowCapable": true,
@@ -3901,6 +3952,47 @@
} }
} }
}, },
"/panel/api/server/getUpdateStatus": {
"get": {
"tags": [
"Server"
],
"summary": "Report the outcome of the most recently launched panel self-update (see POST updatePanel). Compare the returned runId against the one updatePanel returned to tell this run apart from a stale result.",
"operationId": "get_panel_api_server_getUpdateStatus",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/PanelUpdateStatus"
}
}
},
"example": {
"success": true,
"obj": {
"exitCode": 0,
"finishedAt": 1735689612,
"runId": "1735689600123456789",
"state": "success"
}
}
}
}
}
}
}
},
"/panel/api/server/getConfigJson": { "/panel/api/server/getConfigJson": {
"get": { "get": {
"tags": [ "tags": [
@@ -4427,6 +4519,12 @@
}, },
"obj": {} "obj": {}
} }
},
"example": {
"success": true,
"obj": {
"runId": "1735689600123456789"
}
} }
} }
} }
+4 -1
View File
@@ -24,7 +24,10 @@ export interface RemoteInboundOption {
export function useNodeMutations() { export function useNodeMutations() {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.nodes.root() }); const invalidate = () => {
queryClient.invalidateQueries({ queryKey: keys.nodes.root() });
queryClient.invalidateQueries({ queryKey: keys.inbounds.options() });
};
const createMut = useMutation({ const createMut = useMutation({
mutationFn: (payload: Partial<NodeRecord>) => mutationFn: (payload: Partial<NodeRecord>) =>
@@ -0,0 +1,26 @@
import { Tag } from 'antd';
import { SizeFormatter } from '@/utils';
import type { ClientSpeedEntry } from '@/hooks/useClients';
export type { ClientSpeedEntry };
export function isActiveSpeed(speed?: ClientSpeedEntry): speed is ClientSpeedEntry {
return !!speed && (speed.up > 0 || speed.down > 0);
}
interface ClientSpeedTagProps {
speed: ClientSpeedEntry;
}
export function ClientSpeedTag({ speed }: ClientSpeedTagProps) {
return (
<Tag color="blue">
↑ {SizeFormatter.speedFormat(speed.up)}
{' / '}
↓ {SizeFormatter.speedFormat(speed.down)}
</Tag>
);
}
export default ClientSpeedTag;
+1
View File
@@ -18,6 +18,7 @@ interface SubPageData {
links?: string[]; links?: string[];
emails?: string[]; emails?: string[];
datepicker?: 'gregorian' | 'jalalian'; datepicker?: 'gregorian' | 'jalalian';
announce?: string;
downloadByte?: string | number; downloadByte?: string | number;
uploadByte?: string | number; uploadByte?: string | number;
usedByte?: string | number; usedByte?: string | number;
+11
View File
@@ -399,11 +399,16 @@ export const EXAMPLES: Record<string, unknown> = {
"xver": 0 "xver": 0
}, },
"InboundOption": { "InboundOption": {
"enable": true,
"id": 1, "id": 1,
"listen": "",
"nodeAddress": "",
"nodeId": null, "nodeId": null,
"port": 443, "port": 443,
"protocol": "vless", "protocol": "vless",
"remark": "VLESS-443", "remark": "VLESS-443",
"shareAddr": "",
"shareAddrStrategy": "",
"ssMethod": "", "ssMethod": "",
"tag": "in-443-tcp", "tag": "in-443-tcp",
"tlsFlowCapable": true, "tlsFlowCapable": true,
@@ -468,6 +473,12 @@ export const EXAMPLES: Record<string, unknown> = {
"total": 0, "total": 0,
"up": 0 "up": 0
}, },
"PanelUpdateStatus": {
"exitCode": 0,
"finishedAt": 1735689612,
"runId": "1735689600123456789",
"state": "success"
},
"ProbeResultUI": { "ProbeResultUI": {
"cpuPct": 12.5, "cpuPct": 12.5,
"error": "", "error": "",
+46
View File
@@ -1798,10 +1798,21 @@ export const SCHEMAS: Record<string, unknown> = {
}, },
"InboundOption": { "InboundOption": {
"properties": { "properties": {
"enable": {
"example": true,
"type": "boolean"
},
"id": { "id": {
"example": 1, "example": 1,
"type": "integer" "type": "integer"
}, },
"listen": {
"type": "string"
},
"nodeAddress": {
"description": "Share-host resolution inputs, mirroring the subscription's\nresolveInboundAddress so the clients page renders a node-managed WireGuard\nEndpoint that points at the node, not the master panel. NodeAddress is the\nhosting node's externally reachable address (empty for this panel's own\ninbounds); Listen and ShareAddrStrategy/ShareAddr feed the same\nnode→listen→custom fallback the share/QR links already use.",
"type": "string"
},
"nodeId": { "nodeId": {
"description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).", "description": "Hosting node; nil for this panel's own inbounds. Lets the clients\npage map a node filter onto inbound IDs (#4997).",
"nullable": true, "nullable": true,
@@ -1819,6 +1830,12 @@ export const SCHEMAS: Record<string, unknown> = {
"example": "VLESS-443", "example": "VLESS-443",
"type": "string" "type": "string"
}, },
"shareAddr": {
"type": "string"
},
"shareAddrStrategy": {
"type": "string"
},
"ssMethod": { "ssMethod": {
"type": "string" "type": "string"
}, },
@@ -1841,6 +1858,7 @@ export const SCHEMAS: Record<string, unknown> = {
} }
}, },
"required": [ "required": [
"enable",
"id", "id",
"port", "port",
"protocol", "protocol",
@@ -2121,6 +2139,34 @@ export const SCHEMAS: Record<string, unknown> = {
], ],
"type": "object" "type": "object"
}, },
"PanelUpdateStatus": {
"description": "PanelUpdateStatus reports the outcome of the most recently launched panel\nself-update. RunID lets the caller confirm this status belongs to the\nupdate it started rather than a stale result left over from an earlier\nrun; State is one of \"pending\", \"success\", or \"failed\". RunID is a decimal\nstring, not a JSON number: it's a formatted UnixNano timestamp, and\nJavaScript's number type can't represent that precisely (it exceeds\nNumber.MAX_SAFE_INTEGER), which would let two different runs round to the\nsame value on the wire and defeat the whole point of this field.",
"properties": {
"exitCode": {
"example": 0,
"type": "integer"
},
"finishedAt": {
"example": 1735689612,
"type": "integer"
},
"runId": {
"example": "1735689600123456789",
"type": "string"
},
"state": {
"example": "success",
"type": "string"
}
},
"required": [
"exitCode",
"finishedAt",
"runId",
"state"
],
"type": "object"
},
"ProbeResultUI": { "ProbeResultUI": {
"properties": { "properties": {
"cpuPct": { "cpuPct": {
+12
View File
@@ -393,11 +393,16 @@ export interface InboundFallback {
} }
export interface InboundOption { export interface InboundOption {
enable: boolean;
id: number; id: number;
listen?: string;
nodeAddress?: string;
nodeId?: number | null; nodeId?: number | null;
port: number; port: number;
protocol: string; protocol: string;
remark: string; remark: string;
shareAddr?: string;
shareAddrStrategy?: string;
ssMethod: string; ssMethod: string;
tag: string; tag: string;
tlsFlowCapable: boolean; tlsFlowCapable: boolean;
@@ -464,6 +469,13 @@ export interface OutboundTraffics {
up: number; up: number;
} }
export interface PanelUpdateStatus {
exitCode: number;
finishedAt: number;
runId: string;
state: string;
}
export interface ProbeResultUI { export interface ProbeResultUI {
cpuPct: number; cpuPct: number;
error: string; error: string;
+13
View File
@@ -420,11 +420,16 @@ export const InboundFallbackSchema = z.object({
export type InboundFallback = z.infer<typeof InboundFallbackSchema>; export type InboundFallback = z.infer<typeof InboundFallbackSchema>;
export const InboundOptionSchema = z.object({ export const InboundOptionSchema = z.object({
enable: z.boolean(),
id: z.number().int(), id: z.number().int(),
listen: z.string().optional(),
nodeAddress: z.string().optional(),
nodeId: z.number().int().nullable().optional(), nodeId: z.number().int().nullable().optional(),
port: z.number().int(), port: z.number().int(),
protocol: z.string(), protocol: z.string(),
remark: z.string(), remark: z.string(),
shareAddr: z.string().optional(),
shareAddrStrategy: z.string().optional(),
ssMethod: z.string(), ssMethod: z.string(),
tag: z.string(), tag: z.string(),
tlsFlowCapable: z.boolean(), tlsFlowCapable: z.boolean(),
@@ -495,6 +500,14 @@ export const OutboundTrafficsSchema = z.object({
}); });
export type OutboundTraffics = z.infer<typeof OutboundTrafficsSchema>; export type OutboundTraffics = z.infer<typeof OutboundTrafficsSchema>;
export const PanelUpdateStatusSchema = z.object({
exitCode: z.number().int(),
finishedAt: z.number().int(),
runId: z.string(),
state: z.string(),
});
export type PanelUpdateStatus = z.infer<typeof PanelUpdateStatusSchema>;
export const ProbeResultUISchema = z.object({ export const ProbeResultUISchema = z.object({
cpuPct: z.number(), cpuPct: z.number(),
error: z.string(), error: z.string(),
+25 -3
View File
@@ -32,6 +32,7 @@ import {
type BulkDetachResult, type BulkDetachResult,
} from '@/schemas/client'; } from '@/schemas/client';
import { DefaultsPayloadSchema } from '@/schemas/defaults'; import { DefaultsPayloadSchema } from '@/schemas/defaults';
import { TRAFFIC_POLL_INTERVAL_S } from '@/lib/traffic/poll-interval';
// One row sent to POST /clients/:email/externalLinks. // One row sent to POST /clients/:email/externalLinks.
export type ExternalLinkInput = { kind: 'link' | 'subscription'; value: string; remark: string }; export type ExternalLinkInput = { kind: 'link' | 'subscription'; value: string; remark: string };
@@ -75,6 +76,11 @@ const DEFAULT_SUMMARY: ClientsSummary = {
total: 0, active: 0, online: [], depleted: [], expiring: [], deactive: [], total: 0, active: 0, online: [], depleted: [], expiring: [], deactive: [],
}; };
export interface ClientSpeedEntry {
up: number;
down: number;
}
type ClientStatRow = ClientTraffic & { email?: string }; type ClientStatRow = ClientTraffic & { email?: string };
// Mirror of the server's buildClientsSummary (web/service/client.go). The // Mirror of the server's buildClientsSummary (web/service/client.go). The
@@ -264,6 +270,7 @@ export function useClients() {
// back to the server-computed summary until the first event lands, and keeps // back to the server-computed summary until the first event lands, and keeps
// the server's authoritative total for the headline count. // the server's authoritative total for the headline count.
const [allClientStats, setAllClientStats] = useState<ClientStatRow[]>([]); const [allClientStats, setAllClientStats] = useState<ClientStatRow[]>([]);
const [clientSpeed, setClientSpeed] = useState<Record<string, ClientSpeedEntry>>({});
const summary = useMemo<ClientsSummary>(() => { const summary = useMemo<ClientsSummary>(() => {
const serverSummary = listQuery.data?.summary ?? DEFAULT_SUMMARY; const serverSummary = listQuery.data?.summary ?? DEFAULT_SUMMARY;
if (allClientStats.length === 0) return serverSummary; if (allClientStats.length === 0) return serverSummary;
@@ -543,17 +550,31 @@ export function useClients() {
const applyTrafficEvent = useCallback((payload: unknown) => { const applyTrafficEvent = useCallback((payload: unknown) => {
if (!payload || typeof payload !== 'object') return; if (!payload || typeof payload !== 'object') return;
const p = payload as { onlineClients?: string[] }; const p = payload as {
onlineClients?: string[];
clientTraffics?: { email: string; up: number; down: number }[];
};
if (Array.isArray(p.onlineClients)) { if (Array.isArray(p.onlineClients)) {
queryClient.setQueryData(keys.clients.onlines(), p.onlineClients); queryClient.setQueryData(keys.clients.onlines(), p.onlineClients);
} }
if (Array.isArray(p.clientTraffics)) {
const next: Record<string, ClientSpeedEntry> = {};
for (const ct of p.clientTraffics) {
if (!ct || !ct.email) continue;
next[ct.email] = {
up: (ct.up || 0) / TRAFFIC_POLL_INTERVAL_S,
down: (ct.down || 0) / TRAFFIC_POLL_INTERVAL_S,
};
}
setClientSpeed(next);
}
}, [queryClient]); }, [queryClient]);
const applyClientStatsEvent = useCallback((payload: unknown) => { const applyClientStatsEvent = useCallback((payload: unknown) => {
if (!payload || typeof payload !== 'object') return; if (!payload || typeof payload !== 'object') return;
const p = payload as { clients?: ClientStatRow[] }; const p = payload as { clients?: ClientStatRow[]; snapshot?: boolean };
if (!Array.isArray(p.clients) || p.clients.length === 0) return; if (!Array.isArray(p.clients) || p.clients.length === 0) return;
setAllClientStats(p.clients); if (p.snapshot !== false) setAllClientStats(p.clients);
const byEmail = new Map<string, ClientTraffic>(); const byEmail = new Map<string, ClientTraffic>();
for (const row of p.clients) { for (const row of p.clients) {
if (row && row.email) byEmail.set(row.email, row); if (row && row.email) byEmail.set(row.email, row);
@@ -629,6 +650,7 @@ export function useClients() {
exportClients, exportClients,
importClients, importClients,
setEnable, setEnable,
clientSpeed,
applyTrafficEvent, applyTrafficEvent,
applyClientStatsEvent, applyClientStatsEvent,
}; };
+13 -9
View File
@@ -17,8 +17,9 @@ import {
const DIRTY_POLL_MS = 1000; const DIRTY_POLL_MS = 1000;
const DEFAULT_TEST_URL = 'https://www.google.com/generate_204'; const DEFAULT_TEST_URL = 'https://www.google.com/generate_204';
// One HTTP-mode batch request tests this many outbounds through a single // One HTTP-mode batch request tests this many outbounds through a single
// shared temp xray instance; chunking keeps responses bounded (~15s worst // shared temp xray instance; chunking keeps responses bounded (~30s worst
// case) and lands Test All results progressively. // case — each probe is a cold plus a warm request) and lands Test All
// results progressively.
const HTTP_BATCH_CHUNK = 16; const HTTP_BATCH_CHUNK = 16;
export function isUdpOutbound(outbound: unknown): boolean { export function isUdpOutbound(outbound: unknown): boolean {
@@ -28,6 +29,8 @@ export function isUdpOutbound(outbound: unknown): boolean {
return p === 'wireguard' || p === 'hysteria' || n === 'hysteria' || n === 'kcp' || n === 'quic'; return p === 'wireguard' || p === 'hysteria' || n === 'hysteria' || n === 'kcp' || n === 'quic';
} }
export type OutboundTestMode = 'tcp' | 'http' | 'real';
export type { OutboundTrafficRow, OutboundTestResult }; export type { OutboundTrafficRow, OutboundTestResult };
export type XraySettingsValue = z.infer<typeof XraySettingsValueSchema>; export type XraySettingsValue = z.infer<typeof XraySettingsValueSchema>;
@@ -288,7 +291,7 @@ export function useXraySetting(): UseXraySettingResult {
const testOutbound = useCallback( const testOutbound = useCallback(
async (index: number, outbound: unknown, mode = 'tcp'): Promise<OutboundTestResult | null> => { async (index: number, outbound: unknown, mode = 'tcp'): Promise<OutboundTestResult | null> => {
if (!outbound) return null; if (!outbound) return null;
const effMode = isUdpOutbound(outbound) ? 'http' : mode; const effMode = mode === 'tcp' && isUdpOutbound(outbound) ? 'http' : mode;
setOutboundTestStates((prev) => ({ setOutboundTestStates((prev) => ({
...prev, ...prev,
[index]: { testing: true, result: null, mode: effMode }, [index]: { testing: true, result: null, mode: effMode },
@@ -305,7 +308,7 @@ export function useXraySetting(): UseXraySettingResult {
const testSubscriptionOutbound = useCallback( const testSubscriptionOutbound = useCallback(
async (tag: string, outbound: unknown, mode = 'tcp'): Promise<OutboundTestResult | null> => { async (tag: string, outbound: unknown, mode = 'tcp'): Promise<OutboundTestResult | null> => {
if (!outbound || !tag) return null; if (!outbound || !tag) return null;
const effMode = isUdpOutbound(outbound) ? 'http' : mode; const effMode = mode === 'tcp' && isUdpOutbound(outbound) ? 'http' : mode;
setSubscriptionTestStates((prev) => ({ setSubscriptionTestStates((prev) => ({
...prev, ...prev,
[tag]: { testing: true, result: null, mode: effMode }, [tag]: { testing: true, result: null, mode: effMode },
@@ -333,6 +336,7 @@ export function useXraySetting(): UseXraySettingResult {
// HTTP batches stay homogeneous (all template or all subscription) so a // HTTP batches stay homogeneous (all template or all subscription) so a
// tag shared between a template and a subscription outbound can't collide // tag shared between a template and a subscription outbound can't collide
// inside one batch, and each batch's results route to one state map. // inside one batch, and each batch's results route to one state map.
const probeMode = mode === 'real' ? 'real' : 'http';
const httpTplQueue: { index: number; outbound: unknown }[] = []; const httpTplQueue: { index: number; outbound: unknown }[] = [];
const httpSubQueue: { tag: string; outbound: unknown }[] = []; const httpSubQueue: { tag: string; outbound: unknown }[] = [];
const enqueue = (ob: { tag?: string; protocol?: string }, kind: 'tpl' | 'sub', index: number, tag: string) => { const enqueue = (ob: { tag?: string; protocol?: string }, kind: 'tpl' | 'sub', index: number, tag: string) => {
@@ -341,7 +345,7 @@ export function useXraySetting(): UseXraySettingResult {
// freedom ("direct") and dns aren't proxies — skip them in every mode. // freedom ("direct") and dns aren't proxies — skip them in every mode.
if (proto === 'freedom' || proto === 'dns') return; if (proto === 'freedom' || proto === 'dns') return;
if (kind === 'sub' && !tag) return; if (kind === 'sub' && !tag) return;
const toHttp = mode === 'http' || isUdpOutbound(ob); const toHttp = mode !== 'tcp' || isUdpOutbound(ob);
if (kind === 'tpl') { if (kind === 'tpl') {
if (toHttp) httpTplQueue.push({ index, outbound: ob }); if (toHttp) httpTplQueue.push({ index, outbound: ob });
else tcpQueue.push({ kind: 'tpl', index, outbound: ob }); else tcpQueue.push({ kind: 'tpl', index, outbound: ob });
@@ -375,10 +379,10 @@ export function useXraySetting(): UseXraySettingResult {
const chunk = httpTplQueue.slice(at, at + HTTP_BATCH_CHUNK); const chunk = httpTplQueue.slice(at, at + HTTP_BATCH_CHUNK);
setOutboundTestStates((prev) => { setOutboundTestStates((prev) => {
const next = { ...prev }; const next = { ...prev };
for (const item of chunk) next[item.index] = { testing: true, result: null, mode: 'http' }; for (const item of chunk) next[item.index] = { testing: true, result: null, mode: probeMode };
return next; return next;
}); });
const results = await postOutboundTestBatch(chunk.map((c) => c.outbound), 'http'); const results = await postOutboundTestBatch(chunk.map((c) => c.outbound), probeMode);
setOutboundTestStates((prev) => { setOutboundTestStates((prev) => {
const next = { ...prev }; const next = { ...prev };
chunk.forEach((item, i) => { chunk.forEach((item, i) => {
@@ -393,10 +397,10 @@ export function useXraySetting(): UseXraySettingResult {
const chunk = httpSubQueue.slice(at, at + HTTP_BATCH_CHUNK); const chunk = httpSubQueue.slice(at, at + HTTP_BATCH_CHUNK);
setSubscriptionTestStates((prev) => { setSubscriptionTestStates((prev) => {
const next = { ...prev }; const next = { ...prev };
for (const item of chunk) next[item.tag] = { testing: true, result: null, mode: 'http' }; for (const item of chunk) next[item.tag] = { testing: true, result: null, mode: probeMode };
return next; return next;
}); });
const results = await postOutboundTestBatch(chunk.map((c) => c.outbound), 'http'); const results = await postOutboundTestBatch(chunk.map((c) => c.outbound), probeMode);
setSubscriptionTestStates((prev) => { setSubscriptionTestStates((prev) => {
const next = { ...prev }; const next = { ...prev };
chunk.forEach((item, i) => { chunk.forEach((item, i) => {
@@ -0,0 +1 @@
export const TRAFFIC_POLL_INTERVAL_S = 5;
@@ -13,7 +13,7 @@ import type { Sniffing } from '@/schemas/primitives';
import type { z } from 'zod'; import type { z } from 'zod';
import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize'; import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize';
import { canEnableSniffing } from '@/lib/xray/protocol-capabilities'; import { canEnableSniffing } from '@/lib/xray/protocol-capabilities';
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp'; import { XHttpStreamSettingsSchema, XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
const XMUX_DEFAULTS = XHttpXmuxSchema.parse({}); const XMUX_DEFAULTS = XHttpXmuxSchema.parse({});
@@ -164,7 +164,9 @@ export function rawInboundToFormValues(row: RawInboundRow): InboundFormValues {
const streamRecord = streamSettings as unknown as Record<string, unknown>; const streamRecord = streamSettings as unknown as Record<string, unknown>;
const xh = streamRecord.xhttpSettings; const xh = streamRecord.xhttpSettings;
if (xh && typeof xh === 'object' && !Array.isArray(xh)) { if (xh && typeof xh === 'object' && !Array.isArray(xh)) {
const xhttp = xh as Record<string, unknown>; const parsed = XHttpStreamSettingsSchema.safeParse(xh);
const xhttp = (parsed.success ? parsed.data : xh) as Record<string, unknown>;
streamRecord.xhttpSettings = xhttp;
const xmux = xhttp.xmux; const xmux = xhttp.xmux;
if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) { if (xmux && typeof xmux === 'object' && !Array.isArray(xmux)) {
xhttp.enableXmux = true; xhttp.enableXmux = true;
+61 -26
View File
@@ -13,6 +13,7 @@ import type { XHttpStreamSettings } from '@/schemas/protocols/stream/xhttp';
import { getHeaderValue } from './headers'; import { getHeaderValue } from './headers';
import { canEnableTlsFlow } from './protocol-capabilities'; import { canEnableTlsFlow } from './protocol-capabilities';
import { deriveSpiderX } from './spider-x';
// Share-link generators. Each per-protocol fn takes a typed inbound plus // Share-link generators. Each per-protocol fn takes a typed inbound plus
// client overrides and returns a URL (or '' when the protocol doesn't // client overrides and returns a URL (or '' when the protocol doesn't
@@ -322,6 +323,7 @@ export interface GenVlessLinkInput {
forceTls?: ForceTls; forceTls?: ForceTls;
remark?: string; remark?: string;
clientId: string; clientId: string;
clientKey?: string;
flow?: VlessClient['flow']; flow?: VlessClient['flow'];
externalProxy?: ExternalProxyEntry | null; externalProxy?: ExternalProxyEntry | null;
} }
@@ -350,6 +352,7 @@ export function genVlessLink(input: GenVlessLinkInput): string {
forceTls = 'same', forceTls = 'same',
remark = '', remark = '',
clientId, clientId,
clientKey = '',
flow = '', flow = '',
externalProxy = null, externalProxy = null,
} = input; } = input;
@@ -430,7 +433,8 @@ export function genVlessLink(input: GenVlessLinkInput): string {
if (sni && sni.length > 0) params.set('sni', sni); if (sni && sni.length > 0) params.set('sni', sni);
if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]); if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX); const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
if (spx.length > 0) params.set('spx', spx);
if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify); if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
} }
} else { } else {
@@ -512,7 +516,7 @@ function writeTlsParams(stream: NonNullable<Inbound['streamSettings']>, params:
// Reality query-string writer shared by VLESS and Trojan. Preserves the // Reality query-string writer shared by VLESS and Trojan. Preserves the
// legacy SNI-omission quirk (see genVlessLink for the full story). // legacy SNI-omission quirk (see genVlessLink for the full story).
function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams): void { function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, params: URLSearchParams, clientKey: string): void {
if (stream.security !== 'reality') return; if (stream.security !== 'reality') return;
const reality = stream.realitySettings; const reality = stream.realitySettings;
params.set('pbk', reality.settings.publicKey); params.set('pbk', reality.settings.publicKey);
@@ -526,7 +530,8 @@ function writeRealityParams(stream: NonNullable<Inbound['streamSettings']>, para
if (sni && sni.length > 0) params.set('sni', sni); if (sni && sni.length > 0) params.set('sni', sni);
if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]); if (reality.shortIds.length > 0) params.set('sid', reality.shortIds[0]);
if (reality.settings.spiderX.length > 0) params.set('spx', reality.settings.spiderX); const spx = deriveSpiderX(reality.settings.spiderX, clientKey);
if (spx.length > 0) params.set('spx', spx);
if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify); if (reality.settings.mldsa65Verify.length > 0) params.set('pqv', reality.settings.mldsa65Verify);
} }
@@ -537,6 +542,7 @@ export interface GenTrojanLinkInput {
forceTls?: ForceTls; forceTls?: ForceTls;
remark?: string; remark?: string;
clientPassword: string; clientPassword: string;
clientKey?: string;
externalProxy?: ExternalProxyEntry | null; externalProxy?: ExternalProxyEntry | null;
} }
@@ -551,6 +557,7 @@ export function genTrojanLink(input: GenTrojanLinkInput): string {
forceTls = 'same', forceTls = 'same',
remark = '', remark = '',
clientPassword, clientPassword,
clientKey = '',
externalProxy = null, externalProxy = null,
} = input; } = input;
@@ -571,7 +578,7 @@ export function genTrojanLink(input: GenTrojanLinkInput): string {
applyExternalProxyTLSParams(externalProxy, params, security); applyExternalProxyTLSParams(externalProxy, params, security);
} else if (security === 'reality') { } else if (security === 'reality') {
params.set('security', 'reality'); params.set('security', 'reality');
writeRealityParams(stream, params); writeRealityParams(stream, params, clientKey);
} else { } else {
params.set('security', 'none'); params.set('security', 'none');
} }
@@ -960,20 +967,51 @@ function isShareableHost(host: string): boolean {
return true; return true;
} }
function shareableListen(inbound: Inbound): string { function shareableListenFrom(listen: string): string {
const listen = inbound.listen.trim(); const trimmed = listen.trim();
return listen.length > 0 && !isUnixSocketListen(listen) && isShareableHost(listen) return trimmed.length > 0 && !isUnixSocketListen(trimmed) && isShareableHost(trimmed)
? normalizeShareHost(listen) ? normalizeShareHost(trimmed)
: ''; : '';
} }
type ShareAddrStrategy = 'node' | 'listen' | 'custom'; type ShareAddrStrategy = 'node' | 'listen' | 'custom';
function shareAddrStrategy(inbound: Inbound): ShareAddrStrategy { function normalizeShareAddrStrategy(strategy: string | undefined): ShareAddrStrategy {
const strategy = inbound.shareAddrStrategy; return strategy === 'listen' || strategy === 'custom' ? strategy : 'node';
return strategy === 'listen' || strategy === 'custom' }
? strategy
: 'node'; // ShareHostFields is the subset of an inbound resolveShareHost needs, so callers
// holding only a lightweight projection (e.g. the clients page InboundOption)
// can pick the same host as the full-inbound share/QR path.
export interface ShareHostFields {
listen?: string;
shareAddr?: string;
shareAddrStrategy?: string;
}
// resolveShareHost picks the host that goes into share/QR links, the browser-side
// analog of the backend resolveInboundAddress. hostOverride is the hosting node's
// address (empty for this panel's own inbounds); fallbackHostname is the
// already-resolved panel/public host used as the last resort — kept verbatim when
// it fails normalization (e.g. an underscore intranet hostname) so the last
// resort never degrades to an empty host.
export function resolveShareHost(
fields: ShareHostFields,
hostOverride: string,
fallbackHostname: string,
): string {
const nodeAddr = normalizeShareHost(hostOverride);
const listenAddr = shareableListenFrom(fields.listen ?? '');
const customAddr = normalizeShareHost(fields.shareAddr ?? '');
const fallbackAddr = normalizeShareHost(fallbackHostname) || fallbackHostname.trim();
switch (normalizeShareAddrStrategy(fields.shareAddrStrategy)) {
case 'listen':
return listenAddr || nodeAddr || fallbackAddr;
case 'custom':
return customAddr || nodeAddr || listenAddr || fallbackAddr;
default:
return nodeAddr || listenAddr || fallbackAddr;
}
} }
// Orchestrators. // Orchestrators.
@@ -982,18 +1020,7 @@ function shareAddrStrategy(inbound: Inbound): ShareAddrStrategy {
// node-managed inbounds; other strategies let a row prefer its listen address // node-managed inbounds; other strategies let a row prefer its listen address
// or a custom endpoint. // or a custom endpoint.
export function resolveAddr(inbound: Inbound, hostOverride: string, fallbackHostname: string): string { export function resolveAddr(inbound: Inbound, hostOverride: string, fallbackHostname: string): string {
const nodeAddr = normalizeShareHost(hostOverride); return resolveShareHost(inbound, hostOverride, fallbackHostname);
const listenAddr = shareableListen(inbound);
const customAddr = normalizeShareHost(inbound.shareAddr ?? '');
const fallbackAddr = normalizeShareHost(fallbackHostname);
switch (shareAddrStrategy(inbound)) {
case 'listen':
return listenAddr || nodeAddr || fallbackAddr;
case 'custom':
return customAddr || nodeAddr || listenAddr || fallbackAddr;
default:
return nodeAddr || listenAddr || fallbackAddr;
}
} }
// A loopback browser host means the panel was reached through a tunnel (e.g. // A loopback browser host means the panel was reached through a tunnel (e.g.
@@ -1017,7 +1044,13 @@ export function preferPublicHost(browserHost: string, publicHost: string): strin
// `this.clients` getter, which used isSSMultiUser to gate). Returns null // `this.clients` getter, which used isSSMultiUser to gate). Returns null
// for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without- // for SS single-user, http, mixed, tunnel, wireguard, hysteria2-without-
// clients, and any protocol without a clients array. // clients, and any protocol without a clients array.
type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string }; type ClientShape = { id?: string; security?: VmessSecurity; flow?: VlessClient['flow']; password?: string; auth?: string; email?: string; subId?: string };
// Mirror of the Go subKey: the stable per-client identity spx derivation
// keys on — subscription id first, unique email as the fallback.
function clientSubKey(client: ClientShape): string {
return client.subId || client.email || '';
}
export function getInboundClients(inbound: Inbound): ClientShape[] | null { export function getInboundClients(inbound: Inbound): ClientShape[] | null {
switch (inbound.protocol) { switch (inbound.protocol) {
@@ -1066,6 +1099,7 @@ export function genLink(input: GenLinkInput): string {
return genVlessLink({ return genVlessLink({
inbound, address, port, forceTls, remark, inbound, address, port, forceTls, remark,
clientId: client.id ?? '', clientId: client.id ?? '',
clientKey: clientSubKey(client),
flow: client.flow, flow: client.flow,
externalProxy, externalProxy,
}); });
@@ -1081,6 +1115,7 @@ export function genLink(input: GenLinkInput): string {
return genTrojanLink({ return genTrojanLink({
inbound, address, port, forceTls, remark, inbound, address, port, forceTls, remark,
clientPassword: client.password ?? '', clientPassword: client.password ?? '',
clientKey: clientSubKey(client),
externalProxy, externalProxy,
}); });
case 'hysteria': case 'hysteria':
+21 -8
View File
@@ -1,7 +1,9 @@
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp'; import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
import { OutboundDomainStrategySchema } from '@/schemas/protocols/outbound';
import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize'; import { normalizeStreamSettingsForWire } from '@/lib/xray/stream-wire-normalize';
import { Wireguard } from '@/utils'; import { Wireguard } from '@/utils';
import type { Sniffing, SniffingDest } from '@/schemas/primitives'; import type { Sniffing, SniffingDest } from '@/schemas/primitives';
import type { OutboundDomainStrategy } from '@/schemas/protocols/outbound';
import type { import type {
DnsOutboundFormSettings, DnsOutboundFormSettings,
@@ -56,6 +58,16 @@ function asPort(value: unknown, fallback: number): number {
return n; return n;
} }
// xray-core matches targetStrategy/domainStrategy case-insensitively;
// normalize the wire value to the canonical spelling or '' (= AsIs).
function targetStrategyFromWire(value: unknown): OutboundDomainStrategy | '' {
const s = asString(value);
if (!s) return '';
return OutboundDomainStrategySchema.options.find(
(v) => v.toLowerCase() === s.toLowerCase(),
) ?? '';
}
const SNIFFING_DEST_VALUES: readonly SniffingDest[] = ['http', 'tls', 'quic', 'fakedns']; const SNIFFING_DEST_VALUES: readonly SniffingDest[] = ['http', 'tls', 'quic', 'fakedns'];
const SNIFFING_DEFAULT: Sniffing = { const SNIFFING_DEFAULT: Sniffing = {
@@ -285,14 +297,9 @@ function freedomFromWire(raw: Raw): FreedomOutboundFormSettings {
&& typeof raw.fragment === 'object' && typeof raw.fragment === 'object'
&& Object.keys(fragment).length > 0; && Object.keys(fragment).length > 0;
return { return {
domainStrategy: ((): FreedomOutboundFormSettings['domainStrategy'] => { domainStrategy: targetStrategyFromWire(
const allowed = [ asString(raw.targetStrategy) || asString(raw.domainStrategy),
'AsIs', 'UseIP', 'UseIPv4', 'UseIPv6', 'UseIPv6v4', 'UseIPv4v6', ),
'ForceIP', 'ForceIPv6v4', 'ForceIPv6', 'ForceIPv4v6', 'ForceIPv4',
];
const s = asString(raw.domainStrategy);
return (allowed.includes(s) ? s : '') as FreedomOutboundFormSettings['domainStrategy'];
})(),
redirect: asString(raw.redirect), redirect: asString(raw.redirect),
userLevel: asNumber(raw.userLevel, 0), userLevel: asNumber(raw.userLevel, 0),
proxyProtocol: ((): FreedomOutboundFormSettings['proxyProtocol'] => { proxyProtocol: ((): FreedomOutboundFormSettings['proxyProtocol'] => {
@@ -374,6 +381,7 @@ export interface RawOutboundRow {
tag?: string; tag?: string;
protocol?: string; protocol?: string;
sendThrough?: string; sendThrough?: string;
targetStrategy?: string;
settings?: unknown; settings?: unknown;
streamSettings?: unknown; streamSettings?: unknown;
mux?: unknown; mux?: unknown;
@@ -401,6 +409,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
const settings = asObject(raw.settings); const settings = asObject(raw.settings);
const tag = asString(raw.tag); const tag = asString(raw.tag);
const sendThrough = asString(raw.sendThrough); const sendThrough = asString(raw.sendThrough);
const targetStrategy = targetStrategyFromWire(raw.targetStrategy);
const mux = muxFromWire(raw.mux); const mux = muxFromWire(raw.mux);
const hasStream = raw.streamSettings const hasStream = raw.streamSettings
&& typeof raw.streamSettings === 'object' && typeof raw.streamSettings === 'object'
@@ -430,6 +439,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
...typed, ...typed,
tag, tag,
sendThrough, sendThrough,
targetStrategy,
mux, mux,
streamSettings, streamSettings,
}; };
@@ -543,6 +553,8 @@ function hysteriaToWire(s: HysteriaOutboundFormSettings) {
} }
function freedomToWire(s: FreedomOutboundFormSettings) { function freedomToWire(s: FreedomOutboundFormSettings) {
// The strategy is emitted under the legacy domainStrategy key: new cores
// fall back to it when targetStrategy is absent, old cores only know it.
// Legacy semantics: emit fragment only when the user actually populated // Legacy semantics: emit fragment only when the user actually populated
// at least one of the four sub-fields. Defaults like packets='1-3' alone // at least one of the four sub-fields. Defaults like packets='1-3' alone
// are not enough — the modal's Fragment Switch sets all four together. // are not enough — the modal's Fragment Switch sets all four together.
@@ -672,6 +684,7 @@ export function formValuesToWirePayload(values: OutboundFormValues): WireOutboun
settings, settings,
}; };
if (values.tag) result.tag = values.tag; if (values.tag) result.tag = values.tag;
if (values.targetStrategy) result.targetStrategy = values.targetStrategy;
// streamSettings emission gates on canEnableStream — non-stream protocols // streamSettings emission gates on canEnableStream — non-stream protocols
// still emit just `sockopt` if that key is present (legacy behavior). // still emit just `sockopt` if that key is present (legacy behavior).
@@ -218,6 +218,7 @@ function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
try { try {
const parsed = JSON.parse(fm) as Record<string, unknown>; const parsed = JSON.parse(fm) as Record<string, unknown>;
if (parsed && typeof parsed === 'object') { if (parsed && typeof parsed === 'object') {
sanitizeFinalMaskQuicParams(parsed);
stream.finalmask = parsed; stream.finalmask = parsed;
} }
} catch { } catch {
@@ -225,6 +226,68 @@ function applyFinalMaskParam(stream: Raw, params: URLSearchParams): void {
} }
} }
const QUIC_PARAMS_NUMERIC_KEYS = [
'initStreamReceiveWindow',
'maxStreamReceiveWindow',
'initConnectionReceiveWindow',
'maxConnectionReceiveWindow',
'maxIdleTimeout',
'keepAlivePeriod',
'maxIncomingStreams',
] as const;
const DURATION_SECONDS: Record<string, number> = { ms: 0.001, s: 1, m: 60, h: 3600 };
const QUIC_NUMERIC_MAX = 1e15;
function coerceQuicNumeric(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.trunc(value);
}
if (typeof value === 'string') {
const asNumber = Number(value);
if (value.trim() !== '' && Number.isFinite(asNumber)) {
return Math.trunc(asNumber);
}
const duration = /^(-?\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(value.trim());
if (duration) {
return Math.trunc(Number(duration[1]) * DURATION_SECONDS[duration[2]]);
}
}
return null;
}
function clampQuicNumeric(key: string, n: number): number | null {
if (n < 0 || n > QUIC_NUMERIC_MAX) return null;
if (n === 0) return 0;
if (key === 'keepAlivePeriod') return Math.min(Math.max(n, 2), 60);
if (key === 'maxIdleTimeout') return Math.min(Math.max(n, 4), 120);
if (key === 'maxIncomingStreams') return Math.max(n, 8);
return n;
}
// xray-core rejects the whole config when these quicParams fields are not
// plain integers within its accepted ranges (keepAlivePeriod 0 or 2-60,
// maxIdleTimeout 0 or 4-120, maxIncomingStreams 0 or >= 8), so coerce
// numeric/duration strings, clamp the ranged fields, and drop anything
// unparseable, negative, or absurdly large (#5783). Mirrors the Go parser in
// internal/util/link/outbound.go.
function sanitizeFinalMaskQuicParams(parsed: Record<string, unknown>): void {
const raw = parsed.quicParams;
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return;
const quic = raw as Record<string, unknown>;
for (const key of QUIC_PARAMS_NUMERIC_KEYS) {
if (!(key in quic)) continue;
const coerced = coerceQuicNumeric(quic[key]);
const clamped = coerced === null ? null : clampQuicNumeric(key, coerced);
if (clamped === null) {
delete quic[key];
continue;
}
quic[key] = clamped;
}
}
function applySecurityParams(stream: Raw, params: URLSearchParams): void { function applySecurityParams(stream: Raw, params: URLSearchParams): void {
if (stream.security === 'tls') { if (stream.security === 'tls') {
const tls = stream.tlsSettings as Raw; const tls = stream.tlsSettings as Raw;
+10
View File
@@ -0,0 +1,10 @@
import { sha256 } from '@noble/hashes/sha2.js';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js';
// Mirrors deriveSpiderX in internal/sub/service.go byte-for-byte so panel
// links and subscription links agree; returns '' when there is no seed and
// no client key (the caller then omits spx, as the legacy builder did).
export function deriveSpiderX(seed: string, clientKey: string): string {
if (!seed && !clientKey) return '';
return `/${bytesToHex(sha256(utf8ToBytes(`${seed}|${clientKey}`))).slice(0, 15)}`;
}
+13 -1
View File
@@ -108,6 +108,18 @@ export function validateRealityTarget(target: string): string | undefined {
return undefined; return undefined;
} }
function liftLegacyXhttpSessionKeys(obj: Record<string, unknown>): void {
const lift = (legacy: string, renamed: string) => {
const v = obj[legacy];
if ((obj[renamed] === undefined || obj[renamed] === '') && typeof v === 'string' && v !== '') {
obj[renamed] = v;
}
delete obj[legacy];
};
lift('sessionPlacement', 'sessionIDPlacement');
lift('sessionKey', 'sessionIDKey');
}
function dropEmptyStrings(obj: Record<string, unknown>, keys: readonly string[]): void { function dropEmptyStrings(obj: Record<string, unknown>, keys: readonly string[]): void {
for (const key of keys) { for (const key of keys) {
const v = obj[key]; const v = obj[key];
@@ -160,6 +172,7 @@ export function normalizeXhttpForWire(
side: StreamWireSide, side: StreamWireSide,
): Record<string, unknown> { ): Record<string, unknown> {
const out: Record<string, unknown> = { ...raw }; const out: Record<string, unknown> = { ...raw };
liftLegacyXhttpSessionKeys(out);
const mode = typeof out.mode === 'string' && out.mode !== '' ? out.mode : 'auto'; const mode = typeof out.mode === 'string' && out.mode !== '' ? out.mode : 'auto';
const enableXmux = out.enableXmux === true; const enableXmux = out.enableXmux === true;
delete out.enableXmux; delete out.enableXmux;
@@ -254,7 +267,6 @@ export function normalizeSockoptForWire(
const he = out.happyEyeballs; const he = out.happyEyeballs;
if (isRecord(he)) { if (isRecord(he)) {
const heOut: Record<string, unknown> = { ...he }; const heOut: Record<string, unknown> = { ...he };
if (heOut.tryDelayMs === 0) delete heOut.tryDelayMs;
if (heOut.prioritizeIPv6 === false) delete heOut.prioritizeIPv6; if (heOut.prioritizeIPv6 === false) delete heOut.prioritizeIPv6;
if (heOut.interleave === 1) delete heOut.interleave; if (heOut.interleave === 1) delete heOut.interleave;
if (heOut.maxConcurrentTry === 4) delete heOut.maxConcurrentTry; if (heOut.maxConcurrentTry === 4) delete heOut.maxConcurrentTry;
+29
View File
@@ -0,0 +1,29 @@
export type VlessAuthKind =
| 'x25519'
| 'x25519_xorpub'
| 'x25519_random'
| 'mlkem768'
| 'mlkem768_xorpub'
| 'mlkem768_random';
export const VLESS_AUTH_LABEL_KEYS: Record<VlessAuthKind, string> = {
x25519: 'pages.inbounds.vlessAuthX25519',
x25519_xorpub: 'pages.inbounds.vlessAuthX25519Xorpub',
x25519_random: 'pages.inbounds.vlessAuthX25519Random',
mlkem768: 'pages.inbounds.vlessAuthMlkem768',
mlkem768_xorpub: 'pages.inbounds.vlessAuthMlkem768Xorpub',
mlkem768_random: 'pages.inbounds.vlessAuthMlkem768Random',
};
const MLKEM768_MIN_KEY_LENGTH = 300;
export function vlessEncryptionAuthKind(encryption: string): VlessAuthKind | null {
if (!encryption || encryption === 'none') return null;
const parts = encryption.split('.').filter(Boolean);
const authKey = parts[parts.length - 1] || '';
if (!authKey) return null;
const mode = parts[1] || 'native';
const keyType = authKey.length > MLKEM768_MIN_KEY_LENGTH ? 'mlkem768' : 'x25519';
if (mode === 'xorpub' || mode === 'random') return `${keyType}_${mode}`;
return keyType;
}
+3
View File
@@ -103,6 +103,9 @@ export class AllSetting {
hasWarpSecret = false; hasWarpSecret = false;
hasNordSecret = false; hasNordSecret = false;
hasSmtpPassword = false; hasSmtpPassword = false;
clearTgBotToken = false;
clearLdapPassword = false;
clearSmtpPassword = false;
constructor(data?: unknown) { constructor(data?: unknown) {
if (data != null) { if (data != null) {
+9 -2
View File
@@ -323,6 +323,12 @@ export const sections: readonly Section[] = [
path: '/panel/api/server/getPanelUpdateInfo', path: '/panel/api/server/getPanelUpdateInfo',
summary: 'Check whether a newer 3x-ui release is available on GitHub.', summary: 'Check whether a newer 3x-ui release is available on GitHub.',
}, },
{
method: 'GET',
path: '/panel/api/server/getUpdateStatus',
summary: 'Report the outcome of the most recently launched panel self-update (see POST updatePanel). Compare the returned runId against the one updatePanel returned to tell this run apart from a stale result.',
responseSchema: 'PanelUpdateStatus',
},
{ {
method: 'GET', method: 'GET',
path: '/panel/api/server/getConfigJson', path: '/panel/api/server/getConfigJson',
@@ -407,6 +413,7 @@ export const sections: readonly Section[] = [
method: 'POST', method: 'POST',
path: '/panel/api/server/updatePanel', path: '/panel/api/server/updatePanel',
summary: 'Self-update the panel to the latest version. The server restarts on success.', summary: 'Self-update the panel to the latest version. The server restarts on success.',
response: '{\n "success": true,\n "obj": {\n "runId": "1735689600123456789"\n }\n}',
}, },
{ {
method: 'POST', method: 'POST',
@@ -1298,7 +1305,7 @@ export const sections: readonly Section[] = [
params: [ params: [
{ name: 'outbound', in: 'body (form)', type: 'string', desc: 'JSON-encoded single outbound to test (required).' }, { name: 'outbound', in: 'body (form)', type: 'string', desc: 'JSON-encoded single outbound to test (required).' },
{ name: 'allOutbounds', in: 'body (form)', type: 'string', desc: 'JSON array of all outbounds — used to resolve dialerProxy chains.' }, { name: 'allOutbounds', in: 'body (form)', type: 'string', desc: 'JSON array of all outbounds — used to resolve dialerProxy chains.' },
{ name: 'mode', in: 'body (form)', type: 'string', desc: '"tcp" for a fast dial-only probe (parallel-safe). Default/empty uses a full HTTP probe through a temp xray instance.' }, { name: 'mode', in: 'body (form)', type: 'string', desc: '"tcp" for a fast dial-only probe (parallel-safe), "real" for a real-delay probe whose delay is the full request time including tunnel establishment. Default/empty uses a full HTTP probe reporting the warm per-request round-trip. Both HTTP variants run through a temp xray instance.' },
], ],
body: 'outbound={"protocol":"freedom","settings":{}}&mode=tcp', body: 'outbound={"protocol":"freedom","settings":{}}&mode=tcp',
}, },
@@ -1309,7 +1316,7 @@ export const sections: readonly Section[] = [
params: [ params: [
{ name: 'outbounds', in: 'body (form)', type: 'string', desc: 'JSON array of outbound configs to test (required).' }, { name: 'outbounds', in: 'body (form)', type: 'string', desc: 'JSON array of outbound configs to test (required).' },
{ name: 'allOutbounds', in: 'body (form)', type: 'string', desc: 'JSON array of all outbounds — used to resolve dialerProxy chains.' }, { name: 'allOutbounds', in: 'body (form)', type: 'string', desc: 'JSON array of all outbounds — used to resolve dialerProxy chains.' },
{ name: 'mode', in: 'body (form)', type: 'string', desc: '"tcp" for fast dial-only probes (UDP-transport outbounds are still probed over HTTP). Default/empty routes a real HTTP request through each outbound.' }, { name: 'mode', in: 'body (form)', type: 'string', desc: '"tcp" for fast dial-only probes (UDP-transport outbounds are still probed over HTTP), "real" for real-delay probes whose delay is the full request time including tunnel establishment. Default/empty routes an HTTP request through each outbound and reports the warm per-request round-trip.' },
], ],
body: 'outbounds=[{"tag":"direct","protocol":"freedom","settings":{}}]&mode=http', body: 'outbounds=[{"tag":"direct","protocol":"freedom","settings":{}}]&mode=http',
}, },
+18 -5
View File
@@ -376,12 +376,13 @@ export default function ClientFormModal({
const inboundOptions = useMemo( const inboundOptions = useMemo(
() => (inbounds || []) () => (inbounds || [])
.filter((ib) => MULTI_CLIENT_PROTOCOLS.has(ib.protocol || '')) .filter((ib) => MULTI_CLIENT_PROTOCOLS.has(ib.protocol || ''))
.filter((ib) => ib.enable || (form.inboundIds || []).includes(ib.id))
.map((ib) => ({ .map((ib) => ({
label: formatInboundLabel(ib.tag, ib.remark), label: formatInboundLabel(ib.tag, ib.remark),
value: ib.id, value: ib.id,
title: formatInboundLabel(ib.tag, ib.remark), title: formatInboundLabel(ib.tag, ib.remark),
})), })),
[inbounds], [inbounds, form.inboundIds],
); );
const linkRows = useMemo(() => form.externalLinks.filter((r) => r.kind === 'link'), [form.externalLinks]); const linkRows = useMemo(() => form.externalLinks.filter((r) => r.kind === 'link'), [form.externalLinks]);
@@ -492,6 +493,13 @@ export default function ClientFormModal({
if (form.wgPreSharedKey) { if (form.wgPreSharedKey) {
clientPayload.preSharedKey = form.wgPreSharedKey; clientPayload.preSharedKey = form.wgPreSharedKey;
} }
const allowedIPs = form.wgAllowedIPs
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '');
if (allowedIPs.length > 0) {
clientPayload.allowedIPs = allowedIPs;
}
} }
const externalLinks: ExternalLinkInput[] = form.externalLinks const externalLinks: ExternalLinkInput[] = form.externalLinks
@@ -802,11 +810,16 @@ export default function ClientFormModal({
onChange={(e) => update('wgPreSharedKey', e.target.value)} onChange={(e) => update('wgPreSharedKey', e.target.value)}
/> />
</Form.Item> </Form.Item>
{isEdit && form.wgAllowedIPs && ( <Form.Item
<Form.Item label={t('pages.clients.wireguardAllowedIPs')}> label={t('pages.clients.wireguardAllowedIPs')}
<Input value={form.wgAllowedIPs} disabled /> extra={t('pages.clients.wireguardAllowedIPsHint')}
>
<Input
value={form.wgAllowedIPs}
placeholder="10.0.0.2/32"
onChange={(e) => update('wgAllowedIPs', e.target.value)}
/>
</Form.Item> </Form.Item>
)}
</> </>
)} )}
</> </>
@@ -308,6 +308,12 @@ export default function ClientInfoModal({
<td>{t('pages.inbounds.updatedAt')}</td> <td>{t('pages.inbounds.updatedAt')}</td>
<td><Tag>{dateLabel(client.updatedAt)}</Tag></td> <td><Tag>{dateLabel(client.updatedAt)}</Tag></td>
</tr> </tr>
{client.group && (
<tr>
<td>{t('pages.clients.group')}</td>
<td><Tag color="geekblue">{client.group}</Tag></td>
</tr>
)}
{client.comment && ( {client.comment && (
<tr> <tr>
<td>{t('pages.clients.comment')}</td> <td>{t('pages.clients.comment')}</td>
@@ -162,6 +162,12 @@
background: color-mix(in srgb, var(--ant-color-primary) 6%, transparent); background: color-mix(in srgb, var(--ant-color-primary) 6%, transparent);
} }
.client-card-speed {
margin-top: 6px;
font-size: 12px;
color: var(--ant-color-text-secondary);
}
.card-head { .card-head {
display: flex; display: flex;
align-items: center; align-items: center;
+23 -1
View File
@@ -61,6 +61,7 @@ import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useDatepicker } from '@/hooks/useDatepicker'; import { useDatepicker } from '@/hooks/useDatepicker';
import type { ClientRecord, InboundOption, ExternalLink, ExternalLinkInput } from '@/hooks/useClients'; import type { ClientRecord, InboundOption, ExternalLink, ExternalLinkInput } from '@/hooks/useClients';
import ClientTrafficCell from '@/components/clients/ClientTrafficCell'; import ClientTrafficCell from '@/components/clients/ClientTrafficCell';
import ClientSpeedTag, { isActiveSpeed } from '@/components/clients/ClientSpeedTag';
import AppSidebar from '@/layouts/AppSidebar'; import AppSidebar from '@/layouts/AppSidebar';
import { IntlUtil, SizeFormatter } from '@/utils'; import { IntlUtil, SizeFormatter } from '@/utils';
import { setMessageInstance } from '@/utils/messageBus'; import { setMessageInstance } from '@/utils/messageBus';
@@ -209,6 +210,7 @@ export default function ClientsPage() {
tgBotEnable, expireDiff, trafficDiff, pageSize, tgBotEnable, expireDiff, trafficDiff, pageSize,
create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach, create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable, resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable,
clientSpeed,
applyTrafficEvent, applyClientStatsEvent, applyTrafficEvent, applyClientStatsEvent,
refresh, refresh,
hydrate, hydrate,
@@ -902,6 +904,17 @@ export default function ClientsPage() {
/> />
), ),
}, },
{
title: t('pages.clients.speed'),
key: 'speed',
width: 110,
align: 'center',
render: (_v, record) => {
const speed = clientSpeed[record.email];
if (!isActiveSpeed(speed)) return <Tag color="default">—</Tag>;
return <ClientSpeedTag speed={speed} />;
},
},
{ {
title: t('pages.clients.remaining'), title: t('pages.clients.remaining'),
key: 'remaining', key: 'remaining',
@@ -919,7 +932,7 @@ export default function ClientsPage() {
), ),
}, },
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters, allGroups, datepicker, trafficDiff]); ], [t, togglingEmail, clientBucket, isOnline, inboundsById, filters, allGroups, datepicker, trafficDiff, clientSpeed]);
const tablePagination = { const tablePagination = {
current: currentPage, current: currentPage,
@@ -1428,6 +1441,15 @@ export default function ClientsPage() {
enabled={row.enable} enabled={row.enable}
trafficDiff={trafficDiff} trafficDiff={trafficDiff}
/> />
{(() => {
const speed = clientSpeed[row.email];
if (!isActiveSpeed(speed)) return null;
return (
<div className="client-card-speed">
<ClientSpeedTag speed={speed} />
</div>
);
})()}
</div> </div>
); );
})} })}
@@ -1,5 +1,5 @@
import { formatInboundLabel } from '@/lib/inbounds/label'; import { formatInboundLabel } from '@/lib/inbounds/label';
import { preferPublicHost } from '@/lib/xray/inbound-link'; import { preferPublicHost, resolveShareHost } from '@/lib/xray/inbound-link';
import type { ClientRecord, InboundOption } from '@/hooks/useClients'; import type { ClientRecord, InboundOption } from '@/hooks/useClients';
export function isWireguardClient(client: ClientRecord | null | undefined): boolean { export function isWireguardClient(client: ClientRecord | null | undefined): boolean {
@@ -22,7 +22,7 @@ export function buildWireguardClientConfig(
host = window.location.hostname, host = window.location.hostname,
publicHost = '', publicHost = '',
): string { ): string {
const endpointHost = preferPublicHost(host, publicHost); const endpointHost = resolveShareHost(inbound ?? {}, inbound?.nodeAddress ?? '', preferPublicHost(host, publicHost));
const address = client.allowedIPs || '10.0.0.2/32'; const address = client.allowedIPs || '10.0.0.2/32';
const endpoint = `${endpointHost}:${inbound?.port || ''}`; const endpoint = `${endpointHost}:${inbound?.port || ''}`;
const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : ''; const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : '';
@@ -50,7 +50,7 @@ export default function GroupAddClientsModal({
if (!open) return; if (!open) return;
setSelectedEmails([]); setSelectedEmails([]);
setSearch(''); setSearch('');
}, [open, rows]); }, [open]);
const filteredRows = useMemo(() => { const filteredRows = useMemo(() => {
const q = search.trim().toLowerCase(); const q = search.trim().toLowerCase();
@@ -48,7 +48,7 @@ export default function GroupRemoveClientsModal({
if (!open) return; if (!open) return;
setSelectedEmails([]); setSelectedEmails([]);
setSearch(''); setSearch('');
}, [open, rows]); }, [open]);
const filteredRows = useMemo(() => { const filteredRows = useMemo(() => {
const q = search.trim().toLowerCase(); const q = search.trim().toLowerCase();
@@ -41,6 +41,7 @@ import { Protocols } from '@/schemas/primitives';
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt'; import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
import { HysteriaStreamSettingsSchema } from '@/schemas/protocols/stream/hysteria'; import { HysteriaStreamSettingsSchema } from '@/schemas/protocols/stream/hysteria';
import { createHysteriaTlsSettingsWithDefaultCert } from '@/lib/xray/inbound-tls-defaults'; import { createHysteriaTlsSettingsWithDefaultCert } from '@/lib/xray/inbound-tls-defaults';
import { VLESS_AUTH_LABEL_KEYS, vlessEncryptionAuthKind } from '@/lib/xray/vless-encryption';
import { SniffingSchema } from '@/schemas/primitives/sniffing'; import { SniffingSchema } from '@/schemas/primitives/sniffing';
import { TcpStreamSettingsSchema } from '@/schemas/protocols/stream/tcp'; import { TcpStreamSettingsSchema } from '@/schemas/protocols/stream/tcp';
import { KcpStreamSettingsSchema } from '@/schemas/protocols/stream/kcp'; import { KcpStreamSettingsSchema } from '@/schemas/protocols/stream/kcp';
@@ -248,6 +249,7 @@ export default function InboundFormModal({
scanRealityCandidates, scanRealityCandidates,
applyRealityScanResult, applyRealityScanResult,
randomizeShortIds, randomizeShortIds,
randomizeSpiderX,
getNewEchCert, getNewEchCert,
clearEchCert, clearEchCert,
pinFromCert, pinFromCert,
@@ -316,27 +318,14 @@ export default function InboundFormModal({
form.setFieldValue(['settings', 'encryption'], 'none'); form.setFieldValue(['settings', 'encryption'], 'none');
}; };
const vlessAuthKind = vlessEncryptionAuthKind(
typeof vlessEncryption === 'string' ? vlessEncryption : '',
);
const selectedVlessAuth = (() => { const selectedVlessAuth = (() => {
const enc = typeof vlessEncryption === 'string' ? vlessEncryption : ''; const enc = typeof vlessEncryption === 'string' ? vlessEncryption : '';
if (!enc || enc === 'none') return 'None'; if (!enc || enc === 'none') return 'None';
const parts = enc.split('.').filter(Boolean); if (!vlessAuthKind) return t('pages.inbounds.vlessAuthCustom');
const authKey = parts[parts.length - 1] || ''; return t(VLESS_AUTH_LABEL_KEYS[vlessAuthKind]);
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
const mode = parts[1] || 'native';
const keyType = authKey.length > 300 ? 'mlkem768' : 'x25519';
if (mode === 'xorpub') {
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768Xorpub')
: t('pages.inbounds.vlessAuthX25519Xorpub');
}
if (mode === 'random') {
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768Random')
: t('pages.inbounds.vlessAuthX25519Random');
}
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768')
: t('pages.inbounds.vlessAuthX25519');
})(); })();
useEffect(() => { useEffect(() => {
@@ -539,6 +528,7 @@ export default function InboundFormModal({
{selectableNodes.length > 0 && isNodeEligible && ( {selectableNodes.length > 0 && isNodeEligible && (
<Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}> <Form.Item name="nodeId" label={t('pages.inbounds.deployTo')}>
<Select <Select
showSearch
disabled={mode === 'edit'} disabled={mode === 'edit'}
placeholder={t('pages.inbounds.localPanel')} placeholder={t('pages.inbounds.localPanel')}
allowClear allowClear
@@ -702,7 +692,7 @@ export default function InboundFormModal({
{protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />} {protocol === Protocols.SHADOWSOCKS && <ShadowsocksFields form={form} isSSWith2022={isSSWith2022} />}
{protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />} {protocol === Protocols.VLESS && <VlessFields saving={saving} selectedVlessAuth={selectedVlessAuth} vlessAuthKind={vlessAuthKind} network={network} security={security} getNewVlessEnc={getNewVlessEnc} clearVlessEnc={clearVlessEnc} />}
{isFallbackHost && fallbacksCard} {isFallbackHost && fallbacksCard}
{(protocol === Protocols.VLESS || protocol === Protocols.TROJAN) {(protocol === Protocols.VLESS || protocol === Protocols.TROJAN)
@@ -896,6 +886,7 @@ export default function InboundFormModal({
scanRealityCandidates={scanRealityCandidates} scanRealityCandidates={scanRealityCandidates}
applyRealityScanResult={applyRealityScanResult} applyRealityScanResult={applyRealityScanResult}
randomizeShortIds={randomizeShortIds} randomizeShortIds={randomizeShortIds}
randomizeSpiderX={randomizeSpiderX}
genRealityKeypair={genRealityKeypair} genRealityKeypair={genRealityKeypair}
clearRealityKeypair={clearRealityKeypair} clearRealityKeypair={clearRealityKeypair}
genMldsa65={genMldsa65} genMldsa65={genMldsa65}
@@ -1,18 +1,13 @@
import { useState } from 'react'; import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Select, Space, Typography } from 'antd'; import { Button, Form, Input, InputNumber, Select, Space, Typography } from 'antd';
type VlessAuthKind = import { VLESS_AUTH_LABEL_KEYS, type VlessAuthKind } from '@/lib/xray/vless-encryption';
| 'x25519'
| 'x25519_xorpub'
| 'x25519_random'
| 'mlkem768'
| 'mlkem768_xorpub'
| 'mlkem768_random';
interface VlessFieldsProps { interface VlessFieldsProps {
saving: boolean; saving: boolean;
selectedVlessAuth: string; selectedVlessAuth: string;
vlessAuthKind: VlessAuthKind | null;
network: string; network: string;
security: string; security: string;
getNewVlessEnc: (kind: VlessAuthKind) => void; getNewVlessEnc: (kind: VlessAuthKind) => void;
@@ -22,22 +17,22 @@ interface VlessFieldsProps {
export default function VlessFields({ export default function VlessFields({
saving, saving,
selectedVlessAuth, selectedVlessAuth,
vlessAuthKind,
network, network,
security, security,
getNewVlessEnc, getNewVlessEnc,
clearVlessEnc, clearVlessEnc,
}: VlessFieldsProps) { }: VlessFieldsProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const [authKind, setAuthKind] = useState<VlessAuthKind>('x25519'); const [authKind, setAuthKind] = useState<VlessAuthKind>(vlessAuthKind ?? 'x25519');
const authOptions = [ useEffect(() => {
{ value: 'x25519', label: t('pages.inbounds.vlessAuthX25519') }, setAuthKind(vlessAuthKind ?? 'x25519');
{ value: 'x25519_xorpub', label: t('pages.inbounds.vlessAuthX25519Xorpub') }, }, [vlessAuthKind]);
{ value: 'x25519_random', label: t('pages.inbounds.vlessAuthX25519Random') },
{ value: 'mlkem768', label: t('pages.inbounds.vlessAuthMlkem768') }, const authOptions = (Object.entries(VLESS_AUTH_LABEL_KEYS) as [VlessAuthKind, string][]).map(
{ value: 'mlkem768_xorpub', label: t('pages.inbounds.vlessAuthMlkem768Xorpub') }, ([value, labelKey]) => ({ value, label: t(labelKey) }),
{ value: 'mlkem768_random', label: t('pages.inbounds.vlessAuthMlkem768Random') }, );
];
return ( return (
<> <>
@@ -16,6 +16,7 @@ interface RealityFormProps {
scanRealityCandidates: (targets?: string) => Promise<RealityScanResult[]>; scanRealityCandidates: (targets?: string) => Promise<RealityScanResult[]>;
applyRealityScanResult: (result: RealityScanResult) => void; applyRealityScanResult: (result: RealityScanResult) => void;
randomizeShortIds: () => void; randomizeShortIds: () => void;
randomizeSpiderX: () => void;
genRealityKeypair: () => void; genRealityKeypair: () => void;
clearRealityKeypair: () => void; clearRealityKeypair: () => void;
genMldsa65: () => void; genMldsa65: () => void;
@@ -30,6 +31,7 @@ export default function RealityForm({
scanRealityCandidates, scanRealityCandidates,
applyRealityScanResult, applyRealityScanResult,
randomizeShortIds, randomizeShortIds,
randomizeSpiderX,
genRealityKeypair, genRealityKeypair,
clearRealityKeypair, clearRealityKeypair,
genMldsa65, genMldsa65,
@@ -147,10 +149,18 @@ export default function RealityForm({
</Space.Compact> </Space.Compact>
</Form.Item> </Form.Item>
<Form.Item <Form.Item
name={['streamSettings', 'realitySettings', 'settings', 'spiderX']}
label={t('pages.inbounds.form.spiderX')} label={t('pages.inbounds.form.spiderX')}
tooltip={t('pages.inbounds.form.spiderXHint')}
> >
<Input /> <Space.Compact block style={{ display: 'flex' }}>
<Form.Item
name={['streamSettings', 'realitySettings', 'settings', 'spiderX']}
noStyle
>
<Input style={{ flex: 1 }} />
</Form.Item>
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={randomizeSpiderX} />
</Space.Compact>
</Form.Item> </Form.Item>
<Form.Item <Form.Item
name={['streamSettings', 'realitySettings', 'settings', 'publicKey']} name={['streamSettings', 'realitySettings', 'settings', 'publicKey']}
@@ -124,6 +124,13 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
); );
}; };
const randomizeSpiderX = () => {
form.setFieldValue(
['streamSettings', 'realitySettings', 'settings', 'spiderX'],
`/${RandomUtil.randomSeq(15)}`,
);
};
const getNewEchCert = async () => { const getNewEchCert = async () => {
const sni = form.getFieldValue(['streamSettings', 'tlsSettings', 'serverName']); const sni = form.getFieldValue(['streamSettings', 'tlsSettings', 'serverName']);
setSaving(true); setSaving(true);
@@ -270,6 +277,7 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
} }
form.setFieldValue('streamSettings', cleaned); form.setFieldValue('streamSettings', cleaned);
if (next === 'reality') { if (next === 'reality') {
randomizeSpiderX();
try { try {
const msg = await HttpUtil.get('/panel/api/server/getNewX25519Cert'); const msg = await HttpUtil.get('/panel/api/server/getNewX25519Cert');
if (msg?.success) { if (msg?.success) {
@@ -292,6 +300,7 @@ export function useSecurityActions({ form, setSaving, messageApi, nodeId, setSca
scanRealityCandidates, scanRealityCandidates,
applyRealityScanResult, applyRealityScanResult,
randomizeShortIds, randomizeShortIds,
randomizeSpiderX,
getNewEchCert, getNewEchCert,
clearEchCert, clearEchCert,
pinFromCert, pinFromCert,
@@ -5,6 +5,7 @@ import {
Card, Card,
Checkbox, Checkbox,
Dropdown, Dropdown,
Input,
Select, Select,
Space, Space,
Switch, Switch,
@@ -22,6 +23,7 @@ import {
ReloadOutlined, ReloadOutlined,
InfoCircleOutlined, InfoCircleOutlined,
DeleteOutlined, DeleteOutlined,
SearchOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { HttpUtil } from '@/utils'; import { HttpUtil } from '@/utils';
@@ -56,6 +58,7 @@ export default function InboundList({
// Node filter (#4997): 'all' shows everything, 0 is the local-panel // Node filter (#4997): 'all' shows everything, 0 is the local-panel
// sentinel (inbounds without a nodeId), otherwise a node id. Session-only. // sentinel (inbounds without a nodeId), otherwise a node id. Session-only.
const [nodeFilter, setNodeFilter] = useState<number | 'all'>('all'); const [nodeFilter, setNodeFilter] = useState<number | 'all'>('all');
const [searchKey, setSearchKey] = useState('');
const showNodeFilter = useMemo( const showNodeFilter = useMemo(
() => nodesById.size > 0 || dbInbounds.some((ib) => ib.nodeId != null), () => nodesById.size > 0 || dbInbounds.some((ib) => ib.nodeId != null),
@@ -72,10 +75,17 @@ export default function InboundList({
); );
const visibleInbounds = useMemo(() => { const visibleInbounds = useMemo(() => {
if (nodeFilter === 'all') return dbInbounds; let list = dbInbounds;
if (nodeFilter === 0) return dbInbounds.filter((ib) => ib.nodeId == null); if (nodeFilter === 0) list = list.filter((ib) => ib.nodeId == null);
return dbInbounds.filter((ib) => ib.nodeId === nodeFilter); else if (nodeFilter !== 'all') list = list.filter((ib) => ib.nodeId === nodeFilter);
}, [dbInbounds, nodeFilter]); const q = searchKey.trim().toLowerCase();
if (!q) return list;
return list.filter((ib) => (
(ib.remark || '').toLowerCase().includes(q)
|| String(ib.port).includes(q)
|| (ib.protocol || '').toLowerCase().includes(q)
));
}, [dbInbounds, nodeFilter, searchKey]);
const onSwitchEnable = useCallback(async (dbInbound: DBInboundRecord, next: boolean) => { const onSwitchEnable = useCallback(async (dbInbound: DBInboundRecord, next: boolean) => {
const previous = dbInbound.enable; const previous = dbInbound.enable;
@@ -174,11 +184,21 @@ export default function InboundList({
value={nodeFilter} value={nodeFilter}
onChange={(v) => setNodeFilter(v)} onChange={(v) => setNodeFilter(v)}
options={nodeFilterOptions} options={nodeFilterOptions}
showSearch
popupMatchSelectWidth={false} popupMatchSelectWidth={false}
style={{ minWidth: isMobile ? 90 : 140 }} style={{ minWidth: isMobile ? 90 : 140 }}
aria-label={t('pages.clients.filters.nodes')} aria-label={t('pages.clients.filters.nodes')}
/> />
)} )}
<Input
value={searchKey}
onChange={(e) => setSearchKey(e.target.value)}
placeholder={t('search')}
allowClear
prefix={<SearchOutlined />}
style={{ maxWidth: isMobile ? 110 : 200 }}
aria-label={t('search')}
/>
{selectedRowKeys.length > 0 && ( {selectedRowKeys.length > 0 && (
<> <>
<Tag color="blue" closable onClose={() => setSelectedRowKeys([])} style={{ marginInlineEnd: 0 }}> <Tag color="blue" closable onClose={() => setSelectedRowKeys([])} style={{ marginInlineEnd: 0 }}>
+1 -4
View File
@@ -13,6 +13,7 @@ import { OnlinesSchema, OnlineByNodeSchema, ActiveInboundsByNodeSchema } from '@
import { DefaultsPayloadSchema, type DefaultsPayload } from '@/schemas/defaults'; import { DefaultsPayloadSchema, type DefaultsPayload } from '@/schemas/defaults';
import type { InboundSpeedEntry } from './list/types'; import type { InboundSpeedEntry } from './list/types';
import { TRAFFIC_POLL_INTERVAL_S } from '@/lib/traffic/poll-interval';
export interface SubSettings { export interface SubSettings {
enable: boolean; enable: boolean;
@@ -28,10 +29,6 @@ export interface SubSettings {
type DBInboundInstance = InstanceType<typeof DBInbound>; type DBInboundInstance = InstanceType<typeof DBInbound>;
// Server-side traffic polling interval in seconds. XrayTrafficJob broadcasts
// deltas accumulated over this window, so dividing by it yields bytes/sec.
const TRAFFIC_POLL_INTERVAL_S = 5;
// Speed is delta-derived, so it can't be recomputed until the first poll after // Speed is delta-derived, so it can't be recomputed until the first poll after
// mount; navigating away and back would otherwise blank the column for up to one // mount; navigating away and back would otherwise blank the column for up to one
// poll. Cache the last speed map across mounts (module scope) and reseed from it // poll. Cache the last speed map across mounts (module scope) and reseed from it
+24 -7
View File
@@ -6,8 +6,11 @@ import axios from 'axios';
import { HttpUtil, PromiseUtil } from '@/utils'; import { HttpUtil, PromiseUtil } from '@/utils';
import { formatPanelVersion } from '@/lib/panel-version'; import { formatPanelVersion } from '@/lib/panel-version';
import type { PanelUpdateStatus } from '@/generated/types';
import './PanelUpdateModal.css'; import './PanelUpdateModal.css';
type UpdateOutcome = 'success' | 'failed' | 'timeout';
export interface PanelUpdateInfo { export interface PanelUpdateInfo {
channel?: string; channel?: string;
currentVersion: string; currentVersion: string;
@@ -45,19 +48,23 @@ export default function PanelUpdateModal({
const isDev = info.channel === 'dev'; const isDev = info.channel === 'dev';
async function pollUntilBack(): Promise<boolean> { async function pollUpdateStatus(expectedRunId: string): Promise<UpdateOutcome> {
await PromiseUtil.sleep(5000); await PromiseUtil.sleep(5000);
const deadline = Date.now() + 90_000; const deadline = Date.now() + 90_000;
while (Date.now() < deadline) { while (Date.now() < deadline) {
try { try {
const r = await axios.get('/panel/api/server/status', { timeout: 2000 }); const r = await axios.get('/panel/api/server/getUpdateStatus', { timeout: 2000 });
if (r?.data?.success) return true; const status = r?.data?.obj as PanelUpdateStatus | undefined;
if (status?.runId === expectedRunId) {
if (status.state === 'success') return 'success';
if (status.state === 'failed') return 'failed';
}
} catch { } catch {
/* still restarting */ /* still restarting */
} }
await PromiseUtil.sleep(2000); await PromiseUtil.sleep(2000);
} }
return false; return 'timeout';
} }
async function handleChannel(checked: boolean) { async function handleChannel(checked: boolean) {
@@ -81,14 +88,24 @@ export default function PanelUpdateModal({
const tip = info.latestVersion ? `${baseTip} (${info.latestVersion})` : baseTip; const tip = info.latestVersion ? `${baseTip} (${info.latestVersion})` : baseTip;
onClose(); onClose();
onBusy({ busy: true, tip }); onBusy({ busy: true, tip });
const result = await HttpUtil.post('/panel/api/server/updatePanel'); const result = await HttpUtil.post<{ runId: string }>('/panel/api/server/updatePanel');
if (!result?.success) { if (!result?.success) {
onBusy({ busy: false }); onBusy({ busy: false });
return; return;
} }
const back = await pollUntilBack(); const outcome = await pollUpdateStatus(result.obj?.runId ?? '');
if (back) await PromiseUtil.sleep(800); onBusy({ busy: false });
if (outcome === 'success') {
await PromiseUtil.sleep(800);
window.location.reload(); window.location.reload();
return;
}
modal[outcome === 'failed' ? 'error' : 'warning']({
title: t(outcome === 'failed' ? 'pages.index.panelUpdateFailedTitle' : 'pages.index.panelUpdateUnknownTitle'),
content: t(outcome === 'failed' ? 'pages.index.panelUpdateFailedDesc' : 'pages.index.panelUpdateUnknownDesc'),
okText: t('refresh'),
onOk: () => window.location.reload(),
});
}, },
}); });
} }
+8 -4
View File
@@ -8,6 +8,7 @@ import { SettingListItem } from '@/components/ui';
import { EmailNotifications } from '@/components/ui/notifications/EmailNotifications'; import { EmailNotifications } from '@/components/ui/notifications/EmailNotifications';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel'; import { catTabLabel } from './catTabLabel';
import SecretInput from './SecretInput';
interface EmailTabProps { interface EmailTabProps {
allSetting: AllSetting; allSetting: AllSetting;
@@ -72,10 +73,13 @@ export default function EmailTab({ allSetting, updateSetting }: EmailTabProps) {
</SettingListItem> </SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.smtpPassword')} <SettingListItem paddings="small" title={t('pages.settings.smtpPassword')}
description={allSetting.hasSmtpPassword ? t('pages.settings.smtpPasswordConfigured') : t('pages.settings.smtpPasswordDesc')}> description={allSetting.hasSmtpPassword && !allSetting.clearSmtpPassword ? t('pages.settings.smtpPasswordConfigured') : t('pages.settings.smtpPasswordDesc')}>
<Input.Password value={allSetting.smtpPassword} <SecretInput value={allSetting.smtpPassword}
placeholder={allSetting.hasSmtpPassword ? t('pages.settings.smtpPasswordPlaceholder') : ''} configured={allSetting.hasSmtpPassword}
onChange={(e) => updateSetting({ smtpPassword: e.target.value })} /> clearArmed={allSetting.clearSmtpPassword}
placeholder={t('pages.settings.smtpPasswordPlaceholder')}
onChange={(v) => updateSetting({ smtpPassword: v })}
onClearArmedChange={(armed) => updateSetting({ clearSmtpPassword: armed })} />
</SettingListItem> </SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.smtpTo')} description={t('pages.settings.smtpToDesc')}> <SettingListItem paddings="small" title={t('pages.settings.smtpTo')} description={t('pages.settings.smtpToDesc')}>
+8 -4
View File
@@ -21,6 +21,7 @@ import { SettingListItem } from '@/components/ui';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel'; import { catTabLabel } from './catTabLabel';
import { sanitizePath } from './uriPath'; import { sanitizePath } from './uriPath';
import SecretInput from './SecretInput';
interface ApiMsg<T = unknown> { interface ApiMsg<T = unknown> {
success?: boolean; success?: boolean;
@@ -329,12 +330,15 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
<SettingListItem <SettingListItem
paddings="small" paddings="small"
title={t('password')} title={t('password')}
description={allSetting.hasLdapPassword ? t('pages.settings.ldap.passwordConfigured') : t('pages.settings.ldap.passwordUnconfigured')} description={allSetting.hasLdapPassword && !allSetting.clearLdapPassword ? t('pages.settings.ldap.passwordConfigured') : t('pages.settings.ldap.passwordUnconfigured')}
> >
<Input.Password <SecretInput
value={allSetting.ldapPassword} value={allSetting.ldapPassword}
placeholder={allSetting.hasLdapPassword ? t('pages.settings.ldap.passwordPlaceholder') : ''} configured={allSetting.hasLdapPassword}
onChange={(e) => updateSetting({ ldapPassword: e.target.value })} clearArmed={allSetting.clearLdapPassword}
placeholder={t('pages.settings.ldap.passwordPlaceholder')}
onChange={(v) => updateSetting({ ldapPassword: v })}
onClearArmedChange={(armed) => updateSetting({ clearLdapPassword: armed })}
/> />
</SettingListItem> </SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.ldap.baseDn')}> <SettingListItem paddings="small" title={t('pages.settings.ldap.baseDn')}>
@@ -0,0 +1,45 @@
import { Button, Input, Space } from 'antd';
import { useTranslation } from 'react-i18next';
interface SecretInputProps {
value: string;
configured: boolean;
clearArmed: boolean;
placeholder: string;
onChange: (value: string) => void;
onClearArmedChange: (armed: boolean) => void;
}
export default function SecretInput({
value,
configured,
clearArmed,
placeholder,
onChange,
onClearArmedChange,
}: SecretInputProps) {
const { t } = useTranslation();
return (
<Space.Compact style={{ width: '100%' }}>
<Input.Password
value={value}
placeholder={configured && !clearArmed ? placeholder : ''}
onChange={(e) => {
onChange(e.target.value);
if (clearArmed) onClearArmedChange(false);
}}
/>
{configured && (
<Button
danger={clearArmed}
onClick={() => {
onChange('');
onClearArmedChange(!clearArmed);
}}
>
{clearArmed ? t('pages.settings.secretClearUndo') : t('pages.settings.secretClear')}
</Button>
)}
</Space.Compact>
);
}
+1 -1
View File
@@ -204,7 +204,7 @@ export default function SettingsPage() {
case 'subscription-formats': return <SubscriptionFormatsTab allSetting={allSetting} updateSetting={updateSetting} />; case 'subscription-formats': return <SubscriptionFormatsTab allSetting={allSetting} updateSetting={updateSetting} />;
default: return <GeneralTab allSetting={allSetting} updateSetting={updateSetting} />; default: return <GeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
} }
}, [activeSlug, allSetting, updateSetting]); }, [activeSlug, allSetting, updateSetting, savePayload]);
return ( return (
<ConfigProvider theme={antdThemeConfig}> <ConfigProvider theme={antdThemeConfig}>
@@ -79,7 +79,7 @@ export default function SubscriptionGeneralTab({ allSetting, updateSetting }: Su
</SettingListItem> </SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.subUpdates')} description={t('pages.settings.subUpdatesDesc')}> <SettingListItem paddings="small" title={t('pages.settings.subUpdates')} description={t('pages.settings.subUpdatesDesc')}>
<InputNumber value={allSetting.subUpdates} min={1} style={{ width: '100%' }} <InputNumber value={allSetting.subUpdates} min={0} max={525600} style={{ width: '100%' }}
onChange={(v) => updateSetting({ subUpdates: Number(v) || 0 })} /> onChange={(v) => updateSetting({ subUpdates: Number(v) || 0 })} />
</SettingListItem> </SettingListItem>
</> </>
+8 -4
View File
@@ -9,6 +9,7 @@ import { SettingListItem } from '@/components/ui';
import { TelegramNotifications } from '@/components/ui/notifications/TelegramNotifications'; import { TelegramNotifications } from '@/components/ui/notifications/TelegramNotifications';
import { useMediaQuery } from '@/hooks/useMediaQuery'; import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel'; import { catTabLabel } from './catTabLabel';
import SecretInput from './SecretInput';
interface TelegramTabProps { interface TelegramTabProps {
allSetting: AllSetting; allSetting: AllSetting;
@@ -193,12 +194,15 @@ export default function TelegramTab({ allSetting, updateSetting }: TelegramTabPr
<SettingListItem <SettingListItem
paddings="small" paddings="small"
title={t('pages.settings.telegramToken')} title={t('pages.settings.telegramToken')}
description={allSetting.hasTgBotToken ? t('pages.settings.telegramTokenConfigured') : t('pages.settings.telegramTokenDesc')} description={allSetting.hasTgBotToken && !allSetting.clearTgBotToken ? t('pages.settings.telegramTokenConfigured') : t('pages.settings.telegramTokenDesc')}
> >
<Input.Password <SecretInput
value={allSetting.tgBotToken} value={allSetting.tgBotToken}
placeholder={allSetting.hasTgBotToken ? t('pages.settings.telegramTokenPlaceholder') : ''} configured={allSetting.hasTgBotToken}
onChange={(e) => updateSetting({ tgBotToken: e.target.value })} clearArmed={allSetting.clearTgBotToken}
placeholder={t('pages.settings.telegramTokenPlaceholder')}
onChange={(v) => updateSetting({ tgBotToken: v })}
onClearArmedChange={(armed) => updateSetting({ clearTgBotToken: armed })}
/> />
</SettingListItem> </SettingListItem>
+5
View File
@@ -1,6 +1,7 @@
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react'; import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { import {
Alert,
Button, Button,
Card, Card,
Col, Col,
@@ -61,6 +62,7 @@ const links: string[] = Array.isArray(subData.links) ? subData.links : [];
const linkEmails: string[] = Array.isArray(subData.emails) ? subData.emails : []; const linkEmails: string[] = Array.isArray(subData.emails) ? subData.emails : [];
const subEmail = [...new Set(linkEmails.filter(Boolean))].join(', '); const subEmail = [...new Set(linkEmails.filter(Boolean))].join(', ');
const datepicker = subData.datepicker || 'gregorian'; const datepicker = subData.datepicker || 'gregorian';
const announce = subData.announce || '';
const isUnlimited = totalByte <= 0 && expireMs === 0; const isUnlimited = totalByte <= 0 && expireMs === 0;
const isActive = (() => { const isActive = (() => {
@@ -283,6 +285,9 @@ export default function SubPage() {
<Row justify="center"> <Row justify="center">
<Col xs={24} sm={22} md={18} lg={14} xl={12}> <Col xs={24} sm={22} md={18} lg={14} xl={12}>
<Card hoverable className="subscription-card" title={cardTitle} extra={cardExtra}> <Card hoverable className="subscription-card" title={cardTitle} extra={cardExtra}>
{announce && (
<Alert type="info" showIcon message={announce} style={{ marginBottom: 16 }} />
)}
<Descriptions <Descriptions
bordered bordered
column={1} column={1}
@@ -367,7 +367,6 @@ export default function BalancersTab({
<ObservatorySettingsTab <ObservatorySettingsTab
templateSettings={templateSettings} templateSettings={templateSettings}
mutate={mutate} mutate={mutate}
isMobile={isMobile}
/> />
), ),
}, },
@@ -1,6 +1,6 @@
import { useMemo, useState } from 'react'; import { useMemo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Alert, Empty, Input, InputNumber, Segmented, Select, Space, Switch, Tag } from 'antd'; import { Alert, Empty, Input, InputNumber, Select, Space, Switch, Tag } from 'antd';
import { SettingListItem } from '@/components/ui'; import { SettingListItem } from '@/components/ui';
import { import {
@@ -13,11 +13,11 @@ import {
type PingConfigObject, type PingConfigObject,
} from '@/schemas/observatory'; } from '@/schemas/observatory';
import type { XraySettingsValue } from '@/hooks/useXraySetting'; import type { XraySettingsValue } from '@/hooks/useXraySetting';
import { settingsRequireBurstObservatory } from './balancer-helpers';
interface ObservatorySettingsTabProps { interface ObservatorySettingsTabProps {
templateSettings: XraySettingsValue | null; templateSettings: XraySettingsValue | null;
mutate: (mutator: (next: XraySettingsValue) => void) => void; mutate: (mutator: (next: XraySettingsValue) => void) => void;
isMobile: boolean;
} }
const OBSERVATORY_DEFAULTS = ObservatorySchema.parse({}); const OBSERVATORY_DEFAULTS = ObservatorySchema.parse({});
@@ -43,7 +43,6 @@ function SelectorTags({ tags }: { tags: string[] }) {
export default function ObservatorySettingsTab({ export default function ObservatorySettingsTab({
templateSettings, templateSettings,
mutate, mutate,
isMobile,
}: ObservatorySettingsTabProps) { }: ObservatorySettingsTabProps) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -63,13 +62,10 @@ export default function ObservatorySettingsTab({
const hasObservatory = observatory != null; const hasObservatory = observatory != null;
const hasBurst = burst != null; const hasBurst = burst != null;
const hasMixedObservers = hasObservatory && hasBurst;
const [view, setView] = useState<'observatory' | 'burstObservatory'>('observatory'); const activeView = hasBurst && (!hasObservatory || settingsRequireBurstObservatory(templateSettings))
const effectiveView = !hasObservatory && hasBurst
? 'burstObservatory' ? 'burstObservatory'
: !hasBurst && hasObservatory : 'observatory';
? 'observatory'
: view;
function patchObservatory(patch: Partial<ObservatoryObject>) { function patchObservatory(patch: Partial<ObservatoryObject>) {
mutate((tt) => { mutate((tt) => {
@@ -220,19 +216,15 @@ export default function ObservatorySettingsTab({
return ( return (
<Space orientation="vertical" size="middle" style={{ width: '100%' }}> <Space orientation="vertical" size="middle" style={{ width: '100%' }}>
<Alert type="info" showIcon message={t('pages.xray.observatory.autoManaged')} /> <Alert type="info" showIcon title={t('pages.xray.observatory.autoManaged')} />
{hasObservatory && hasBurst && ( {hasMixedObservers && (
<Segmented <Alert
block={isMobile} type="warning"
value={effectiveView} showIcon
onChange={(v) => setView(v as 'observatory' | 'burstObservatory')} title={t('pages.xray.observatory.mixedLegacy')}
options={[
{ label: t('pages.xray.observatory.title'), value: 'observatory' },
{ label: t('pages.xray.observatory.burstTitle'), value: 'burstObservatory' },
]}
/> />
)} )}
<div>{effectiveView === 'observatory' ? observatorySection : burstSection}</div> <div>{activeView === 'observatory' ? observatorySection : burstSection}</div>
</Space> </Space>
); );
} }
@@ -26,6 +26,16 @@ export function collectSelectors(list: BalancerObject[]): string[] {
return [...out]; return [...out];
} }
export function balancerRequiresBurstObservatory(b: BalancerObject): boolean {
const type = b.strategy?.type || 'random';
return type === 'leastLoad' || ((type === 'random' || type === 'roundRobin') && (b.fallbackTag ?? '').length > 0);
}
export function settingsRequireBurstObservatory(t: XraySettingsValue | null): boolean {
const balancers = (t?.routing?.balancers || []) as BalancerObject[];
return balancers.some(balancerRequiresBurstObservatory);
}
// syncObservatories keeps the (burst)observatory sections aligned with the // syncObservatories keeps the (burst)observatory sections aligned with the
// balancer strategies that actually require them. Observatories have no runtime // balancer strategies that actually require them. Observatories have no runtime
// reload API in xray-core, so creating OR removing one forces a full process // reload API in xray-core, so creating OR removing one forces a full process
@@ -36,39 +46,35 @@ export function collectSelectors(list: BalancerObject[]): string[] {
// when its fallbackTag is set (issue #5605): with a fallbackTag the strategy // when its fallbackTag is set (issue #5605): with a fallbackTag the strategy
// calls RequireFeatures(Observatory) and the core aborts startup with "not all // calls RequireFeatures(Observatory) and the core aborts startup with "not all
// dependencies are resolved" if none exists; without a fallbackTag it never even // dependencies are resolved" if none exists; without a fallbackTag it never even
// consults an observatory. leastLoad always needs the burst observer, leastPing // consults an observatory. leastLoad needs the burst observer, while leastPing
// the regular one. // can use any extension.Observatory result with Alive/Delay. When a burst
// observer is required, keep all observer-backed balancers on burstObservatory
// to avoid xray-core resolving the earlier regular observatory feature instead.
// //
// So each observer lives exactly as long as something requires it, and is // So each observer lives exactly as long as something requires it, and is
// dropped the moment nothing does — clearing the last fallbackTag (or deleting // dropped the moment nothing does — clearing the last fallbackTag (or deleting
// the last leastLoad) removes the burst observer again. A no-fallback balancer's // the last leastLoad) removes the burst observer again. A no-fallback
// selector is still probed while the observer exists for another reason, but // Random/RoundRobin balancer never expands the observer either, because those
// never keeps it alive on its own. // strategies do not consume observer data.
export function syncObservatories(t: XraySettingsValue) { export function syncObservatories(t: XraySettingsValue) {
const balancers = (t.routing?.balancers || []) as BalancerObject[]; const balancers = (t.routing?.balancers || []) as BalancerObject[];
const leastPings = balancers.filter((b) => b.strategy?.type === 'leastPing'); const leastPings = balancers.filter((b) => b.strategy?.type === 'leastPing');
const required = balancers.filter(balancerRequiresBurstObservatory);
if (required.length > 0) {
delete t.observatory;
if (!t.burstObservatory) t.burstObservatory = JSON.parse(JSON.stringify(DEFAULT_BURST_OBSERVATORY));
(t.burstObservatory as { subjectSelector: string[] }).subjectSelector = collectSelectors([
...required,
...leastPings,
]);
} else {
delete t.burstObservatory;
if (leastPings.length > 0) { if (leastPings.length > 0) {
if (!t.observatory) t.observatory = JSON.parse(JSON.stringify(DEFAULT_OBSERVATORY)); if (!t.observatory) t.observatory = JSON.parse(JSON.stringify(DEFAULT_OBSERVATORY));
(t.observatory as { subjectSelector: string[] }).subjectSelector = collectSelectors(leastPings); (t.observatory as { subjectSelector: string[] }).subjectSelector = collectSelectors(leastPings);
} else { } else {
delete t.observatory; delete t.observatory;
} }
const hasFallback = (b: BalancerObject) => (b.fallbackTag ?? '').length > 0;
const required = balancers.filter((b) => {
const type = b.strategy?.type || 'random';
if (type === 'leastLoad') return true;
return (type === 'random' || type === 'roundRobin') && hasFallback(b);
});
const optional = balancers.filter((b) => {
const type = b.strategy?.type || 'random';
return (type === 'random' || type === 'roundRobin') && !hasFallback(b);
});
if (required.length > 0) {
if (!t.burstObservatory) t.burstObservatory = JSON.parse(JSON.stringify(DEFAULT_BURST_OBSERVATORY));
(t.burstObservatory as { subjectSelector: string[] }).subjectSelector = collectSelectors([...required, ...optional]);
} else {
delete t.burstObservatory;
} }
} }
@@ -13,7 +13,7 @@ import {
import { SizeFormatter } from '@/utils'; import { SizeFormatter } from '@/utils';
import { OutboundProtocols as Protocols } from '@/schemas/primitives'; import { OutboundProtocols as Protocols } from '@/schemas/primitives';
import type { OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting'; import type { OutboundTestMode, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundRow } from './outbounds-tab-types'; import type { OutboundRow } from './outbounds-tab-types';
import TestResultPopover from './TestResultPopover'; import TestResultPopover from './TestResultPopover';
@@ -28,7 +28,7 @@ import {
interface OutboundCardListProps { interface OutboundCardListProps {
rows: OutboundRow[]; rows: OutboundRow[];
testMode: 'tcp' | 'http'; testMode: OutboundTestMode;
outboundsTraffic: OutboundTrafficRow[]; outboundsTraffic: OutboundTrafficRow[];
outboundTestStates: Record<number, OutboundTestState>; outboundTestStates: Record<number, OutboundTestState>;
setFirst: (idx: number) => void; setFirst: (idx: number) => void;
@@ -39,6 +39,7 @@ import {
NETWORK_OPTIONS, NETWORK_OPTIONS,
PROTOCOL_OPTIONS, PROTOCOL_OPTIONS,
SERVER_PROTOCOLS, SERVER_PROTOCOLS,
TARGET_STRATEGY_OPTIONS,
} from './outbound-form-constants'; } from './outbound-form-constants';
import { import {
applyNetworkChange, applyNetworkChange,
@@ -394,6 +395,14 @@ export default function OutboundFormModal({
<Input placeholder={t('pages.xray.outboundForm.localIpPlaceholder')} /> <Input placeholder={t('pages.xray.outboundForm.localIpPlaceholder')} />
</Form.Item> </Form.Item>
<Form.Item
label={t('pages.xray.outbound.targetStrategy')}
name="targetStrategy"
tooltip={t('pages.xray.outboundForm.targetStrategyHint')}
>
<Select allowClear placeholder="AsIs" options={TARGET_STRATEGY_OPTIONS} />
</Form.Item>
{SERVER_PROTOCOLS.has(protocol) && <ServerTarget />} {SERVER_PROTOCOLS.has(protocol) && <ServerTarget />}
{protocol === 'vmess' && <VmessFields />} {protocol === 'vmess' && <VmessFields />}
{protocol === 'vless' && <VlessFields />} {protocol === 'vless' && <VlessFields />}
@@ -45,7 +45,7 @@ import OutboundFormModal from './OutboundFormModal';
import { propagateOutboundTagRename } from '../basics/helpers'; import { propagateOutboundTagRename } from '../basics/helpers';
import { planOutboundDeletion, applyOutboundDeletion } from '../reference-cleanup'; import { planOutboundDeletion, applyOutboundDeletion } from '../reference-cleanup';
import DeletionImpactList from '../DeletionImpactList'; import DeletionImpactList from '../DeletionImpactList';
import type { XraySettingsValue, SetTemplate, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting'; import type { XraySettingsValue, SetTemplate, OutboundTestMode, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import './OutboundsTab.css'; import './OutboundsTab.css';
import type { OutboundRow } from './outbounds-tab-types'; import type { OutboundRow } from './outbounds-tab-types';
@@ -110,7 +110,7 @@ export default function OutboundsTab({
const { t } = useTranslation(); const { t } = useTranslation();
const [modal, modalContextHolder] = Modal.useModal(); const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage(); const [messageApi, messageContextHolder] = message.useMessage();
const [testMode, setTestMode] = useState<'tcp' | 'http'>('tcp'); const [testMode, setTestMode] = useState<OutboundTestMode>('tcp');
const [modalOpen, setModalOpen] = useState(false); const [modalOpen, setModalOpen] = useState(false);
const [editingOutbound, setEditingOutbound] = useState<Record<string, unknown> | null>(null); const [editingOutbound, setEditingOutbound] = useState<Record<string, unknown> | null>(null);
const [editingIndex, setEditingIndex] = useState<number | null>(null); const [editingIndex, setEditingIndex] = useState<number | null>(null);
@@ -486,6 +486,7 @@ export default function OutboundsTab({
<Radio.Group value={testMode} onChange={(e) => setTestMode(e.target.value)} buttonStyle="solid" size="small"> <Radio.Group value={testMode} onChange={(e) => setTestMode(e.target.value)} buttonStyle="solid" size="small">
<Radio.Button value="tcp">TCP</Radio.Button> <Radio.Button value="tcp">TCP</Radio.Button>
<Radio.Button value="http">HTTP</Radio.Button> <Radio.Button value="http">HTTP</Radio.Button>
<Radio.Button value="real">{t('pages.xray.outbound.modeRealDelay')}</Radio.Button>
</Radio.Group> </Radio.Group>
</Tooltip> </Tooltip>
<Button type="primary" loading={testingAll} icon={<PlayCircleOutlined />} onClick={() => onTestAll(testMode)}> <Button type="primary" loading={testingAll} icon={<PlayCircleOutlined />} onClick={() => onTestAll(testMode)}>
@@ -6,16 +6,17 @@ import type { ColumnsType } from 'antd/es/table';
import { SizeFormatter } from '@/utils'; import { SizeFormatter } from '@/utils';
import { OutboundProtocols as Protocols } from '@/schemas/primitives'; import { OutboundProtocols as Protocols } from '@/schemas/primitives';
import { isUdpOutbound } from '@/hooks/useXraySetting'; import type { OutboundTestMode, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundRow } from './outbounds-tab-types'; import type { OutboundRow } from './outbounds-tab-types';
import TestResultPopover from './TestResultPopover'; import TestResultPopover from './TestResultPopover';
import { import {
effectiveTestMode,
isTesting, isTesting,
isUntestable, isUntestable,
outboundAddresses, outboundAddresses,
showSecurity, showSecurity,
testModeLabel,
testResult, testResult,
trafficFor, trafficFor,
} from './outbounds-tab-helpers'; } from './outbounds-tab-helpers';
@@ -24,7 +25,7 @@ interface SubscriptionOutboundsProps {
subscriptionOutbounds: unknown[]; subscriptionOutbounds: unknown[];
outboundsTraffic: OutboundTrafficRow[]; outboundsTraffic: OutboundTrafficRow[];
subscriptionTestStates: Record<string, OutboundTestState>; subscriptionTestStates: Record<string, OutboundTestState>;
testMode: 'tcp' | 'http'; testMode: OutboundTestMode;
isMobile: boolean; isMobile: boolean;
onTestSubscription: (outbound: Record<string, unknown>, mode: string) => void; onTestSubscription: (outbound: Record<string, unknown>, mode: string) => void;
} }
@@ -104,7 +105,7 @@ export default function SubscriptionOutbounds({
const testButton = (record: OutboundRow) => { const testButton = (record: OutboundRow) => {
const key = record.tag || ''; const key = record.tag || '';
return ( return (
<Tooltip title={`${t('check')} (${(isUdpOutbound(record) ? 'http' : testMode).toUpperCase()})`}> <Tooltip title={`${t('check')} (${testModeLabel(effectiveTestMode(record, testMode), t)})`}>
<Button <Button
aria-label={t('check')} aria-label={t('check')}
type="primary" type="primary"
@@ -5,6 +5,8 @@ import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
import type { OutboundTestResult } from '@/hooks/useXraySetting'; import type { OutboundTestResult } from '@/hooks/useXraySetting';
import { testModeLabel } from './outbounds-tab-helpers';
interface TestResultPopoverProps { interface TestResultPopoverProps {
result: OutboundTestResult; result: OutboundTestResult;
// Custom trigger element; defaults to the ok/fail latency pill. // Custom trigger element; defaults to the ok/fail latency pill.
@@ -39,7 +41,7 @@ export default function TestResultPopover({ result: r, children }: TestResultPop
<div className="timing-breakdown"> <div className="timing-breakdown">
<div className={`td-head ${r.success ? 'ok' : 'fail'}`}> <div className={`td-head ${r.success ? 'ok' : 'fail'}`}>
{r.success ? <span>{r.delay} ms</span> : <span>{r.error || 'failed'}</span>} {r.success ? <span>{r.delay} ms</span> : <span>{r.error || 'failed'}</span>}
{r.mode && <span className="mode-badge">{String(r.mode).toUpperCase()}</span>} {r.mode && <span className="mode-badge">{testModeLabel(String(r.mode), t)}</span>}
</div> </div>
{(r.endpoints || []).map((ep) => ( {(r.endpoints || []).map((ep) => (
<div key={ep.address} className="endpoint-row"> <div key={ep.address} className="endpoint-row">
@@ -7,6 +7,7 @@ import {
USERS_SECURITY, USERS_SECURITY,
UTLS_FINGERPRINT, UTLS_FINGERPRINT,
} from '@/schemas/primitives'; } from '@/schemas/primitives';
import { OutboundDomainStrategySchema } from '@/schemas/protocols/outbound';
import { SSMethodSchema } from '@/schemas/protocols/shared/shadowsocks'; import { SSMethodSchema } from '@/schemas/protocols/shared/shadowsocks';
export const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p })); export const PROTOCOL_OPTIONS = Object.values(Protocols).map((p) => ({ value: p, label: p }));
@@ -20,6 +21,10 @@ export const ADDRESS_PORT_STRATEGY_OPTIONS = Object.values(Address_Port_Strategy
value: v, value: v,
label: v, label: v,
})); }));
export const TARGET_STRATEGY_OPTIONS = OutboundDomainStrategySchema.options.map((v) => ({
value: v,
label: v,
}));
// canEnableMux mirrors the adapter's helper but lives here so the modal // canEnableMux mirrors the adapter's helper but lives here so the modal
// can show/hide the Mux section without going through the adapter. // can show/hide the Mux section without going through the adapter.
@@ -1,5 +1,8 @@
import type { TFunction } from 'i18next';
import { OutboundProtocols as Protocols } from '@/schemas/primitives'; import { OutboundProtocols as Protocols } from '@/schemas/primitives';
import type { OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting'; import { isUdpOutbound } from '@/hooks/useXraySetting';
import type { OutboundTestMode, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundRow } from './outbounds-tab-types'; import type { OutboundRow } from './outbounds-tab-types';
@@ -45,6 +48,14 @@ export function showSecurity(security?: string): boolean {
return security === 'tls' || security === 'reality'; return security === 'tls' || security === 'reality';
} }
export function effectiveTestMode(o: unknown, mode: OutboundTestMode): OutboundTestMode {
return mode === 'tcp' && isUdpOutbound(o) ? 'http' : mode;
}
export function testModeLabel(mode: string, t: TFunction): string {
return mode === 'real' ? t('pages.xray.outbound.modeRealDelay') : mode.toUpperCase();
}
export function trafficFor(outboundsTraffic: OutboundTrafficRow[], o: OutboundRow): { up: number; down: number } { export function trafficFor(outboundsTraffic: OutboundTrafficRow[], o: OutboundRow): { up: number; down: number } {
const tr = outboundsTraffic.find((x) => x.tag === o.tag); const tr = outboundsTraffic.find((x) => x.tag === o.tag);
return { up: tr?.up || 0, down: tr?.down || 0 }; return { up: tr?.up || 0, down: tr?.down || 0 };
@@ -16,22 +16,23 @@ import type { ColumnsType } from 'antd/es/table';
import { SizeFormatter } from '@/utils'; import { SizeFormatter } from '@/utils';
import { OutboundProtocols as Protocols } from '@/schemas/primitives'; import { OutboundProtocols as Protocols } from '@/schemas/primitives';
import { isUdpOutbound } from '@/hooks/useXraySetting'; import type { OutboundTestMode, OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundTestState, OutboundTrafficRow } from '@/hooks/useXraySetting';
import type { OutboundRow } from './outbounds-tab-types'; import type { OutboundRow } from './outbounds-tab-types';
import TestResultPopover from './TestResultPopover'; import TestResultPopover from './TestResultPopover';
import { import {
effectiveTestMode,
isTesting, isTesting,
isUntestable, isUntestable,
outboundAddresses, outboundAddresses,
showSecurity, showSecurity,
testModeLabel,
testResult, testResult,
trafficFor, trafficFor,
} from './outbounds-tab-helpers'; } from './outbounds-tab-helpers';
interface OutboundColumnsParams { interface OutboundColumnsParams {
testMode: 'tcp' | 'http'; testMode: OutboundTestMode;
rows: OutboundRow[]; rows: OutboundRow[];
outboundsTraffic: OutboundTrafficRow[]; outboundsTraffic: OutboundTrafficRow[];
outboundTestStates: Record<number, OutboundTestState>; outboundTestStates: Record<number, OutboundTestState>;
@@ -167,7 +168,7 @@ export function useOutboundColumns({
align: 'center', align: 'center',
width: 80, width: 80,
render: (_v, record, index) => ( render: (_v, record, index) => (
<Tooltip title={`${t('check')} (${(isUdpOutbound(record) ? 'http' : testMode).toUpperCase()})`}> <Tooltip title={`${t('check')} (${testModeLabel(effectiveTestMode(record, testMode), t)})`}>
<Button <Button
type="primary" type="primary"
shape="circle" shape="circle"
+7
View File
@@ -54,6 +54,13 @@ export const InboundOptionSchema = z.object({
wgDns: z.string().optional(), wgDns: z.string().optional(),
// Hosting node id; absent/null for this panel's own inbounds (#4997). // Hosting node id; absent/null for this panel's own inbounds (#4997).
nodeId: z.number().nullable().optional(), nodeId: z.number().nullable().optional(),
// Share-host resolution inputs, mirroring the backend resolveInboundAddress so
// the clients page picks the same WireGuard endpoint host as the subscription:
// the hosting node address, the inbound listen, and its share-address strategy.
nodeAddress: z.string().optional(),
listen: z.string().optional(),
shareAddr: z.string().optional(),
shareAddrStrategy: z.string().optional(),
}).loose(); }).loose();
export const InboundOptionsSchema = z.array(InboundOptionSchema); export const InboundOptionsSchema = z.array(InboundOptionSchema);
+4 -2
View File
@@ -219,11 +219,13 @@ export const OutboundStreamFormSchema = NetworkSettingsSchema
.and(StreamExtrasSchema); .and(StreamExtrasSchema);
export type OutboundStreamFormValues = z.infer<typeof OutboundStreamFormSchema>; export type OutboundStreamFormValues = z.infer<typeof OutboundStreamFormSchema>;
// Top-level form base: identity (tag, sendThrough), then the per-protocol // Top-level form base: identity (tag, sendThrough, targetStrategy), then
// settings DU, then the stream sub-form, then mux. // the per-protocol settings DU, then the stream sub-form, then mux.
// targetStrategy '' means AsIs (omitted from wire).
export const OutboundFormBaseSchema = z.object({ export const OutboundFormBaseSchema = z.object({
tag: z.string().default(''), tag: z.string().default(''),
sendThrough: z.string().default(''), sendThrough: z.string().default(''),
targetStrategy: z.union([OutboundDomainStrategySchema, z.literal('')]).default(''),
streamSettings: OutboundStreamFormSchema.optional(), streamSettings: OutboundStreamFormSchema.optional(),
mux: MuxFormSchema.default({ mux: MuxFormSchema.default({
enabled: false, enabled: false,
@@ -33,7 +33,7 @@ export const AddressPortStrategySchema = z.enum([
export type AddressPortStrategy = z.infer<typeof AddressPortStrategySchema>; export type AddressPortStrategy = z.infer<typeof AddressPortStrategySchema>;
export const HappyEyeballsSchema = z.object({ export const HappyEyeballsSchema = z.object({
tryDelayMs: z.number().int().min(0).default(0), tryDelayMs: z.number().int().min(0).default(250),
prioritizeIPv6: z.boolean().default(false), prioritizeIPv6: z.boolean().default(false),
interleave: z.number().int().min(1).default(1), interleave: z.number().int().min(1).default(1),
maxConcurrentTry: z.number().int().min(0).default(4), maxConcurrentTry: z.number().int().min(0).default(4),
+1 -1
View File
@@ -53,7 +53,7 @@ export const AllSettingSchema = z.object({
restartXrayOnClientDisable: z.boolean().optional(), restartXrayOnClientDisable: z.boolean().optional(),
subCertFile: z.string().optional(), subCertFile: z.string().optional(),
subKeyFile: z.string().optional(), subKeyFile: z.string().optional(),
subUpdates: z.number().int().min(1).max(168).optional(), subUpdates: z.number().int().min(0).max(525600).optional(),
subEncrypt: z.boolean().optional(), subEncrypt: z.boolean().optional(),
subURI: z.string().optional(), subURI: z.string().optional(),
subJsonURI: z.string().optional(), subJsonURI: z.string().optional(),
@@ -8,7 +8,7 @@ exports[`genInboundLinks orchestrator > shadowsocks-tcp-2022: byte-stable 1`] =
exports[`genInboundLinks orchestrator > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@override.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`; exports[`genInboundLinks orchestrator > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@override.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`;
exports[`genInboundLinks orchestrator > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@override.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2F&flow=xtls-rprx-vision#parity-test"`; exports[`genInboundLinks orchestrator > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@override.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2Fdafd018f50a389b&flow=xtls-rprx-vision#parity-test"`;
exports[`genInboundLinks orchestrator > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@override.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`; exports[`genInboundLinks orchestrator > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@override.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`;
@@ -36,7 +36,7 @@ exports[`genShadowsocksLink > shadowsocks-tcp-2022: byte-stable 1`] = `"ss://202
exports[`genTrojanLink > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@example.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`; exports[`genTrojanLink > trojan-ws-tls: byte-stable 1`] = `"trojan://trojan-test-pw-XYZ@example.test:443?type=ws&path=%2Ftrojan&host=trojan.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=trojan.example.test#parity-test"`;
exports[`genVlessLink > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@example.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2F&flow=xtls-rprx-vision#parity-test"`; exports[`genVlessLink > vless-tcp-reality: byte-stable 1`] = `"vless://22222222-3333-4444-9555-666666666666@example.test:443?type=tcp&encryption=none&security=reality&pbk=Tx5yj1bRcOPHkdvT2pIAQ2zh0gQ8m4OPdnzqXJxxV3o&fp=chrome&sni=yahoo.com&sid=a3f1&spx=%2Fd08ed99bd9afc60&flow=xtls-rprx-vision#parity-test"`;
exports[`genVlessLink > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@example.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`; exports[`genVlessLink > vless-ws-tls: byte-stable 1`] = `"vless://8c14d6f7-2e3b-4a91-9d24-3f7a6b8c1e02@example.test:443?type=ws&encryption=none&path=%2Fws&host=cdn.example.test&security=tls&fp=chrome&alpn=h2%2Chttp%2F1.1&sni=cdn.example.test#parity-test"`;
@@ -7,12 +7,208 @@ function tpl(routing: Record<string, unknown>, extra: Record<string, unknown> =
return { routing, ...extra } as unknown as XraySettingsValue; return { routing, ...extra } as unknown as XraySettingsValue;
} }
type ExpectedObserver = 'none' | 'observatory' | 'burstObservatory';
function expectObserver(t: XraySettingsValue, expected: ExpectedObserver, selectors: string[] = []) {
if (expected === 'none') {
expect(t.observatory).toBeUndefined();
expect(t.burstObservatory).toBeUndefined();
return;
}
if (expected === 'observatory') {
expect(t.observatory).toBeDefined();
expect(t.burstObservatory).toBeUndefined();
expect(new Set((t.observatory as { subjectSelector: string[] }).subjectSelector)).toEqual(new Set(selectors));
return;
}
expect(t.observatory).toBeUndefined();
expect(t.burstObservatory).toBeDefined();
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(new Set(selectors));
}
// Observatory sections have no reload API in xray-core, so creating one turns // Observatory sections have no reload API in xray-core, so creating one turns
// a balancer save from a live (hot-applied) routing change into a full // a balancer save from a live (hot-applied) routing change into a full
// restart. These tests pin the rule: only strategies that genuinely need an // restart. These tests pin the rule: only strategies that genuinely need an
// observer may create one — which, for random/roundRobin, means a fallbackTag // observer may create one — which, for random/roundRobin, means a fallbackTag
// is set (xray-core then requires the Observatory feature; see #5605). // is set (xray-core then requires the Observatory feature; see #5605).
describe('syncObservatories', () => { describe('syncObservatories', () => {
it.each([
{
name: 'random without fallback',
balancers: [{ tag: 'random', selector: ['random-out'] }],
expected: 'none' as const,
selectors: [],
},
{
name: 'random with fallback',
balancers: [{ tag: 'random', selector: ['random-out'], fallbackTag: 'direct' }],
expected: 'burstObservatory' as const,
selectors: ['random-out'],
},
{
name: 'roundRobin without fallback',
balancers: [{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } }],
expected: 'none' as const,
selectors: [],
},
{
name: 'roundRobin with fallback',
balancers: [{ tag: 'rr', selector: ['rr-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } }],
expected: 'burstObservatory' as const,
selectors: ['rr-out'],
},
{
name: 'leastPing without fallback',
balancers: [{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }],
expected: 'observatory' as const,
selectors: ['lp-out'],
},
{
name: 'leastPing with fallback',
balancers: [{ tag: 'lp', selector: ['lp-out'], fallbackTag: 'direct', strategy: { type: 'leastPing' } }],
expected: 'observatory' as const,
selectors: ['lp-out'],
},
{
name: 'leastLoad without fallback',
balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }],
expected: 'burstObservatory' as const,
selectors: ['ll-out'],
},
{
name: 'leastLoad with fallback',
balancers: [{ tag: 'll', selector: ['ll-out'], fallbackTag: 'direct', strategy: { type: 'leastLoad' } }],
expected: 'burstObservatory' as const,
selectors: ['ll-out'],
},
])('covers standalone strategy: $name', ({ balancers, expected, selectors }) => {
const t = tpl({ balancers });
syncObservatories(t);
expectObserver(t, expected, selectors);
});
it.each([
{
name: 'random + roundRobin without fallbacks',
balancers: [
{ tag: 'random', selector: ['random-out'] },
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
],
expected: 'none' as const,
selectors: [],
},
{
name: 'leastPing + random without fallback',
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'random', selector: ['random-out'] },
],
expected: 'observatory' as const,
selectors: ['lp-out'],
},
{
name: 'leastPing + roundRobin without fallback',
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
],
expected: 'observatory' as const,
selectors: ['lp-out'],
},
{
name: 'random fallback + random without fallback',
balancers: [
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
{ tag: 'random', selector: ['random-out'] },
],
expected: 'burstObservatory' as const,
selectors: ['random-fallback-out'],
},
{
name: 'roundRobin fallback + roundRobin without fallback',
balancers: [
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
],
expected: 'burstObservatory' as const,
selectors: ['rr-fallback-out'],
},
{
name: 'leastLoad + random without fallback',
balancers: [
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
{ tag: 'random', selector: ['random-out'] },
],
expected: 'burstObservatory' as const,
selectors: ['ll-out'],
},
{
name: 'leastLoad + roundRobin without fallback',
balancers: [
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
],
expected: 'burstObservatory' as const,
selectors: ['ll-out'],
},
{
name: 'leastPing + leastLoad with disjoint selectors',
balancers: [
{ tag: 'lp', selector: ['lp-out', 'direct'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out-1', 'll-out-2'], strategy: { type: 'leastLoad' } },
],
expected: 'burstObservatory' as const,
selectors: ['lp-out', 'direct', 'll-out-1', 'll-out-2'],
},
{
name: 'leastPing + random fallback',
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
],
expected: 'burstObservatory' as const,
selectors: ['lp-out', 'random-fallback-out'],
},
{
name: 'leastPing + roundRobin fallback',
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
],
expected: 'burstObservatory' as const,
selectors: ['lp-out', 'rr-fallback-out'],
},
{
name: 'all strategies mixed',
balancers: [
{ tag: 'random', selector: ['random-out'] },
{ tag: 'rr', selector: ['rr-out'], strategy: { type: 'roundRobin' } },
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
{ tag: 'rrf', selector: ['rr-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
],
expected: 'burstObservatory' as const,
selectors: ['random-fallback-out', 'rr-fallback-out', 'lp-out', 'll-out'],
},
{
name: 'shared selectors are de-duplicated',
balancers: [
{ tag: 'lp', selector: ['shared', 'lp-only'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['shared', 'll-only'], strategy: { type: 'leastLoad' } },
{ tag: 'rf', selector: ['shared', 'rf-only'], fallbackTag: 'direct' },
],
expected: 'burstObservatory' as const,
selectors: ['shared', 'lp-only', 'll-only', 'rf-only'],
},
])('covers mixed strategy matrix: $name', ({ balancers, expected, selectors }) => {
const t = tpl({ balancers });
syncObservatories(t);
expectObserver(t, expected, selectors);
});
it('does not create burstObservatory for a fresh random balancer (stays hot-appliable)', () => { it('does not create burstObservatory for a fresh random balancer (stays hot-appliable)', () => {
const t = tpl({ balancers: [{ tag: 'b1', selector: ['direct'] }] }); const t = tpl({ balancers: [{ tag: 'b1', selector: ['direct'] }] });
syncObservatories(t); syncObservatories(t);
@@ -64,7 +260,7 @@ describe('syncObservatories', () => {
expect(t.burstObservatory).toBeUndefined(); expect(t.burstObservatory).toBeUndefined();
}); });
it('keeps burstObservatory while another fallback balancer still needs it', () => { it('keeps burstObservatory while another fallback balancer still needs it without adding no-fallback selectors', () => {
const t = tpl( const t = tpl(
{ {
balancers: [ balancers: [
@@ -76,7 +272,7 @@ describe('syncObservatories', () => {
); );
syncObservatories(t); syncObservatories(t);
expect(t.burstObservatory).toBeDefined(); expect(t.burstObservatory).toBeDefined();
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b', 'a']); expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b']);
}); });
it('creates burstObservatory for leastLoad (required by the strategy)', () => { it('creates burstObservatory for leastLoad (required by the strategy)', () => {
@@ -86,20 +282,55 @@ describe('syncObservatories', () => {
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']); expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']);
}); });
it('creates observatory for leastPing (required by the strategy)', () => { it('creates observatory for leastPing when no burst observer is required', () => {
const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastPing' } }] }); const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastPing' } }] });
syncObservatories(t); syncObservatories(t);
expect(t.observatory).toBeDefined(); expect(t.observatory).toBeDefined();
expect((t.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']); expect((t.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['a']);
}); });
it('keeps an existing burstObservatory in sync for random balancers (legacy setups)', () => { it('uses only burstObservatory when leastPing is mixed with leastLoad', () => {
const t = tpl(
{
balancers: [
{ tag: 'lp', selector: ['least-ping-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['least-load-out'], strategy: { type: 'leastLoad' } },
],
},
{ observatory: { subjectSelector: ['stale-least-ping-out'] } },
);
syncObservatories(t);
expect(t.observatory).toBeUndefined();
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(
new Set(['least-load-out', 'least-ping-out']),
);
});
it('uses only burstObservatory when leastPing is mixed with fallback balancers', () => {
const t = tpl(
{
balancers: [
{ tag: 'lp', selector: ['least-ping-out'], strategy: { type: 'leastPing' } },
{ tag: 'rf', selector: ['random-fallback-out'], fallbackTag: 'direct' },
{ tag: 'rr', selector: ['round-robin-fallback-out'], fallbackTag: 'direct', strategy: { type: 'roundRobin' } },
],
},
{ observatory: { subjectSelector: ['stale-least-ping-out'] } },
);
syncObservatories(t);
expect(t.observatory).toBeUndefined();
expect(new Set((t.burstObservatory as { subjectSelector: string[] }).subjectSelector)).toEqual(
new Set(['random-fallback-out', 'round-robin-fallback-out', 'least-ping-out']),
);
});
it('does not keep no-fallback random selectors in an observer created by another balancer', () => {
const t = tpl( const t = tpl(
{ balancers: [{ tag: 'b1', selector: ['a'] }, { tag: 'b2', selector: ['b'], strategy: { type: 'leastLoad' } }] }, { balancers: [{ tag: 'b1', selector: ['a'] }, { tag: 'b2', selector: ['b'], strategy: { type: 'leastLoad' } }] },
{ burstObservatory: { subjectSelector: ['stale'] } }, { burstObservatory: { subjectSelector: ['stale'] } },
); );
syncObservatories(t); syncObservatories(t);
expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b', 'a']); expect((t.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['b']);
}); });
it('removes observatories when no balancer can use them', () => { it('removes observatories when no balancer can use them', () => {
@@ -112,6 +343,30 @@ describe('syncObservatories', () => {
expect(t.burstObservatory).toBeUndefined(); expect(t.burstObservatory).toBeUndefined();
}); });
it('switches from stale burstObservatory back to regular observatory when only leastPing remains', () => {
const t = tpl(
{ balancers: [{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }] },
{
observatory: { subjectSelector: ['stale-observatory-out'] },
burstObservatory: { subjectSelector: ['stale-burst-out'] },
},
);
syncObservatories(t);
expectObserver(t, 'observatory', ['lp-out']);
});
it('switches from stale observatory to burstObservatory when any burst strategy remains', () => {
const t = tpl(
{ balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }] },
{
observatory: { subjectSelector: ['stale-observatory-out'] },
burstObservatory: { subjectSelector: ['stale-burst-out'] },
},
);
syncObservatories(t);
expectObserver(t, 'burstObservatory', ['ll-out']);
});
it('creates burstObservatory with the HEAD httpMethod default for leastLoad', () => { it('creates burstObservatory with the HEAD httpMethod default for leastLoad', () => {
const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastLoad' } }] }); const t = tpl({ balancers: [{ tag: 'b1', selector: ['a'], strategy: { type: 'leastLoad' } }] });
syncObservatories(t); syncObservatories(t);
@@ -7,6 +7,7 @@ import {
type RawInboundRow, type RawInboundRow,
} from '@/lib/xray/inbound-form-adapter'; } from '@/lib/xray/inbound-form-adapter';
import { InboundDbFieldsSchema, InboundFormSchema } from '@/schemas/forms/inbound-form'; import { InboundDbFieldsSchema, InboundFormSchema } from '@/schemas/forms/inbound-form';
import { normalizeXhttpForWire } from '@/lib/xray/stream-wire-normalize';
import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt'; import { SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
// Round-trip: raw DB row → InboundFormValues → wire payload, asserting // Round-trip: raw DB row → InboundFormValues → wire payload, asserting
@@ -304,3 +305,51 @@ describe('subSortIndex', () => {
expect(InboundDbFieldsSchema.parse({}).subSortIndex).toBe(1); expect(InboundDbFieldsSchema.parse({}).subSortIndex).toBe(1);
}); });
}); });
describe('legacy xhttp session keys on edit (#5621)', () => {
const legacyXhttpRow: RawInboundRow = {
...vlessRow,
streamSettings: {
network: 'xhttp',
security: 'none',
xhttpSettings: {
path: '/xh',
mode: 'packet-up',
sessionPlacement: 'cookie',
sessionKey: 'x_session',
},
},
};
it('rawInboundToFormValues lifts sessionPlacement/sessionKey onto the renamed keys', () => {
const values = rawInboundToFormValues(legacyXhttpRow);
const xhttp = (values.streamSettings as unknown as Record<string, Record<string, unknown>>).xhttpSettings;
expect(xhttp.sessionIDPlacement).toBe('cookie');
expect(xhttp.sessionIDKey).toBe('x_session');
expect(xhttp.sessionPlacement).toBeUndefined();
expect(xhttp.sessionKey).toBeUndefined();
expect(xhttp.path).toBe('/xh');
expect(xhttp.xPaddingBytes).toBe('100-1000');
});
it('formValuesToWirePayload never emits the legacy key names', () => {
const values = rawInboundToFormValues(legacyXhttpRow);
const payload = formValuesToWirePayload(values);
const stream = JSON.parse(payload.streamSettings) as Record<string, Record<string, unknown>>;
expect(stream.xhttpSettings.sessionPlacement).toBeUndefined();
expect(stream.xhttpSettings.sessionKey).toBeUndefined();
expect(stream.xhttpSettings.sessionIDPlacement).toBe('cookie');
expect(stream.xhttpSettings.sessionIDKey).toBe('x_session');
});
it('normalizeXhttpForWire lifts stale legacy keys that bypassed the schema', () => {
const out = normalizeXhttpForWire(
{ sessionPlacement: 'header', sessionKey: 'x_raw' },
'inbound',
);
expect(out.sessionIDPlacement).toBe('header');
expect(out.sessionIDKey).toBe('x_raw');
expect(out.sessionPlacement).toBeUndefined();
expect(out.sessionKey).toBeUndefined();
});
});
@@ -104,6 +104,7 @@ describe('inbound security forms', () => {
scanRealityCandidates={async () => []} scanRealityCandidates={async () => []}
applyRealityScanResult={noop} applyRealityScanResult={noop}
randomizeShortIds={noop} randomizeShortIds={noop}
randomizeSpiderX={noop}
genRealityKeypair={noop} genRealityKeypair={noop}
clearRealityKeypair={noop} clearRealityKeypair={noop}
genMldsa65={noop} genMldsa65={noop}
@@ -0,0 +1,47 @@
import { describe, expect, it, vi } from 'vitest';
import { screen } from '@testing-library/react';
import ObservatorySettingsTab from '@/pages/xray/balancers/ObservatorySettingsTab';
import type { XraySettingsValue } from '@/hooks/useXraySetting';
import { renderWithProviders } from './test-utils';
function renderTab(templateSettings: XraySettingsValue) {
renderWithProviders(
<ObservatorySettingsTab
templateSettings={templateSettings}
mutate={vi.fn()}
/>,
);
}
describe('ObservatorySettingsTab', () => {
it('shows one burst settings panel and warns for legacy mixed observers', () => {
renderTab({
routing: {
balancers: [{ tag: 'll', selector: ['proxy-a'], strategy: { type: 'leastLoad' } }],
},
observatory: { subjectSelector: ['stale-regular'] },
burstObservatory: { subjectSelector: ['proxy-a'] },
} as unknown as XraySettingsValue);
expect(screen.getByText(/This config contains both Observatory and Burst Observatory/)).toBeTruthy();
expect(document.querySelector('.ant-segmented')).toBeFalsy();
expect(screen.getByText('Probe Destination')).toBeTruthy();
expect(screen.queryByText('Probe URL')).toBeFalsy();
});
it('shows regular observatory settings for mixed legacy configs that normalize back to leastPing only', () => {
renderTab({
routing: {
balancers: [{ tag: 'lp', selector: ['proxy-b'], strategy: { type: 'leastPing' } }],
},
observatory: { subjectSelector: ['proxy-b'] },
burstObservatory: { subjectSelector: ['stale-burst'] },
} as unknown as XraySettingsValue);
expect(screen.getByText(/This config contains both Observatory and Burst Observatory/)).toBeTruthy();
expect(document.querySelector('.ant-segmented')).toBeFalsy();
expect(screen.getByText('Probe URL')).toBeTruthy();
expect(screen.queryByText('Probe Destination')).toBeFalsy();
});
});
@@ -420,6 +420,54 @@ describe('outbound-form-adapter: round-trip', () => {
}); });
}); });
describe('outbound-form-adapter: targetStrategy', () => {
it('round-trips a top-level targetStrategy', () => {
const back = formValuesToWirePayload(rawOutboundToFormValues({
protocol: 'vless',
settings: { address: 's', port: 443, id: '11111111-2222-4333-8444-555555555555', flow: '', encryption: 'none' },
targetStrategy: 'ForceIPv6v4',
}));
expect(back.targetStrategy).toBe('ForceIPv6v4');
});
it('normalizes wire case to the canonical spelling (core matches case-insensitively)', () => {
const form = rawOutboundToFormValues({
protocol: 'freedom',
settings: {},
targetStrategy: 'useipv4v6',
});
expect(form.targetStrategy).toBe('UseIPv4v6');
});
it('omits targetStrategy when unset and drops unknown values', () => {
const unset = formValuesToWirePayload(rawOutboundToFormValues({
protocol: 'freedom',
settings: {},
}));
expect(unset).not.toHaveProperty('targetStrategy');
const invalid = formValuesToWirePayload(rawOutboundToFormValues({
protocol: 'freedom',
settings: {},
targetStrategy: 'UseIPv5',
}));
expect(invalid).not.toHaveProperty('targetStrategy');
});
it('freedom prefers settings.targetStrategy over domainStrategy and emits the legacy key', () => {
const form = rawOutboundToFormValues({
protocol: 'freedom',
settings: { targetStrategy: 'UseIPv6', domainStrategy: 'UseIPv4' },
});
if (form.protocol === 'freedom') {
expect(form.settings.domainStrategy).toBe('UseIPv6');
}
const back = formValuesToWirePayload(form);
expect(back.settings).toMatchObject({ domainStrategy: 'UseIPv6' });
expect(back.settings).not.toHaveProperty('targetStrategy');
});
});
describe('outbound-form-adapter: xhttp xmux toggle', () => { describe('outbound-form-adapter: xhttp xmux toggle', () => {
const xmuxWire = { const xmuxWire = {
protocol: 'vless', protocol: 'vless',
@@ -308,6 +308,52 @@ describe('parseHysteria2Link', () => {
expect(settings.packetSize).toBe('100-200'); expect(settings.packetSize).toBe('100-200');
}); });
it('coerces string quicParams numerics under fm to integers — #5783', () => {
const fm = encodeURIComponent(JSON.stringify({
quicParams: {
keepAlivePeriod: '10s',
maxIdleTimeout: '30',
initStreamReceiveWindow: 524288,
maxIncomingStreams: true,
brutalUp: '100 mbps',
},
}));
const link = `hysteria2://78e7795a209c4c099f896a816fc8448f@news.domain.org:8443?security=tls&sni=news.domain.org&fm=${fm}#hy2-quic`;
const out = parseHysteria2Link(link);
expect(out).not.toBeNull();
const finalmask = (out!.streamSettings as Record<string, unknown>).finalmask as Record<string, unknown>;
const quic = finalmask.quicParams as Record<string, unknown>;
expect(quic.keepAlivePeriod).toBe(10);
expect(quic.maxIdleTimeout).toBe(30);
expect(quic.initStreamReceiveWindow).toBe(524288);
expect('maxIncomingStreams' in quic).toBe(false);
expect(quic.brutalUp).toBe('100 mbps');
});
it('clamps quicParams to the ranges xray accepts and drops junk — #5783', () => {
const fm = encodeURIComponent(JSON.stringify({
quicParams: {
keepAlivePeriod: '1s',
maxIdleTimeout: '10m',
maxIncomingStreams: 4,
initStreamReceiveWindow: 'inf',
maxStreamReceiveWindow: -5,
initConnectionReceiveWindow: 1e30,
},
}));
const link = `hysteria2://78e7795a209c4c099f896a816fc8448f@news.domain.org:8443?security=tls&sni=news.domain.org&fm=${fm}#hy2-clamp`;
const out = parseHysteria2Link(link);
expect(out).not.toBeNull();
const finalmask = (out!.streamSettings as Record<string, unknown>).finalmask as Record<string, unknown>;
const quic = finalmask.quicParams as Record<string, unknown>;
expect(quic.keepAlivePeriod).toBe(2);
expect(quic.maxIdleTimeout).toBe(120);
expect(quic.maxIncomingStreams).toBe(8);
expect('initStreamReceiveWindow' in quic).toBe(false);
expect('maxStreamReceiveWindow' in quic).toBe(false);
expect('initConnectionReceiveWindow' in quic).toBe(false);
});
it('round-trips the realm tlsConfig under fm', () => { it('round-trips the realm tlsConfig under fm', () => {
const fm = encodeURIComponent(JSON.stringify({ const fm = encodeURIComponent(JSON.stringify({
udp: [{ udp: [{
@@ -83,6 +83,65 @@ describe('outbound deletion', () => {
expect(tt.routing!.rules![0].balancerTag).toBeUndefined(); expect(tt.routing!.rules![0].balancerTag).toBeUndefined();
}); });
it('cascade-removes the burst observer when deleting an outbound removes the last leastLoad balancer', () => {
const tt = tpl({
outbounds: [{ tag: 'll-out' }],
routing: {
rules: [],
balancers: [{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }],
},
burstObservatory: { subjectSelector: ['ll-out'] },
});
const impact = planOutboundDeletion(tt, 0);
expect(impact.balancers).toEqual([{ tag: 'll', reason: 'selectorEmptied' }]);
expect(impact.burst).toBe(true);
applyOutboundDeletion(tt, 0);
expect(tt.burstObservatory).toBeUndefined();
expect(tt.routing!.balancers).toEqual([]);
});
it('cascade-switches from burst to regular observer when only leastPing remains', () => {
const tt = tpl({
outbounds: [{ tag: 'lp-out' }, { tag: 'll-out' }],
routing: {
rules: [],
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
],
},
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
});
const impact = planOutboundDeletion(tt, 1);
expect(impact.balancers).toEqual([{ tag: 'll', reason: 'selectorEmptied' }]);
expect(impact.burst).toBe(true);
applyOutboundDeletion(tt, 1);
expect(tt.burstObservatory).toBeUndefined();
expect((tt.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['lp-out']);
expect(tt.routing!.balancers).toEqual([{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }]);
});
it('cascade-keeps burst observer when leastPing is removed but leastLoad remains', () => {
const tt = tpl({
outbounds: [{ tag: 'lp-out' }, { tag: 'll-out' }],
routing: {
rules: [],
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
],
},
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
});
const impact = planOutboundDeletion(tt, 0);
expect(impact.balancers).toEqual([{ tag: 'lp', reason: 'selectorEmptied' }]);
expect(impact.burst).toBe(false);
applyOutboundDeletion(tt, 0);
expect(tt.observatory).toBeUndefined();
expect((tt.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['ll-out']);
expect(tt.routing!.balancers).toEqual([{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }]);
});
it('clears a fallbackTag and a dialerProxy pointing at the deleted outbound', () => { it('clears a fallbackTag and a dialerProxy pointing at the deleted outbound', () => {
const tt = tpl({ const tt = tpl({
outbounds: [ outbounds: [
@@ -253,6 +312,68 @@ describe('balancer deletion', () => {
expect(tt.routing!.balancers).toEqual([]); expect(tt.routing!.balancers).toEqual([]);
}); });
it('reports and removes the burst observer when deleting the last leastLoad balancer', () => {
const tt = tpl({
routing: { rules: [], balancers: [{ tag: 'll', selector: ['a'], strategy: { type: 'leastLoad' } }] },
burstObservatory: { subjectSelector: ['a'] },
});
expect(planBalancerDeletion(tt, 0).burst).toBe(true);
applyBalancerDeletion(tt, 0);
expect(tt.burstObservatory).toBeUndefined();
expect(tt.routing!.balancers).toEqual([]);
});
it('reports and removes the burst observer when deleting the last fallback balancer', () => {
const tt = tpl({
routing: { rules: [], balancers: [{ tag: 'rf', selector: ['a'], fallbackTag: 'direct' }] },
burstObservatory: { subjectSelector: ['a'] },
});
expect(planBalancerDeletion(tt, 0).burst).toBe(true);
applyBalancerDeletion(tt, 0);
expect(tt.burstObservatory).toBeUndefined();
expect(tt.routing!.balancers).toEqual([]);
});
it('switches from burst to regular observer when the deleted balancer was the last burst-required one', () => {
const tt = tpl({
routing: {
rules: [],
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
],
},
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
});
const impact = planBalancerDeletion(tt, 1);
expect(impact.burst).toBe(true);
expect(impact.observatory).toBe(false);
applyBalancerDeletion(tt, 1);
expect(tt.burstObservatory).toBeUndefined();
expect((tt.observatory as { subjectSelector: string[] }).subjectSelector).toEqual(['lp-out']);
expect(tt.routing!.balancers).toEqual([{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } }]);
});
it('keeps burst observer when deleting leastPing but a burst-required balancer remains', () => {
const tt = tpl({
routing: {
rules: [],
balancers: [
{ tag: 'lp', selector: ['lp-out'], strategy: { type: 'leastPing' } },
{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } },
],
},
burstObservatory: { subjectSelector: ['lp-out', 'll-out'] },
});
const impact = planBalancerDeletion(tt, 0);
expect(impact.burst).toBe(false);
expect(impact.observatory).toBe(false);
applyBalancerDeletion(tt, 0);
expect(tt.observatory).toBeUndefined();
expect((tt.burstObservatory as { subjectSelector: string[] }).subjectSelector).toEqual(['ll-out']);
expect(tt.routing!.balancers).toEqual([{ tag: 'll', selector: ['ll-out'], strategy: { type: 'leastLoad' } }]);
});
it('does not report rules when the deleted balancer is unreferenced', () => { it('does not report rules when the deleted balancer is unreferenced', () => {
const tt = tpl({ const tt = tpl({
routing: { rules: [{ type: 'field', inboundTag: ['in'], outboundTag: 'direct' }], balancers: [{ tag: 'pool', selector: ['a'] }] }, routing: { rules: [{ type: 'field', inboundTag: ['in'], outboundTag: 'direct' }], balancers: [{ tag: 'pool', selector: ['a'] }] },
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest';
import { AllSettingSchema } from '@/schemas/setting';
describe('subUpdates range', () => {
it('accepts values the backend allows (gte=0, lte=525600)', () => {
for (const v of [0, 12, 168, 720, 525600]) {
const r = AllSettingSchema.safeParse({ subUpdates: v });
expect(r.success, `subUpdates=${v} should be valid`).toBe(true);
}
});
it('rejects values outside the backend range', () => {
for (const v of [-1, 525601, 1.5]) {
expect(AllSettingSchema.safeParse({ subUpdates: v }).success, `subUpdates=${v} should be invalid`).toBe(false);
}
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { deriveSpiderX } from '@/lib/xray/spider-x';
// Cross-language vectors shared with TestDeriveSpiderXMatchesFrontendVectors
// in internal/sub/service_sharelink_test.go: subscription links come from Go,
// panel links from this module, and the two must agree byte-for-byte.
describe('deriveSpiderX', () => {
it('matches the Go deriveSpiderX vectors', () => {
expect(deriveSpiderX('/seed', 'subAlice')).toBe('/c252fbc3ecd3e3c');
expect(deriveSpiderX('/', '')).toBe('/d08ed99bd9afc60');
});
it('is stable per client, distinct across clients, and rotates with the seed', () => {
expect(deriveSpiderX('/seed', 'subAlice')).toBe(deriveSpiderX('/seed', 'subAlice'));
expect(deriveSpiderX('/seed', 'subAlice')).not.toBe(deriveSpiderX('/seed', 'subBob'));
expect(deriveSpiderX('/seedA', 'subAlice')).not.toBe(deriveSpiderX('/seedB', 'subAlice'));
});
it('returns empty when there is nothing to derive from', () => {
expect(deriveSpiderX('', '')).toBe('');
});
it('emits a /-prefixed 15-hex-char path', () => {
expect(deriveSpiderX('/some-seed', 'client@example.com')).toMatch(/^\/[0-9a-f]{15}$/);
});
});
@@ -10,6 +10,7 @@ import {
validateRealityTarget, validateRealityTarget,
} from '@/lib/xray/stream-wire-normalize'; } from '@/lib/xray/stream-wire-normalize';
import { InboundFormSchema } from '@/schemas/forms/inbound-form'; import { InboundFormSchema } from '@/schemas/forms/inbound-form';
import { HappyEyeballsSchema } from '@/schemas/protocols/stream/sockopt';
import type { InboundFormValues } from '@/schemas/forms/inbound-form'; import type { InboundFormValues } from '@/schemas/forms/inbound-form';
import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp'; import { XHttpXmuxSchema } from '@/schemas/protocols/stream/xhttp';
@@ -204,6 +205,22 @@ describe('normalizeSockoptForWire', () => {
}); });
expect(out?.domainStrategy).toBe('UseIP'); expect(out?.domainStrategy).toBe('UseIP');
}); });
it('keeps a freshly toggled happyEyeballs (schema defaults) across the wire round trip', () => {
const out = normalizeSockoptForWire({
happyEyeballs: HappyEyeballsSchema.parse({}),
});
expect(out?.happyEyeballs).toEqual({ tryDelayMs: 250 });
});
it('keeps an explicit tryDelayMs of 0 so it cannot rehydrate as the 250 default', () => {
const out = normalizeSockoptForWire({
happyEyeballs: { tryDelayMs: 0, prioritizeIPv6: true, interleave: 1, maxConcurrentTry: 4 },
});
expect(out?.happyEyeballs).toEqual({ tryDelayMs: 0, prioritizeIPv6: true });
});
}); });
describe('normalizeStreamSettingsForWire reality', () => { describe('normalizeStreamSettingsForWire reality', () => {
@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest';
import { vlessEncryptionAuthKind } from '@/lib/xray/vless-encryption';
const x25519Key = 'kO9pIKKPtoUCzo3ZWfWfp0lQoWCyJC1TqL8oz1hpsFM';
const mlkem768Key = 'A'.repeat(1590);
describe('vlessEncryptionAuthKind', () => {
const cases: { name: string; encryption: string; want: ReturnType<typeof vlessEncryptionAuthKind> }[] = [
{ name: 'empty string', encryption: '', want: null },
{ name: 'none', encryption: 'none', want: null },
{ name: 'only dots', encryption: '...', want: null },
{ name: 'x25519 native', encryption: `mlkem768x25519plus.native.600s.${x25519Key}`, want: 'x25519' },
{ name: 'x25519 xorpub', encryption: `mlkem768x25519plus.xorpub.600s.${x25519Key}`, want: 'x25519_xorpub' },
{ name: 'x25519 random', encryption: `mlkem768x25519plus.random.600s.${x25519Key}`, want: 'x25519_random' },
{ name: 'mlkem768 native', encryption: `mlkem768x25519plus.native.600s.${mlkem768Key}`, want: 'mlkem768' },
{ name: 'mlkem768 xorpub', encryption: `mlkem768x25519plus.xorpub.600s.${mlkem768Key}`, want: 'mlkem768_xorpub' },
{ name: 'mlkem768 random', encryption: `mlkem768x25519plus.random.600s.${mlkem768Key}`, want: 'mlkem768_random' },
{ name: 'two-segment value treated as native', encryption: `mlkem768x25519plus.${x25519Key}`, want: 'x25519' },
];
for (const c of cases) {
it(c.name, () => {
expect(vlessEncryptionAuthKind(c.encryption)).toBe(c.want);
});
}
});
@@ -52,4 +52,41 @@ describe('buildWireguardClientConfig', () => {
const cfg = buildWireguardClientConfig({ ...client, preSharedKey: undefined }, inbound, 'example.com', ''); const cfg = buildWireguardClientConfig({ ...client, preSharedKey: undefined }, inbound, 'example.com', '');
expect(cfg).not.toContain('PresharedKey'); expect(cfg).not.toContain('PresharedKey');
}); });
it('uses the hosting node address as the endpoint host for node-managed inbounds', () => {
const cfg = buildWireguardClientConfig(client, { ...inbound, nodeAddress: 'node.example.net' }, 'master.example.com', '');
expect(cfg).toContain('Endpoint = node.example.net:51820');
expect(cfg).not.toContain('master.example.com');
});
it('falls back to the panel host when the node address is blank', () => {
const cfg = buildWireguardClientConfig(client, { ...inbound, nodeAddress: ' ' }, 'master.example.com', '');
expect(cfg).toContain('Endpoint = master.example.com:51820');
});
it('honors the custom share-address strategy over the node address', () => {
const cfg = buildWireguardClientConfig(
client,
{ ...inbound, nodeAddress: 'node.example.net', shareAddrStrategy: 'custom', shareAddr: 'vpn.example.com' },
'master.example.com',
'',
);
expect(cfg).toContain('Endpoint = vpn.example.com:51820');
});
it('honors the listen share-address strategy over the node address', () => {
const cfg = buildWireguardClientConfig(
client,
{ ...inbound, nodeAddress: 'node.example.net', shareAddrStrategy: 'listen', listen: '198.51.100.7' },
'master.example.com',
'',
);
expect(cfg).toContain('Endpoint = 198.51.100.7:51820');
});
it('keeps a panel hostname that fails share-host normalization instead of emitting an empty endpoint', () => {
const cfg = buildWireguardClientConfig(client, { ...inbound, listen: '0.0.0.0' }, 'wg_gw.corp.lan', '');
expect(cfg).toContain('Endpoint = wg_gw.corp.lan:51820');
expect(cfg).not.toContain('Endpoint = :51820');
});
}); });
+3 -3
View File
@@ -17,7 +17,7 @@ require (
github.com/nicksnyder/go-i18n/v2 v2.6.1 github.com/nicksnyder/go-i18n/v2 v2.6.1
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/robfig/cron/v3 v3.0.1 github.com/robfig/cron/v3 v3.0.1
github.com/shirou/gopsutil/v4 v4.26.5 github.com/shirou/gopsutil/v4 v4.26.6
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/valyala/fasthttp v1.72.0 github.com/valyala/fasthttp v1.72.0
github.com/xlzd/gotp v0.1.0 github.com/xlzd/gotp v0.1.0
@@ -26,7 +26,7 @@ require (
golang.org/x/crypto v0.53.0 golang.org/x/crypto v0.53.0
golang.org/x/sys v0.46.0 golang.org/x/sys v0.46.0
golang.org/x/text v0.38.0 golang.org/x/text v0.38.0
google.golang.org/grpc v1.81.1 google.golang.org/grpc v1.82.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/driver/postgres v1.6.0 gorm.io/driver/postgres v1.6.0
gorm.io/driver/sqlite v1.6.0 gorm.io/driver/sqlite v1.6.0
@@ -63,7 +63,7 @@ require (
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/juju/ratelimit v1.0.2 // indirect github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.18.6 github.com/klauspost/compress v1.19.0
github.com/klauspost/cpuid/v2 v2.3.0 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
+6 -6
View File
@@ -115,8 +115,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI= github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -178,8 +178,8 @@ github.com/sagernet/sing v0.8.10 h1:V5VZffy8rm4dtBVKIpKa8vibRR2SiJprtu/10DFUalU=
github.com/sagernet/sing v0.8.10/go.mod h1:olXxWQNqRW/l2Q6JI3b2Qmz8iQnIFlOeeH8bx6JhgUA= github.com/sagernet/sing v0.8.10/go.mod h1:olXxWQNqRW/l2Q6JI3b2Qmz8iQnIFlOeeH8bx6JhgUA=
github.com/sagernet/sing-shadowsocks v0.2.9 h1:Paep5zCszRKsEn8587O0MnhFWKJwDW1Y4zOYYlIxMkM= github.com/sagernet/sing-shadowsocks v0.2.9 h1:Paep5zCszRKsEn8587O0MnhFWKJwDW1Y4zOYYlIxMkM=
github.com/sagernet/sing-shadowsocks v0.2.9/go.mod h1:TE/Z6401Pi8tgr0nBZcM/xawAI6u3F6TTbz4nH/qw+8= github.com/sagernet/sing-shadowsocks v0.2.9/go.mod h1:TE/Z6401Pi8tgr0nBZcM/xawAI6u3F6TTbz4nH/qw+8=
github.com/shirou/gopsutil/v4 v4.26.5 h1:RPcBXkpz7kOj9PqGFQOlBPZHsyaPvPVQc098y9RmCNM= github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
github.com/shirou/gopsutil/v4 v4.26.5/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M= github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -281,8 +281,8 @@ gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d h1:mpAgMyM9vQHxycBlDq50y1VHpfSfVwzXvrQKtYbXuUY= google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d h1:mpAgMyM9vQHxycBlDq50y1VHpfSfVwzXvrQKtYbXuUY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/genproto/googleapis/rpc v0.0.0-20260622175928-b703f567277d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+142 -27
View File
@@ -101,17 +101,17 @@ install_base() {
apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl apt-get update && apt-get install -y -q cron curl tar tzdata socat ca-certificates openssl
;; ;;
fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol) fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
;; ;;
centos) centos)
if [[ "${VERSION_ID}" =~ ^7 ]]; then if [[ "${VERSION_ID}" =~ ^7 ]]; then
yum -y update && yum install -y cronie curl tar tzdata socat ca-certificates openssl yum makecache -y && yum install -y cronie curl tar tzdata socat ca-certificates openssl
else else
dnf -y update && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl dnf makecache -y && dnf install -y -q cronie curl tar tzdata socat ca-certificates openssl
fi fi
;; ;;
arch | manjaro | parch) arch | manjaro | parch)
pacman -Syu && pacman -Syu --noconfirm cronie curl tar tzdata socat ca-certificates openssl pacman -Sy --noconfirm cronie curl tar tzdata socat ca-certificates openssl
;; ;;
opensuse-tumbleweed | opensuse-leap) opensuse-tumbleweed | opensuse-leap)
zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl zypper refresh && zypper -q install -y cron curl tar timezone socat ca-certificates openssl
@@ -180,6 +180,36 @@ write_install_result() {
echo -e "${green}Install result written to ${result_file} (mode 600).${plain}" echo -e "${green}Install result written to ${result_file} (mode 600).${plain}"
} }
# RHEL-family initdb writes pg_hba.conf host rules with ident auth, which
# compares the OS username against the Postgres role and always rejects the
# randomly generated panel role over TCP (#5806). Prepend password-auth rules
# scoped to the panel database; first match wins, and md5 also accepts
# scram-sha-256-stored verifiers, so this works on every supported distro.
pg_ensure_hba_password_auth() {
local pg_db="$1"
local hba_file
hba_file=$(sudo -u postgres psql -tAc 'SHOW hba_file' 2> /dev/null | tr -d '[:space:]')
[[ -n "${hba_file}" && -f "${hba_file}" ]] || return 0
grep -Eq "^host[[:space:]]+${pg_db}[[:space:]]" "${hba_file}" && return 0
local tmp
tmp=$(mktemp) || return 1
{
echo "# Added by 3x-ui: allow password logins for the panel database."
echo "host ${pg_db} all 127.0.0.1/32 md5"
echo "host ${pg_db} all ::1/128 md5"
cat "${hba_file}"
} > "${tmp}" || {
rm -f "${tmp}"
return 1
}
cat "${tmp}" > "${hba_file}" || {
rm -f "${tmp}"
return 1
}
rm -f "${tmp}"
sudo -u postgres psql -tAc 'SELECT pg_reload_conf()' > /dev/null 2>&1 || true
}
install_postgres_local() { install_postgres_local() {
local pg_user pg_pass local pg_user pg_pass
pg_pass=$(gen_random_string 24) pg_pass=$(gen_random_string 24)
@@ -204,7 +234,7 @@ install_postgres_local() {
[[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1 [[ -d /var/lib/pgsql/data && -f /var/lib/pgsql/data/PG_VERSION ]] || postgresql-setup --initdb >&2 || return 1
;; ;;
arch | manjaro | parch) arch | manjaro | parch)
pacman -Syu --noconfirm postgresql >&2 || return 1 pacman -Sy --noconfirm postgresql >&2 || return 1
if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then if [[ ! -f /var/lib/postgres/data/PG_VERSION ]]; then
sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1 sudo -u postgres initdb -D /var/lib/postgres/data >&2 || return 1
fi fi
@@ -263,6 +293,9 @@ install_postgres_local() {
sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1 sudo -u postgres psql -c "ALTER USER \"${pg_user}\" WITH PASSWORD '${pg_pass}';" >&2 || return 1
pg_ensure_hba_password_auth "${pg_db}" \
|| echo -e "${yellow}Warning: could not update pg_hba.conf; PostgreSQL may reject the panel's TCP login (ident auth).${plain}" >&2
local pg_pass_enc 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') pg_pass_enc=$(printf '%s' "${pg_pass}" | sed -e 's/%/%25/g' -e 's/:/%3A/g' -e 's/@/%40/g' -e 's|/|%2F|g' -e 's/?/%3F/g' -e 's/#/%23/g')
@@ -373,7 +406,7 @@ setup_ssl_certificate() {
fi fi
# Install certificate # Install certificate
~/.acme.sh/acme.sh --installcert -d ${domain} \ ~/.acme.sh/acme.sh --installcert --force -d ${domain} \
--key-file /root/cert/${domain}/privkey.pem \ --key-file /root/cert/${domain}/privkey.pem \
--fullchain-file /root/cert/${domain}/fullchain.pem \ --fullchain-file /root/cert/${domain}/fullchain.pem \
--reloadcmd "systemctl restart x-ui" > /dev/null 2>&1 --reloadcmd "systemctl restart x-ui" > /dev/null 2>&1
@@ -517,7 +550,7 @@ setup_ip_certificate() {
# Install certificate # Install certificate
# Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails, # 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. # but the cert files are still installed. We check for files instead of exit code.
~/.acme.sh/acme.sh --installcert -d ${ipv4} \ ~/.acme.sh/acme.sh --installcert --force -d ${ipv4} \
--key-file "${certDir}/privkey.pem" \ --key-file "${certDir}/privkey.pem" \
--fullchain-file "${certDir}/fullchain.pem" \ --fullchain-file "${certDir}/fullchain.pem" \
--reloadcmd "${reloadCmd}" 2>&1 || true --reloadcmd "${reloadCmd}" 2>&1 || true
@@ -646,7 +679,9 @@ ssl_cert_issue() {
# get the port number for the standalone server # get the port number for the standalone server
local WebPort=80 local WebPort=80
prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT prompt_or_default WebPort "Please choose which port to use (default is 80): " "80" XUI_ACME_HTTP_PORT
if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then if [[ -z ${WebPort} ]]; then
WebPort=80
elif [[ ! ${WebPort} =~ ^[1-9][0-9]*$ || ${WebPort} -gt 65535 ]]; then
echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}" echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
WebPort=80 WebPort=80
fi fi
@@ -705,7 +740,7 @@ ssl_cert_issue() {
# install the certificate # install the certificate
local installOutput="" local installOutput=""
installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \ installOutput=$(~/.acme.sh/acme.sh --installcert --force -d ${domain} \
--key-file /root/cert/${domain}/privkey.pem \ --key-file /root/cert/${domain}/privkey.pem \
--fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1) --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
local installRc=$? local installRc=$?
@@ -1326,6 +1361,40 @@ setup_fail2ban() {
return 0 return 0
} }
# Lands a systemd unit file at ${xui_service}/x-ui.service via a temp file +
# atomic mv, so a failed cp/curl or an interrupted mv never leaves a
# truncated unit file at the live path -- systemd would then fail to parse
# it on the next daemon-reload/start. Same pattern already used for
# /usr/bin/x-ui elsewhere in this script. source_is_url picks cp (from a
# file already extracted from the release tarball) vs curl (GitHub fallback).
_install_xui_service_unit() {
local source="$1"
local source_is_url="$2"
local dest="${xui_service}/x-ui.service"
local temp_file="${dest}.tmp.$$"
rm -f "$temp_file"
if [[ "$source_is_url" == "true" ]]; then
curl -fLRo "$temp_file" "$source" > /dev/null 2>&1
else
cp -f "$source" "$temp_file" > /dev/null 2>&1
fi
if [[ $? -ne 0 ]]; then
rm -f "$temp_file"
return 1
fi
if [[ ! -s "$temp_file" ]]; then
rm -f "$temp_file"
return 1
fi
mv -f "$temp_file" "$dest"
if [[ $? -ne 0 ]]; then
rm -f "$temp_file"
return 1
fi
return 0
}
install_x-ui() { install_x-ui() {
cd ${xui_folder%/x-ui}/ cd ${xui_folder%/x-ui}/
@@ -1342,6 +1411,11 @@ install_x-ui() {
echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}" echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
exit 1 exit 1
fi fi
if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
rm ${xui_folder}-linux-$(arch).tar.gz -f
echo -e "${red}Downloaded x-ui release archive is empty${plain}"
exit 1
fi
else else
tag_version=$1 tag_version=$1
# The rolling dev channel ships under a fixed, non-semver tag that is # The rolling dev channel ships under a fixed, non-semver tag that is
@@ -1367,12 +1441,25 @@ install_x-ui() {
echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}" echo -e "${red}Download x-ui ${tag_version} failed, please check if the version exists ${plain}"
exit 1 exit 1
fi fi
if [[ ! -s ${xui_folder}-linux-$(arch).tar.gz ]]; then
rm ${xui_folder}-linux-$(arch).tar.gz -f
echo -e "${red}Downloaded x-ui release archive is empty${plain}"
exit 1
fi fi
curl -fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh fi
local xui_script_temp="/usr/bin/x-ui-temp.$$"
rm -f "${xui_script_temp}"
curl -fLRo "${xui_script_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
if [[ $? -ne 0 ]]; then if [[ $? -ne 0 ]]; then
rm -f "${xui_script_temp}"
echo -e "${red}Failed to download x-ui.sh${plain}" echo -e "${red}Failed to download x-ui.sh${plain}"
exit 1 exit 1
fi fi
if [[ ! -s "${xui_script_temp}" ]]; then
rm -f "${xui_script_temp}"
echo -e "${red}Downloaded x-ui.sh is empty${plain}"
exit 1
fi
# Stop x-ui service and remove old resources # Stop x-ui service and remove old resources
if [[ -e ${xui_folder}/ ]]; then if [[ -e ${xui_folder}/ ]]; then
@@ -1391,16 +1478,29 @@ install_x-ui() {
# Extract resources and set permissions # Extract resources and set permissions
tar zxvf x-ui-linux-$(arch).tar.gz tar zxvf x-ui-linux-$(arch).tar.gz
if [[ $? -ne 0 ]]; then
rm x-ui-linux-$(arch).tar.gz -f
rm -f "${xui_script_temp}"
echo -e "${red}Failed to extract the x-ui release archive -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
exit 1
fi
rm x-ui-linux-$(arch).tar.gz -f rm x-ui-linux-$(arch).tar.gz -f
cd x-ui cd x-ui
if [[ $? -ne 0 || ! -s x-ui ]]; then
rm -f "${xui_script_temp}"
echo -e "${red}Extracted x-ui archive is missing the x-ui binary -- the previous installation has already been removed, so the panel will not start until this is fixed; try running the installer again${plain}"
exit 1
fi
chmod +x x-ui chmod +x x-ui
chmod +x x-ui.sh chmod +x x-ui.sh
# Check the system's architecture and rename the file accordingly # Check the system's architecture and rename the file accordingly.
# The panel binary maps GOARCH=arm to "arm32" (internal/xray/process.go),
# so the Xray binary must be named xray-linux-arm32; mtg keeps plain "arm".
if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
mv bin/xray-linux-$(arch) bin/xray-linux-arm mv bin/xray-linux-$(arch) bin/xray-linux-arm32
chmod +x bin/xray-linux-arm chmod +x bin/xray-linux-arm32
if [[ -f bin/mtg-linux-$(arch) ]]; then if [[ -f bin/mtg-linux-$(arch) ]]; then
mv bin/mtg-linux-$(arch) bin/mtg-linux-arm mv bin/mtg-linux-$(arch) bin/mtg-linux-arm
chmod +x bin/mtg-linux-arm chmod +x bin/mtg-linux-arm
@@ -1414,7 +1514,12 @@ install_x-ui() {
fi fi
# Update x-ui cli and se set permission # Update x-ui cli and se set permission
mv -f /usr/bin/x-ui-temp /usr/bin/x-ui mv -f "${xui_script_temp}" /usr/bin/x-ui
if [[ $? -ne 0 ]]; then
rm -f "${xui_script_temp}"
echo -e "${red}Failed to install x-ui.sh${plain}"
exit 1
fi
chmod +x /usr/bin/x-ui chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui mkdir -p /var/log/x-ui
config_after_install config_after_install
@@ -1434,11 +1539,25 @@ install_x-ui() {
fi fi
if [[ $release == "alpine" ]]; then if [[ $release == "alpine" ]]; then
curl -fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc xui_rc_temp="/etc/init.d/x-ui.tmp.$$"
rm -f "${xui_rc_temp}"
curl -fLRo "${xui_rc_temp}" https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
if [[ $? -ne 0 ]]; then if [[ $? -ne 0 ]]; then
rm -f "${xui_rc_temp}"
echo -e "${red}Failed to download x-ui.rc${plain}" echo -e "${red}Failed to download x-ui.rc${plain}"
exit 1 exit 1
fi fi
if [[ ! -s "${xui_rc_temp}" ]]; then
rm -f "${xui_rc_temp}"
echo -e "${red}Downloaded x-ui.rc is empty${plain}"
exit 1
fi
mv -f "${xui_rc_temp}" /etc/init.d/x-ui
if [[ $? -ne 0 ]]; then
rm -f "${xui_rc_temp}"
echo -e "${red}Failed to install x-ui.rc${plain}"
exit 1
fi
chmod +x /etc/init.d/x-ui chmod +x /etc/init.d/x-ui
rc-update add x-ui rc-update add x-ui
rc-service x-ui start rc-service x-ui start
@@ -1448,8 +1567,7 @@ install_x-ui() {
if [ -f "x-ui.service" ]; then if [ -f "x-ui.service" ]; then
echo -e "${green}Found x-ui.service in extracted files, installing...${plain}" echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
cp -f x-ui.service ${xui_service}/ > /dev/null 2>&1 if _install_xui_service_unit "x-ui.service" "false"; then
if [[ $? -eq 0 ]]; then
service_installed=true service_installed=true
fi fi
fi fi
@@ -1459,8 +1577,7 @@ install_x-ui() {
ubuntu | debian | armbian) ubuntu | debian | armbian)
if [ -f "x-ui.service.debian" ]; then if [ -f "x-ui.service.debian" ]; then
echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}" echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
cp -f x-ui.service.debian ${xui_service}/x-ui.service > /dev/null 2>&1 if _install_xui_service_unit "x-ui.service.debian" "false"; then
if [[ $? -eq 0 ]]; then
service_installed=true service_installed=true
fi fi
fi fi
@@ -1468,8 +1585,7 @@ install_x-ui() {
arch | manjaro | parch) arch | manjaro | parch)
if [ -f "x-ui.service.arch" ]; then if [ -f "x-ui.service.arch" ]; then
echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}" echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
cp -f x-ui.service.arch ${xui_service}/x-ui.service > /dev/null 2>&1 if _install_xui_service_unit "x-ui.service.arch" "false"; then
if [[ $? -eq 0 ]]; then
service_installed=true service_installed=true
fi fi
fi fi
@@ -1477,8 +1593,7 @@ install_x-ui() {
*) *)
if [ -f "x-ui.service.rhel" ]; then if [ -f "x-ui.service.rhel" ]; then
echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}" echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
cp -f x-ui.service.rhel ${xui_service}/x-ui.service > /dev/null 2>&1 if _install_xui_service_unit "x-ui.service.rhel" "false"; then
if [[ $? -eq 0 ]]; then
service_installed=true service_installed=true
fi fi
fi fi
@@ -1491,17 +1606,17 @@ install_x-ui() {
echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}" echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
case "${release}" in case "${release}" in
ubuntu | debian | armbian) ubuntu | debian | armbian)
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian > /dev/null 2>&1 service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian"
;; ;;
arch | manjaro | parch) arch | manjaro | parch)
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch > /dev/null 2>&1 service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch"
;; ;;
*) *)
curl -fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel > /dev/null 2>&1 service_unit_url="https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel"
;; ;;
esac esac
if [[ $? -ne 0 ]]; then if ! _install_xui_service_unit "$service_unit_url" "true"; then
echo -e "${red}Failed to install x-ui.service from GitHub${plain}" echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
exit 1 exit 1
fi fi
+8
View File
@@ -169,6 +169,14 @@ func GetDBPath() string {
return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName()) return fmt.Sprintf("%s/%s.db", GetDBFolderPath(), GetName())
} }
// GetUpdateStatusFilePath returns the path to the panel self-update status
// file update.sh writes on completion. It lives beside the database, outside
// XUI_MAIN_FOLDER, so it survives an update regardless of what happens to
// that folder.
func GetUpdateStatusFilePath() string {
return filepath.Join(GetDBFolderPath(), "update-status.json")
}
// GetDBKind returns the configured database backend: "sqlite" (default) or "postgres". // GetDBKind returns the configured database backend: "sqlite" (default) or "postgres".
func GetDBKind() string { func GetDBKind() string {
v := strings.ToLower(strings.TrimSpace(os.Getenv("XUI_DB_TYPE"))) v := strings.ToLower(strings.TrimSpace(os.Getenv("XUI_DB_TYPE")))
+193 -1
View File
@@ -83,6 +83,9 @@ func initModels() error {
&model.OutboundSubscription{}, &model.OutboundSubscription{},
} }
for _, mdl := range models { for _, mdl := range models {
if IsPostgres() && postgresModelSettled(mdl) {
continue
}
if err := db.AutoMigrate(mdl); err != nil { if err := db.AutoMigrate(mdl); err != nil {
if isIgnorableDuplicateColumnErr(err, mdl) { if isIgnorableDuplicateColumnErr(err, mdl) {
log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err) log.Printf("Ignoring duplicate column during auto migration for %T: %v", mdl, err)
@@ -110,6 +113,15 @@ func initModels() error {
if err := normalizeInboundSubSortIndex(); err != nil { if err := normalizeInboundSubSortIndex(); err != nil {
return err return err
} }
if err := repairOverflowedTrafficCounters(); err != nil {
return err
}
if err := dedupeInboundSettingsClients(); err != nil {
return err
}
if err := migrateLegacySocksInboundsToMixed(); err != nil {
return err
}
if IsPostgres() { if IsPostgres() {
if err := resyncPostgresSequences(db, models); err != nil { if err := resyncPostgresSequences(db, models); err != nil {
log.Printf("Error resyncing postgres sequences: %v", err) log.Printf("Error resyncing postgres sequences: %v", err)
@@ -119,6 +131,30 @@ func initModels() error {
return nil return nil
} }
// postgresModelSettled skips AutoMigrate when table, columns, and indexes all exist:
// its catalog-filtered column probe misdetects on some setups and re-ADDs columns forever (#5665).
func postgresModelSettled(mdl any) bool {
migrator := db.Migrator()
if !migrator.HasTable(mdl) {
return false
}
stmt := &gorm.Statement{DB: db}
if err := stmt.Parse(mdl); err != nil || stmt.Schema == nil {
return false
}
for _, dbName := range stmt.Schema.DBNames {
if !migrator.HasColumn(mdl, dbName) {
return false
}
}
for _, idx := range stmt.Schema.ParseIndexes() {
if !migrator.HasIndex(mdl, idx.Name) {
return false
}
}
return true
}
func dropLegacyForeignKeys() error { func dropLegacyForeignKeys() error {
if !IsPostgres() { if !IsPostgres() {
return nil return nil
@@ -456,6 +492,23 @@ func pruneOrphanedClientInbounds() error {
return nil return nil
} }
// migrateLegacySocksInboundsToMixed renames legacy socks inbounds to mixed.
// The protocol enum dropped socks in favor of mixed (identical settings shape,
// same behavior plus HTTP on the shared port), so rows predating the rename
// fail model validation — most visibly when pushed to a node, where one legacy
// inbound stalled the entire node's config and traffic sync (#5685).
func migrateLegacySocksInboundsToMixed() error {
res := db.Exec("UPDATE inbounds SET protocol = 'mixed' WHERE protocol = 'socks'")
if res.Error != nil {
log.Printf("Error migrating legacy socks inbounds to mixed: %v", res.Error)
return res.Error
}
if res.RowsAffected > 0 {
log.Printf("Migrated %d legacy socks inbound(s) to mixed", res.RowsAffected)
}
return nil
}
// normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based // normalizeInboundSubSortIndex lifts sub_sort_index values below the 1-based
// minimum (rows written by builds that defaulted the column to 0, or by nodes // minimum (rows written by builds that defaulted the column to 0, or by nodes
// predating the field) so they cannot sort ahead of explicitly ranked inbounds. // predating the field) so they cannot sort ahead of explicitly ranked inbounds.
@@ -471,6 +524,111 @@ func normalizeInboundSubSortIndex() error {
return nil return nil
} }
// repairOverflowedTrafficCounters heals traffic counters that historic
// compounding bugs pushed past int64: on SQLite an overflowing INTEGER is
// silently promoted to REAL, after which the column no longer scans into the
// Go int64 field and every reader of the table fails (#5762). REAL cells are
// cast back to INTEGER (SQLite caps the cast at math.MaxInt64), then values
// are clamped into [0, TrafficMax] on both backends so the next delta cannot
// overflow again.
func repairOverflowedTrafficCounters() error {
targets := []struct {
table string
columns []string
}{
{"client_traffics", []string{"up", "down"}},
{"inbounds", []string{"up", "down"}},
{"outbound_traffics", []string{"up", "down", "total"}},
{"node_client_traffics", []string{"up", "down"}},
}
for _, target := range targets {
for _, col := range target.columns {
statements := []string{
fmt.Sprintf("UPDATE %s SET %s = %d WHERE %s > %d", target.table, col, TrafficMax, col, TrafficMax),
fmt.Sprintf("UPDATE %s SET %s = 0 WHERE %s < 0", target.table, col, col),
}
if !IsPostgres() {
statements = append([]string{
fmt.Sprintf("UPDATE %s SET %s = CAST(%s AS INTEGER) WHERE typeof(%s) = 'real'", target.table, col, col, col),
}, statements...)
}
var repaired int64
for _, statement := range statements {
res := db.Exec(statement)
if res.Error != nil {
log.Printf("Error repairing %s.%s: %v", target.table, col, res.Error)
return res.Error
}
repaired += res.RowsAffected
}
if repaired > 0 {
log.Printf("Repaired %d overflowed %s.%s value(s)", repaired, target.table, col)
}
}
}
return nil
}
// dedupeInboundSettingsClients collapses duplicate same-email entries inside
// every inbound's settings.clients array, keeping the first occurrence.
// Retried or raced multi-node client adds on older builds appended the same
// client several times (#5770), which the client lists then rendered as
// phantom duplicates. Runs on every start (idempotent, writes only changed
// rows) because a restored backup or a not-yet-upgraded node's snapshot can
// reintroduce duplicates.
func dedupeInboundSettingsClients() error {
var inbounds []model.Inbound
if err := db.Find(&inbounds).Error; err != nil {
return err
}
repaired := int64(0)
for _, inbound := range inbounds {
if strings.TrimSpace(inbound.Settings) == "" {
continue
}
var settings map[string]any
if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
continue
}
clients, _ := settings["clients"].([]any)
if len(clients) < 2 {
continue
}
seen := make(map[string]struct{}, len(clients))
kept := make([]any, 0, len(clients))
for _, c := range clients {
if cm, ok := c.(map[string]any); ok {
if email, _ := cm["email"].(string); email != "" {
key := strings.ToLower(email)
if _, dup := seen[key]; dup {
continue
}
seen[key] = struct{}{}
}
}
kept = append(kept, c)
}
if len(kept) == len(clients) {
continue
}
settings["clients"] = kept
newSettings, err := json.MarshalIndent(settings, "", " ")
if err != nil {
log.Printf("dedupeInboundSettingsClients: skip inbound %d (marshal failed): %v", inbound.Id, err)
continue
}
if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).
Update("settings", string(newSettings)).Error; err != nil {
return err
}
repaired++
}
if repaired > 0 {
log.Printf("Removed duplicate client entries from %d inbound(s)", repaired)
}
return nil
}
func isIgnorableDuplicateColumnErr(err error, mdl any) bool { func isIgnorableDuplicateColumnErr(err error, mdl any) bool {
if err == nil { if err == nil {
return false return false
@@ -637,7 +795,10 @@ func runSeeders(isUsersEmpty bool) error {
if err := seedWireguardPeersToClients(); err != nil { if err := seedWireguardPeersToClients(); err != nil {
return err return err
} }
return nil
// Idempotent, not seeder-gated: bad values can re-enter via a restored
// backup, so re-check on every start.
return normalizeSettingPaths()
} }
// resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where // resetIpLimitsWithoutFail2ban zeroes every client's IP limit on hosts where
@@ -742,6 +903,37 @@ func clearLegacyProxySettings() error {
}) })
} }
// normalizeSettingPaths repairs URI-path settings persisted before the
// leading/trailing-slash rules existed (or restored from an old backup),
// mirroring entity.AllSetting.CheckValid. CheckValid self-heals these on save,
// but the frontend rejects the whole Settings form on the bad stored value
// before a save can ever reach it (#5726), so the stored rows themselves must
// be fixed. Idempotent; runs on every start.
func normalizeSettingPaths() error {
pathKeys := []string{"webBasePath", "subPath", "subJsonPath", "subClashPath"}
var rows []model.Setting
if err := db.Where("key IN ?", pathKeys).Find(&rows).Error; err != nil {
return err
}
for _, row := range rows {
fixed := row.Value
if !strings.HasPrefix(fixed, "/") {
fixed = "/" + fixed
}
if !strings.HasSuffix(fixed, "/") {
fixed += "/"
}
if fixed == row.Value {
continue
}
if err := db.Model(&model.Setting{}).Where("id = ?", row.Id).
Update("value", fixed).Error; err != nil {
return err
}
}
return nil
}
func normalizeInboundClientTgId() error { func normalizeInboundClientTgId() error {
var inbounds []model.Inbound var inbounds []model.Inbound
if err := db.Find(&inbounds).Error; err != nil { if err := db.Find(&inbounds).Error; err != nil {
+41
View File
@@ -153,3 +153,44 @@ func TestNormalizeInboundClientSubId_FillsMissingAndPreservesExisting(t *testing
t.Fatalf("expected one InboundClientSubIdFix history row, got %d", historyCount) t.Fatalf("expected one InboundClientSubIdFix history row, got %d", historyCount)
} }
} }
func TestNormalizeSettingPaths_RepairsLegacyValues(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB failed: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
seed := []model.Setting{
{Key: "subJsonPath", Value: "YIrCXJOOOL"},
{Key: "subPath", Value: "/sub"},
{Key: "subClashPath", Value: "clash/"},
{Key: "webBasePath", Value: "/panel/"},
}
for i := range seed {
if err := db.Create(&seed[i]).Error; err != nil {
t.Fatalf("seed setting %s: %v", seed[i].Key, err)
}
}
if err := normalizeSettingPaths(); err != nil {
t.Fatalf("normalizeSettingPaths: %v", err)
}
want := map[string]string{
"subJsonPath": "/YIrCXJOOOL/",
"subPath": "/sub/",
"subClashPath": "/clash/",
"webBasePath": "/panel/",
}
for key, expected := range want {
var row model.Setting
if err := db.Where("key = ?", key).First(&row).Error; err != nil {
t.Fatalf("read %s: %v", key, err)
}
if row.Value != expected {
t.Errorf("%s = %q, want %q", key, row.Value, expected)
}
}
}
+57
View File
@@ -0,0 +1,57 @@
package database
import (
"path/filepath"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
// Locks the #5665 guard: composite-PK client_inbounds has no id column, so the
// sequence-reset SQL must never be issued for it.
func TestTableWithIdColumn_SkipsCompositeKeyModels(t *testing.T) {
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
if table, ok := tableWithIdColumn(db, &model.ClientInbound{}); ok {
t.Errorf("ClientInbound (table %q) has no id column but was not skipped", table)
}
table, ok := tableWithIdColumn(db, &model.Inbound{})
if !ok {
t.Fatal("Inbound has an id column but was reported as skippable")
}
if table != "inbounds" {
t.Errorf("Inbound table = %q, want inbounds", table)
}
}
// Exercises the #5665 AutoMigrate skip on SQLite (the check is dialect-agnostic):
// settled after InitDB, not settled with a missing column or table.
func TestPostgresModelSettled_TracksSchemaPresence(t *testing.T) {
if err := InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
for _, mdl := range []any{&model.ClientRecord{}, &model.ClientGroup{}, &model.ClientInbound{}} {
if !postgresModelSettled(mdl) {
t.Errorf("%T not settled right after InitDB", mdl)
}
}
if err := db.Migrator().DropColumn(&model.ClientGroup{}, "reset_up"); err != nil {
t.Fatalf("drop column: %v", err)
}
if postgresModelSettled(&model.ClientGroup{}) {
t.Error("ClientGroup settled despite missing reset_up column")
}
if err := db.Migrator().DropTable(&model.ClientGroup{}); err != nil {
t.Fatalf("drop table: %v", err)
}
if postgresModelSettled(&model.ClientGroup{}) {
t.Error("ClientGroup settled despite missing table")
}
}
+13
View File
@@ -2,6 +2,19 @@ package database
import "fmt" import "fmt"
// TrafficMax caps every traffic counter safely below math.MaxInt64 (~9.22e18)
// so that one more delta can never overflow int64. SQLite silently promotes an
// overflowing INTEGER to REAL, after which the column no longer scans into the
// Go int64 field and every reader of the table fails (#5762).
const TrafficMax = int64(9_000_000_000_000_000_000)
func ClampedAddExpr(col string) string {
if IsPostgres() {
return fmt.Sprintf("LEAST(%s + ?, %d)", col, TrafficMax)
}
return fmt.Sprintf("MIN(%s + ?, %d)", col, TrafficMax)
}
func JSONClientsFromInbound() string { func JSONClientsFromInbound() string {
if IsPostgres() { if IsPostgres() {
return "FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value)" return "FROM inbounds, jsonb_array_elements(inbounds.settings::jsonb -> 'clients') AS client(value)"
+78
View File
@@ -0,0 +1,78 @@
package database
import (
"encoding/json"
"path/filepath"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
// TestDedupeInboundSettingsClients_CollapsesDuplicateEmails covers the #5770
// repair: settings.clients arrays written by older builds can carry the same
// email several times; startup must collapse them to the first occurrence and
// leave clean inbounds byte-for-byte untouched.
func TestDedupeInboundSettingsClients_CollapsesDuplicateEmails(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB failed: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
dupSettings := `{"clients": [` +
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true},` +
`{"id": "u2", "email": "keep@x", "subId": "s2", "enable": true},` +
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true},` +
`{"id": "u1", "email": "dup@x", "subId": "s1", "enable": true}]}`
dirty := model.Inbound{UserId: 1, Port: 21001, Protocol: model.VLESS, Tag: "dedupe-dirty", Settings: dupSettings}
if err := db.Create(&dirty).Error; err != nil {
t.Fatalf("create dirty inbound: %v", err)
}
cleanSettings := `{"clients": [{"id": "u3", "email": "solo@x", "subId": "s3", "enable": true}]}`
clean := model.Inbound{UserId: 1, Port: 21002, Protocol: model.VLESS, Tag: "dedupe-clean", Settings: cleanSettings}
if err := db.Create(&clean).Error; err != nil {
t.Fatalf("create clean inbound: %v", err)
}
if err := dedupeInboundSettingsClients(); err != nil {
t.Fatalf("dedupeInboundSettingsClients: %v", err)
}
var gotDirty model.Inbound
if err := db.First(&gotDirty, dirty.Id).Error; err != nil {
t.Fatalf("reload dirty inbound: %v", err)
}
var parsed struct {
Clients []map[string]any `json:"clients"`
}
if err := json.Unmarshal([]byte(gotDirty.Settings), &parsed); err != nil {
t.Fatalf("parse repaired settings: %v", err)
}
if len(parsed.Clients) != 2 {
t.Fatalf("expected 2 clients after dedupe, got %d: %s", len(parsed.Clients), gotDirty.Settings)
}
if parsed.Clients[0]["email"] != "dup@x" || parsed.Clients[1]["email"] != "keep@x" {
t.Fatalf("expected first occurrences [dup@x keep@x], got %v", parsed.Clients)
}
var gotClean model.Inbound
if err := db.First(&gotClean, clean.Id).Error; err != nil {
t.Fatalf("reload clean inbound: %v", err)
}
if gotClean.Settings != cleanSettings {
t.Fatalf("clean inbound settings were rewritten:\nbefore: %s\nafter: %s", cleanSettings, gotClean.Settings)
}
if err := dedupeInboundSettingsClients(); err != nil {
t.Fatalf("second dedupe run: %v", err)
}
var again model.Inbound
if err := db.First(&again, dirty.Id).Error; err != nil {
t.Fatalf("reload after second run: %v", err)
}
if again.Settings != gotDirty.Settings {
t.Fatal("dedupe is not idempotent: settings changed on the second run")
}
}
+17 -9
View File
@@ -270,19 +270,14 @@ func resetPostgresSequences(dst *gorm.DB) error {
return resyncPostgresSequences(dst, migrationModels()) return resyncPostgresSequences(dst, migrationModels())
} }
// resyncPostgresSequences sets each model's id sequence to MAX(id) so the next // resyncPostgresSequences sets each model's id sequence to MAX(id); idempotent. Id-less
// auto-increment INSERT won't collide with an existing row. Table names are // composite-PK tables are skipped — Postgres rejects MAX(id) at parse time and logs it (#5665).
// resolved from the models themselves (not hardcoded), so they always match the
// migrated tables. The statement is a no-op for tables without an id sequence
// (e.g. composite-PK tables), and idempotent on a healthy DB, so it is safe to
// run both after migration and on every Postgres startup.
func resyncPostgresSequences(db *gorm.DB, models []any) error { func resyncPostgresSequences(db *gorm.DB, models []any) error {
for _, m := range models { for _, m := range models {
stmt := &gorm.Statement{DB: db} t, ok := tableWithIdColumn(db, m)
if err := stmt.Parse(m); err != nil { if !ok {
continue continue
} }
t := stmt.Table
// t comes from the trusted model set parsed by GORM, not user input, so // t comes from the trusted model set parsed by GORM, not user input, so
// interpolating it as an identifier is safe. We ignore errors per-table. // interpolating it as an identifier is safe. We ignore errors per-table.
_ = db.Exec( _ = db.Exec(
@@ -293,3 +288,16 @@ func resyncPostgresSequences(db *gorm.DB, models []any) error {
} }
return nil return nil
} }
// tableWithIdColumn resolves a model's table name and reports whether its GORM
// schema maps an "id" database column.
func tableWithIdColumn(db *gorm.DB, m any) (string, bool) {
stmt := &gorm.Statement{DB: db}
if err := stmt.Parse(m); err != nil {
return "", false
}
if stmt.Schema == nil || stmt.Schema.LookUpField("id") == nil {
return "", false
}
return stmt.Table, true
}
@@ -0,0 +1,103 @@
package database
import (
"path/filepath"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// TestRepairOverflowedTrafficCounters_HealsSQLiteRealPromotion reproduces
// #5762: a counter pushed past int64 makes SQLite silently store the cell as
// REAL, after which scanning the row back into the Go int64 field fails and
// every reader of client_traffics breaks. The startup repair must convert the
// cell back to a scannable integer clamped to TrafficMax.
func TestRepairOverflowedTrafficCounters_HealsSQLiteRealPromotion(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB failed: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
rows := []xray.ClientTraffic{
{Email: "overflowed@x", Enable: true, Up: 5, Down: 6},
{Email: "negative@x", Enable: true, Up: 7, Down: 8},
{Email: "healthy@x", Enable: true, Up: 100, Down: 200},
}
for i := range rows {
if err := db.Create(&rows[i]).Error; err != nil {
t.Fatalf("create traffic row %d: %v", i, err)
}
}
if err := db.Exec("UPDATE client_traffics SET down = 1.2247589467272907e+19 WHERE email = 'overflowed@x'").Error; err != nil {
t.Fatalf("corrupt down: %v", err)
}
if err := db.Exec("UPDATE client_traffics SET up = -42 WHERE email = 'negative@x'").Error; err != nil {
t.Fatalf("corrupt up: %v", err)
}
var broken []xray.ClientTraffic
if err := db.Find(&broken).Error; err == nil {
t.Fatal("expected the REAL-promoted row to break scanning before the repair")
}
if err := repairOverflowedTrafficCounters(); err != nil {
t.Fatalf("repairOverflowedTrafficCounters: %v", err)
}
byEmail := map[string]xray.ClientTraffic{}
var repaired []xray.ClientTraffic
if err := db.Find(&repaired).Error; err != nil {
t.Fatalf("scan after repair: %v", err)
}
for _, r := range repaired {
byEmail[r.Email] = r
}
if got := byEmail["overflowed@x"].Down; got != TrafficMax {
t.Errorf("overflowed down: expected clamp to %d, got %d", TrafficMax, got)
}
if got := byEmail["overflowed@x"].Up; got != 5 {
t.Errorf("overflowed up: expected untouched 5, got %d", got)
}
if got := byEmail["negative@x"].Up; got != 0 {
t.Errorf("negative up: expected clamp to 0, got %d", got)
}
if got := byEmail["healthy@x"]; got.Up != 100 || got.Down != 200 {
t.Errorf("healthy row changed: %+v", got)
}
}
// TestClampedAddExpr_CapsAtTrafficMax verifies the write-path clamp: a delta
// applied to a counter near the cap must saturate at TrafficMax instead of
// overflowing int64 (which SQLite would promote to REAL).
func TestClampedAddExpr_CapsAtTrafficMax(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB failed: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
row := xray.ClientTraffic{Email: "near-cap@x", Enable: true, Up: TrafficMax - 10, Down: 1}
if err := db.Create(&row).Error; err != nil {
t.Fatalf("create traffic row: %v", err)
}
query := "UPDATE client_traffics SET up = " + ClampedAddExpr("up") + ", down = " + ClampedAddExpr("down") + " WHERE email = ?"
if err := db.Exec(query, int64(1_000_000), int64(5), "near-cap@x").Error; err != nil {
t.Fatalf("clamped add: %v", err)
}
var got xray.ClientTraffic
if err := db.Where("email = ?", "near-cap@x").First(&got).Error; err != nil {
t.Fatalf("scan after clamped add: %v", err)
}
if got.Up != TrafficMax {
t.Errorf("up: expected saturation at %d, got %d", TrafficMax, got.Up)
}
if got.Down != 6 {
t.Errorf("down: expected 6, got %d", got.Down)
}
}
+3 -6
View File
@@ -240,8 +240,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
case model.VLESS: case model.VLESS:
proxy["type"] = "vless" proxy["type"] = "vless"
proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep)) proxy["uuid"] = applyVlessRoute(client.ID, hostVlessRoute(ep))
var inboundSettings map[string]any inboundSettings := subReq.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
streamSecurity, _ := stream["security"].(string) streamSecurity, _ := stream["security"].(string)
if client.Flow != "" && vlessFlowAllowed(network, streamSecurity, inboundSettings) { if client.Flow != "" && vlessFlowAllowed(network, streamSecurity, inboundSettings) {
proxy["flow"] = client.Flow proxy["flow"] = client.Flow
@@ -258,8 +257,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
case model.Shadowsocks: case model.Shadowsocks:
proxy["type"] = "ss" proxy["type"] = "ss"
proxy["password"] = client.Password proxy["password"] = client.Password
var inboundSettings map[string]any inboundSettings := subReq.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
method, _ := inboundSettings["method"].(string) method, _ := inboundSettings["method"].(string)
if method == "" { if method == "" {
return nil return nil
@@ -288,8 +286,7 @@ func (s *SubClashService) buildProxy(subReq *SubService, inbound *model.Inbound,
// helpers prune fields (like `allowInsecure` / the salamander obfs // helpers prune fields (like `allowInsecure` / the salamander obfs
// block) that the hysteria proxy wants preserved. // block) that the hysteria proxy wants preserved.
func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any { func (s *SubClashService) buildHysteriaProxy(subReq *SubService, inbound *model.Inbound, client model.Client, ep map[string]any) map[string]any {
var inboundSettings map[string]any inboundSettings := subReq.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
proxyType := "hysteria2" proxyType := "hysteria2"
authKey := "password" authKey := "password"
+41 -17
View File
@@ -146,29 +146,27 @@ func (a *SUBController) initRouter(g *gin.RouterGroup) {
} }
} }
// subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data. // maybeServeSubPage renders the HTML info page when the request comes from a
func (a *SUBController) subs(c *gin.Context) { // browser (Accept: text/html) or explicitly asks for it (?html=1 or ?view=html).
subId := c.Param("subid") // It reports whether the request was handled. The remark template's per-client
scheme, host, hostWithPort, hostHeader := a.subService.ResolveRequest(c) // info is for the content a client app imports — the raw subscription body. A
subReq := a.subService.ForRequest(host) // browser viewing the HTML info page gets clean, name-only remarks (usage is
// The remark template's per-client info is for the content a client app // shown in the page summary).
// imports — the raw subscription body. A browser viewing the HTML info page func (a *SUBController) maybeServeSubPage(c *gin.Context) bool {
// gets clean, name-only remarks (usage is shown in the page summary).
accept := c.GetHeader("Accept") accept := c.GetHeader("Accept")
wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html") wantsHTML := strings.Contains(strings.ToLower(accept), "text/html") || c.Query("html") == "1" || strings.EqualFold(c.Query("view"), "html")
subReq.subscriptionBody = !wantsHTML if !wantsHTML {
return false
}
subId := c.Param("subid")
_, host, _, hostHeader := a.subService.ResolveRequest(c)
subReq := a.subService.ForRequest(host)
subReq.subscriptionBody = false
subs, emails, lastOnline, traffic, err := subReq.getSubs(subId) subs, emails, lastOnline, traffic, err := subReq.getSubs(subId)
if err != nil || len(subs) == 0 { if err != nil || len(subs) == 0 {
writeSubError(c, err) writeSubError(c, err)
} else { return true
var result strings.Builder
for _, sub := range subs {
result.WriteString(sub)
result.WriteString("\n")
} }
// If the request expects HTML (e.g., browser) or explicitly asked (?html=1 or ?view=html), render the info page here
if wantsHTML {
subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId) subURL, subJsonURL, subClashURL := subReq.BuildURLs(a.subPath, a.subJsonPath, a.subClashPath, subId)
if !a.jsonEnabled { if !a.jsonEnabled {
subJsonURL = "" subJsonURL = ""
@@ -183,8 +181,27 @@ func (a *SUBController) subs(c *gin.Context) {
basePathStr := basePath.(string) basePathStr := basePath.(string)
page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl) page := subReq.BuildPageData(subId, hostHeader, traffic, lastOnline, subs, emails, subURL, subJsonURL, subClashURL, basePathStr, a.subTitle, a.subSupportUrl)
a.serveSubPage(c, basePathStr, page) a.serveSubPage(c, basePathStr, page)
return true
}
// subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data.
func (a *SUBController) subs(c *gin.Context) {
if a.maybeServeSubPage(c) {
return return
} }
subId := c.Param("subid")
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
subReq := a.subService.ForRequest(host)
subReq.subscriptionBody = true
subs, _, _, traffic, err := subReq.getSubs(subId)
if err != nil || len(subs) == 0 {
writeSubError(c, err)
} else {
var result strings.Builder
for _, sub := range subs {
result.WriteString(sub)
result.WriteString("\n")
}
// Add headers // Add headers
header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000) header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
@@ -264,6 +281,7 @@ func (a *SUBController) serveSubPage(c *gin.Context, basePath string, page PageD
"links": page.Result, "links": page.Result,
"emails": page.Emails, "emails": page.Emails,
"datepicker": datepicker, "datepicker": datepicker,
"announce": a.subAnnounce,
} }
// When an admin has configured a custom subscription theme, render it // When an admin has configured a custom subscription theme, render it
@@ -366,6 +384,9 @@ func (a *SUBController) loadSubTemplate(themeDir string) (*template.Template, er
// subJsons handles HTTP requests for JSON subscription configurations. // subJsons handles HTTP requests for JSON subscription configurations.
func (a *SUBController) subJsons(c *gin.Context) { func (a *SUBController) subJsons(c *gin.Context) {
if a.maybeServeSubPage(c) {
return
}
subId := c.Param("subid") subId := c.Param("subid")
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
jsonSub, header, err := a.subJsonService.GetJson(subId, host) jsonSub, header, err := a.subJsonService.GetJson(subId, host)
@@ -383,6 +404,9 @@ func (a *SUBController) subJsons(c *gin.Context) {
} }
func (a *SUBController) subClashs(c *gin.Context) { func (a *SUBController) subClashs(c *gin.Context) {
if a.maybeServeSubPage(c) {
return
}
subId := c.Param("subid") subId := c.Param("subid")
scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c)
clashSub, header, err := a.subClashService.GetClash(subId, host) clashSub, header, err := a.subClashService.GetClash(subId, host)
+24 -16
View File
@@ -138,7 +138,7 @@ func (s *SubJsonService) GetJson(subId string, host string) (string, string, err
func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage { func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
var newJsonArray []json_util.RawMessage var newJsonArray []json_util.RawMessage
stream := s.streamData(inbound.StreamSettings) stream := s.streamData(inbound.StreamSettings, subKey(client))
// When externalProxy is empty the JSON config falls back to a // When externalProxy is empty the JSON config falls back to a
// synthetic one whose `dest` is the host the client connects to. // synthetic one whose `dest` is the host the client connects to.
@@ -212,9 +212,9 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c
case "vless": case "vless":
vc := client vc := client
vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy)) vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, vc, jsonMux(mux, hostMux))) newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
case "trojan", "shadowsocks": case "trojan", "shadowsocks":
newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client, jsonMux(mux, hostMux))) newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
case "hysteria": case "hysteria":
newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux))) newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
} }
@@ -234,15 +234,25 @@ func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, c
return newJsonArray return newJsonArray
} }
func (s *SubJsonService) streamData(stream string) map[string]any { func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
var streamSettings map[string]any var streamSettings map[string]any
_ = json.Unmarshal([]byte(stream), &streamSettings) if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
streamSettings = map[string]any{}
}
security, _ := streamSettings["security"].(string) security, _ := streamSettings["security"].(string)
switch security { switch security {
case "tls": case "tls":
streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any)) if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
} else {
delete(streamSettings, "tlsSettings")
}
case "reality": case "reality":
streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any)) if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
} else {
delete(streamSettings, "realitySettings")
}
} }
delete(streamSettings, "sockopt") delete(streamSettings, "sockopt")
@@ -322,7 +332,7 @@ func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
return tlsData return tlsData
} }
func (s *SubJsonService) realityData(rData map[string]any) map[string]any { func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
rltyData := make(map[string]any, 1) rltyData := make(map[string]any, 1)
rltyClientSettings, _ := rData["settings"].(map[string]any) rltyClientSettings, _ := rData["settings"].(map[string]any)
@@ -331,8 +341,8 @@ func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
rltyData["fingerprint"] = rltyClientSettings["fingerprint"] rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"] rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
// Set random data seed, _ := rltyClientSettings["spiderX"].(string)
rltyData["spiderX"] = "/" + random.Seq(15) rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
shortIds, ok := rData["shortIds"].([]any) shortIds, ok := rData["shortIds"].([]any)
if ok && len(shortIds) > 0 { if ok && len(shortIds) > 0 {
rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string) rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
@@ -383,7 +393,7 @@ func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_ut
return result return result
} }
func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage { func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
outbound := Outbound{} outbound := Outbound{}
outbound.Protocol = string(inbound.Protocol) outbound.Protocol = string(inbound.Protocol)
outbound.Tag = "proxy" outbound.Tag = "proxy"
@@ -393,8 +403,7 @@ func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_ut
outbound.StreamSettings = streamSettings outbound.StreamSettings = streamSettings
// Add encryption for VLESS outbound from inbound settings // Add encryption for VLESS outbound from inbound settings
var inboundSettings map[string]any inboundSettings := subReq.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
encryption, _ := inboundSettings["encryption"].(string) encryption, _ := inboundSettings["encryption"].(string)
settings := map[string]any{ settings := map[string]any{
@@ -412,7 +421,7 @@ func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_ut
return result return result
} }
func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage { func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
outbound := Outbound{} outbound := Outbound{}
serverData := make([]ServerSetting, 1) serverData := make([]ServerSetting, 1)
@@ -424,8 +433,7 @@ func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_u
} }
if inbound.Protocol == model.Shadowsocks { if inbound.Protocol == model.Shadowsocks {
var inboundSettings map[string]any inboundSettings := subReq.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
method, _ := inboundSettings["method"].(string) method, _ := inboundSettings["method"].(string)
serverData[0].Method = method serverData[0].Method = method
+88 -11
View File
@@ -41,7 +41,7 @@ func TestSubJsonServiceInjectsGlobalFinalMask(t *testing.T) {
t.Fatal("direct_out outbound must never be emitted") t.Fatal("direct_out outbound must never be emitted")
} }
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`) stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
if _, ok := stream["sockopt"]; ok { if _, ok := stream["sockopt"]; ok {
t.Fatal("legacy direct_out dialerProxy sockopt must never be set") t.Fatal("legacy direct_out dialerProxy sockopt must never be set")
} }
@@ -77,7 +77,7 @@ func TestSubJsonServiceMergesWithExistingFinalMask(t *testing.T) {
stream := svc.streamData(`{ stream := svc.streamData(`{
"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}, "network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}},
"finalmask":{"tcp":[{"type":"sudoku"}]} "finalmask":{"tcp":[{"type":"sudoku"}]}
}`) }`, "")
finalmask, _ := stream["finalmask"].(map[string]any) finalmask, _ := stream["finalmask"].(map[string]any)
tcp, _ := finalmask["tcp"].([]any) tcp, _ := finalmask["tcp"].([]any)
@@ -93,7 +93,7 @@ func TestSubJsonServiceMergesWithExistingFinalMask(t *testing.T) {
func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) { func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) {
svc := NewSubJsonService("", "", "", nil) svc := NewSubJsonService("", "", "", nil)
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`) stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
if _, ok := stream["finalmask"]; ok { if _, ok := stream["finalmask"]; ok {
t.Fatal("no finalmask should be emitted when subJsonFinalMask is empty") t.Fatal("no finalmask should be emitted when subJsonFinalMask is empty")
} }
@@ -107,7 +107,7 @@ func TestSubJsonServiceNoFinalMaskWhenEmpty(t *testing.T) {
// to import the config (#5401). // to import the config (#5401).
func TestSubJsonServicePinnedCertJoinedToString(t *testing.T) { func TestSubJsonServicePinnedCertJoinedToString(t *testing.T) {
svc := NewSubJsonService("", "", "", nil) svc := NewSubJsonService("", "", "", nil)
stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","settings":{"pinnedPeerCertSha256":["aa11","bb22"]}}}`) stream := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":{"serverName":"a.example.com","settings":{"pinnedPeerCertSha256":["aa11","bb22"]}}}`, "")
tls, _ := stream["tlsSettings"].(map[string]any) tls, _ := stream["tlsSettings"].(map[string]any)
if tls == nil { if tls == nil {
@@ -122,7 +122,7 @@ func TestSubJsonServiceVlessFlattened(t *testing.T) {
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`} inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
client := model.Client{ID: "uuid-1", Flow: "xtls-rprx-vision"} client := model.Client{ID: "uuid-1", Flow: "xtls-rprx-vision"}
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(inbound, nil, client, "")) settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genVless(&SubService{}, inbound, nil, client, ""))
if _, ok := settings["vnext"]; ok { if _, ok := settings["vnext"]; ok {
t.Fatal("vless outbound must not use vnext") t.Fatal("vless outbound must not use vnext")
} }
@@ -151,7 +151,7 @@ func TestSubJsonServiceServerUsesServersArray(t *testing.T) {
trojan := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Trojan, Settings: `{}`} trojan := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Trojan, Settings: `{}`}
client := model.Client{Password: "p4ss"} client := model.Client{Password: "p4ss"}
settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(trojan, nil, client, "")) settings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, trojan, nil, client, ""))
server := firstServer(settings) server := firstServer(settings)
if server == nil { if server == nil {
t.Fatalf("trojan outbound must use a servers array, got: %#v", settings) t.Fatalf("trojan outbound must use a servers array, got: %#v", settings)
@@ -164,7 +164,7 @@ func TestSubJsonServiceServerUsesServersArray(t *testing.T) {
} }
ss := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Shadowsocks, Settings: `{"method":"aes-256-gcm"}`} ss := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.Shadowsocks, Settings: `{"method":"aes-256-gcm"}`}
ssSettings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(ss, nil, client, "")) ssSettings := outboundSettings(t, NewSubJsonService("", "", "", nil).genServer(&SubService{}, ss, nil, client, ""))
ssServer := firstServer(ssSettings) ssServer := firstServer(ssSettings)
if ssServer == nil { if ssServer == nil {
t.Fatalf("shadowsocks outbound must use a servers array, got: %#v", ssSettings) t.Fatalf("shadowsocks outbound must use a servers array, got: %#v", ssSettings)
@@ -181,7 +181,7 @@ func TestSubJsonServiceXmuxSuppressesGlobalMux(t *testing.T) {
// When xmux is present in xhttpSettings, the per-inbound xmux handles // When xmux is present in xhttpSettings, the per-inbound xmux handles
// multiplexing and the legacy outbound.Mux must NOT be set. // multiplexing and the legacy outbound.Mux must NOT be set.
stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up","xmux":{"maxConcurrency":"16-32"}}}` stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up","xmux":{"maxConcurrency":"16-32"}}}`
parsed := svc.streamData(stream) parsed := svc.streamData(stream, "")
mux := globalMux mux := globalMux
if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok { if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
@@ -194,7 +194,7 @@ func TestSubJsonServiceXmuxSuppressesGlobalMux(t *testing.T) {
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`} inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
client := model.Client{ID: "uuid-1"} client := model.Client{ID: "uuid-1"}
raw := svc.genVless(inbound, streamSettings, client, mux) raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
var ob map[string]any var ob map[string]any
if err := json.Unmarshal(raw, &ob); err != nil { if err := json.Unmarshal(raw, &ob); err != nil {
t.Fatalf("unmarshal outbound: %v", err) t.Fatalf("unmarshal outbound: %v", err)
@@ -227,7 +227,7 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
// When no xmux is present, the global subJsonMux should be used. // When no xmux is present, the global subJsonMux should be used.
stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up"}}` stream := `{"network":"xhttp","security":"tls","tlsSettings":{"serverName":"example.com"},"xhttpSettings":{"path":"/api","mode":"packet-up"}}`
parsed := svc.streamData(stream) parsed := svc.streamData(stream, "")
mux := globalMux mux := globalMux
if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok { if xhttp, ok := parsed["xhttpSettings"].(map[string]any); ok {
@@ -240,7 +240,7 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`} inbound := &model.Inbound{Listen: "1.2.3.4", Port: 443, Protocol: model.VLESS, Settings: `{"encryption":"none"}`}
client := model.Client{ID: "uuid-1"} client := model.Client{ID: "uuid-1"}
raw := svc.genVless(inbound, streamSettings, client, mux) raw := svc.genVless(&SubService{}, inbound, streamSettings, client, mux)
var ob map[string]any var ob map[string]any
if err := json.Unmarshal(raw, &ob); err != nil { if err := json.Unmarshal(raw, &ob); err != nil {
t.Fatalf("unmarshal outbound: %v", err) t.Fatalf("unmarshal outbound: %v", err)
@@ -254,3 +254,80 @@ func TestSubJsonServiceGlobalMuxWhenNoXmux(t *testing.T) {
t.Fatalf("mux payload wrong: %#v", m) t.Fatalf("mux payload wrong: %#v", m)
} }
} }
func realitySpiderXFromStream(t *testing.T, svc *SubJsonService, clientKey string) string {
t.Helper()
stream := svc.streamData(`{
"network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
"realitySettings":{
"serverNames":["reality.example.com"],
"shortIds":["ab12cd"],
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/seed"}
}
}`, clientKey)
rlty, _ := stream["realitySettings"].(map[string]any)
if rlty == nil {
t.Fatal("streamData dropped realitySettings")
}
spx, _ := rlty["spiderX"].(string)
if len(spx) != 16 || spx[0] != '/' {
t.Fatalf("spiderX = %q, want a 16-char /-prefixed value", spx)
}
return spx
}
func TestSubJsonServiceRealityDataDerivesPerClientSpiderX(t *testing.T) {
svc := NewSubJsonService("", "", "", nil)
alice := realitySpiderXFromStream(t, svc, "subAlice")
if again := realitySpiderXFromStream(t, svc, "subAlice"); again != alice {
t.Fatalf("spiderX not stable for the same client: %q vs %q", alice, again)
}
if bob := realitySpiderXFromStream(t, svc, "subBob"); bob == alice {
t.Fatalf("spiderX identical across clients (fingerprintable): %q", alice)
}
}
// streamData must tolerate malformed stored inbounds: unparseable stream JSON
// (with a finalMask configured, which writes into the map) and tls/reality
// security whose settings key is missing or null previously panicked the
// subscription request.
func TestSubJsonServiceStreamDataMalformedInputs(t *testing.T) {
withMask := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil)
stream := withMask.streamData("not-json", "clientKey")
if _, ok := stream["finalmask"]; !ok {
t.Fatal("finalMask must still apply when stream settings fail to parse")
}
svc := NewSubJsonService("", "", "", nil)
noReality := svc.streamData(`{"network":"tcp","security":"reality"}`, "clientKey")
if v, ok := noReality["realitySettings"]; ok {
t.Fatalf("missing realitySettings must stay absent, got %v", v)
}
nullTls := svc.streamData(`{"network":"tcp","security":"tls","tlsSettings":null}`, "")
if v, ok := nullTls["tlsSettings"]; ok {
t.Fatalf("null tlsSettings must be dropped, got %v", v)
}
}
func TestSubJsonServiceRealityDataSpiderXFallsBackWhenNoClientKey(t *testing.T) {
svc := NewSubJsonService("", "", "", nil)
stream := svc.streamData(`{
"network":"tcp","security":"reality","tcpSettings":{"header":{"type":"none"}},
"realitySettings":{
"serverNames":["reality.example.com"],
"shortIds":["ab12cd"],
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox"}
}
}`, "")
rlty, _ := stream["realitySettings"].(map[string]any)
if rlty == nil {
t.Fatal("streamData dropped realitySettings")
}
spx, _ := rlty["spiderX"].(string)
if len(spx) != 16 || spx[0] != '/' {
t.Fatalf("spiderX fallback = %q, want random 16-char /-prefixed value", spx)
}
}
+9 -9
View File
@@ -67,11 +67,11 @@ func TestSubJsonService_MuxAttachedWhenConfigured(t *testing.T) {
protocol model.Protocol protocol model.Protocol
}{ }{
{"vmess mux", NewSubJsonService(mux, "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, mux), true, model.VMESS}, {"vmess mux", NewSubJsonService(mux, "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, mux), true, model.VMESS},
{"vless mux", NewSubJsonService(mux, "", "", nil).genVless(&model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, mux), true, model.VLESS}, {"vless mux", NewSubJsonService(mux, "", "", nil).genVless(&SubService{}, &model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, mux), true, model.VLESS},
{"server mux", NewSubJsonService(mux, "", "", nil).genServer(&model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, mux), true, model.Trojan}, {"server mux", NewSubJsonService(mux, "", "", nil).genServer(&SubService{}, &model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, mux), true, model.Trojan},
{"vmess no mux", NewSubJsonService("", "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, ""), false, model.VMESS}, {"vmess no mux", NewSubJsonService("", "", "", nil).genVnext(&model.Inbound{Protocol: model.VMESS, Settings: `{}`}, nil, client, ""), false, model.VMESS},
{"vless no mux", NewSubJsonService("", "", "", nil).genVless(&model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, ""), false, model.VLESS}, {"vless no mux", NewSubJsonService("", "", "", nil).genVless(&SubService{}, &model.Inbound{Protocol: model.VLESS, Settings: `{}`}, nil, client, ""), false, model.VLESS},
{"server no mux", NewSubJsonService("", "", "", nil).genServer(&model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, ""), false, model.Trojan}, {"server no mux", NewSubJsonService("", "", "", nil).genServer(&SubService{}, &model.Inbound{Protocol: model.Trojan, Settings: `{}`}, nil, client, ""), false, model.Trojan},
} }
for _, tc := range cases { for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
@@ -95,15 +95,15 @@ func TestSubJsonService_MuxAttachedWhenConfigured(t *testing.T) {
} }
} }
// --- json_service.go:268 — a non-empty finalMask that merges to nothing must // --- applyGlobalFinalMask — a non-empty finalMask that merges to nothing must
// not add the finalmask key (the `len(merged) > 0` guard). --- // not add the finalmask key (the `len(merged) > 0` guard). ---
func TestSubJsonService_FinalMaskMergingToEmptyNotAdded(t *testing.T) { func TestSubJsonService_FinalMaskMergingToEmptyNotAdded(t *testing.T) {
// finalMask is non-empty (passes the len(fm)==0 early return) but its only // finalMask is non-empty (passes the len(fm)==0 early return) but its only
// key is an empty tcp slice, which mergeFinalMask drops → merged is empty, // key is an empty tcp slice, which mergeFinalMask drops → merged is empty,
// so applyGlobalFinalMask (json_service.go:268) must NOT set finalmask. // so applyGlobalFinalMask must NOT set finalmask.
svc := NewSubJsonService("", "", `{"tcp":[]}`, nil) svc := NewSubJsonService("", "", `{"tcp":[]}`, nil)
stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`) stream := svc.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
if _, ok := stream["finalmask"]; ok { if _, ok := stream["finalmask"]; ok {
t.Fatalf("finalMask merging to empty must not add a finalmask key: %#v", stream["finalmask"]) t.Fatalf("finalMask merging to empty must not add a finalmask key: %#v", stream["finalmask"])
} }
@@ -111,13 +111,13 @@ func TestSubJsonService_FinalMaskMergingToEmptyNotAdded(t *testing.T) {
// Sanity: a finalMask that DOES merge to something still gets set, so the // Sanity: a finalMask that DOES merge to something still gets set, so the
// guard is the only distinguishing factor. // guard is the only distinguishing factor.
svc2 := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil) svc2 := NewSubJsonService("", "", `{"tcp":[{"type":"fragment"}]}`, nil)
stream2 := svc2.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`) stream2 := svc2.streamData(`{"network":"tcp","security":"none","tcpSettings":{"header":{"type":"none"}}}`, "")
if _, ok := stream2["finalmask"]; !ok { if _, ok := stream2["finalmask"]; !ok {
t.Fatal("non-empty finalMask must be set") t.Fatal("non-empty finalMask must be set")
} }
} }
// --- json_service.go:494 — an empty extra tcp slice must not clobber the base --- // --- mergeFinalMask — an empty extra tcp slice must not clobber the base ---
func TestMergeFinalMask_EmptyExtraTcpKeepsBase(t *testing.T) { func TestMergeFinalMask_EmptyExtraTcpKeepsBase(t *testing.T) {
base := map[string]any{"tcp": []any{map[string]any{"type": "keep"}}} base := map[string]any{"tcp": []any{map[string]any{"type": "keep"}}}
+1 -4
View File
@@ -459,12 +459,9 @@ func (s *SubService) statsForClient(inbound *model.Inbound, client model.Client)
// needed when a global remark template references client-only tokens. Falls back // needed when a global remark template references client-only tokens. Falls back
// to an email-only client if not found. // to an email-only client if not found.
func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Client { func (s *SubService) lookupClient(inbound *model.Inbound, email string) model.Client {
clients, _ := s.inboundService.GetClients(inbound) if c, ok := s.clientForLink(inbound, email); ok {
for _, c := range clients {
if c.Email == email {
return c return c
} }
}
return model.Client{Email: email} return model.Client{Email: email}
} }
+196 -67
View File
@@ -54,6 +54,17 @@ type SubService struct {
// doesn't own its row (multi-inbound subscriptions). Filled in // doesn't own its row (multi-inbound subscriptions). Filled in
// getInboundsBySubId; reset per request in PrepareForRequest. // getInboundsBySubId; reset per request in PrepareForRequest.
statsByEmail map[string]xray.ClientTraffic statsByEmail map[string]xray.ClientTraffic
// clientsByInbound caches clients resolved for this request keyed by
// inbound id then email, so the per-protocol link generators look a client
// up without re-parsing the inbound's settings JSON per link.
// fullyPrimedInbounds marks inbounds whose complete client list is cached
// (a miss there is authoritative). Reset per request in PrepareForRequest.
clientsByInbound map[int]map[string]model.Client
fullyPrimedInbounds map[int]bool
// settingsByInbound caches each inbound's settings decoded once per request
// with the clients array left out; generators read only inbound-level
// fields (encryption, method, version, …) from it.
settingsByInbound map[int]map[string]any
} }
// NewSubService creates a new subscription service with the given configuration. // NewSubService creates a new subscription service with the given configuration.
@@ -86,10 +97,96 @@ func (s *SubService) PrepareForRequest(host string) {
s.address = host s.address = host
s.usageShown = map[string]bool{} s.usageShown = map[string]bool{}
s.statsByEmail = map[string]xray.ClientTraffic{} s.statsByEmail = map[string]xray.ClientTraffic{}
s.clientsByInbound = map[int]map[string]model.Client{}
s.fullyPrimedInbounds = map[int]bool{}
s.settingsByInbound = map[int]map[string]any{}
s.loadNodes() s.loadNodes()
s.loadRemarkSettings() s.loadRemarkSettings()
} }
// primeLinkClients caches clients (first occurrence per email, matching the
// old settings-JSON iteration order) so clientForLink resolves them without a
// parse. complete marks the inbound's whole client list as cached.
func (s *SubService) primeLinkClients(inboundId int, clients []model.Client, complete bool) {
if inboundId <= 0 {
return
}
if s.clientsByInbound == nil {
s.clientsByInbound = map[int]map[string]model.Client{}
}
m := s.clientsByInbound[inboundId]
if m == nil {
m = make(map[string]model.Client, len(clients))
s.clientsByInbound[inboundId] = m
}
for _, c := range clients {
if _, exists := m[c.Email]; !exists {
m[c.Email] = c
}
}
if complete {
if s.fullyPrimedInbounds == nil {
s.fullyPrimedInbounds = map[int]bool{}
}
s.fullyPrimedInbounds[inboundId] = true
}
}
// clientForLink resolves one client of an inbound by email for link
// generation: from the per-request cache when primed, otherwise by parsing
// the settings JSON once and caching every client from it.
func (s *SubService) clientForLink(inbound *model.Inbound, email string) (model.Client, bool) {
if m, ok := s.clientsByInbound[inbound.Id]; ok {
if c, hit := m[email]; hit {
return c, true
}
if s.fullyPrimedInbounds[inbound.Id] {
return model.Client{}, false
}
}
clients, err := s.inboundService.GetClients(inbound)
if err != nil {
return model.Client{}, false
}
s.primeLinkClients(inbound.Id, clients, true)
for i := range clients {
if clients[i].Email == email {
return clients[i], true
}
}
return model.Client{}, false
}
// linkSettings returns the inbound's settings decoded once per request with
// the clients array left out — the link generators read only inbound-level
// fields from it and resolve clients via clientForLink. The shallow
// RawMessage pass skips materializing a huge clients array entirely.
func (s *SubService) linkSettings(inbound *model.Inbound) map[string]any {
if inbound.Id > 0 {
if cached, ok := s.settingsByInbound[inbound.Id]; ok {
return cached
}
}
shallow := map[string]json.RawMessage{}
_ = json.Unmarshal([]byte(inbound.Settings), &shallow)
out := make(map[string]any, len(shallow))
for key, raw := range shallow {
if key == "clients" {
continue
}
var value any
_ = json.Unmarshal(raw, &value)
out[key] = value
}
if inbound.Id > 0 {
if s.settingsByInbound == nil {
s.settingsByInbound = map[int]map[string]any{}
}
s.settingsByInbound[inbound.Id] = out
}
return out
}
// loadRemarkSettings populates the per-request remark formatting state so // loadRemarkSettings populates the per-request remark formatting state so
// every subscription format — raw, JSON, Clash — renders remarks the same way // every subscription format — raw, JSON, Clash — renders remarks the same way
// (the date formatter reads datepicker). Loading it only in getSubs left // (the date formatter reads datepicker). Loading it only in getSubs left
@@ -144,25 +241,23 @@ func listenIsInternalOnly(listen string) bool {
} }
// matchingClients returns the inbound's clients whose SubID equals subId, // matchingClients returns the inbound's clients whose SubID equals subId,
// deduplicated by email. settings.clients can accumulate duplicate entries // resolved from the normalized clients/client_inbounds tables (both filter
// for the same client (multi-node sync/import drift, old DBs): SyncInbound // columns indexed) instead of parsing the settings JSON — at large client
// dedupes the normalized client_inbounds rows on write but never rewrites // counts that parse made every subscription fetch cost seconds. The
// the legacy JSON, and the subscription builders iterate that JSON — so // case-insensitive email dedupe stays as cheap insurance even though
// without this guard every duplicate became a duplicate profile in the // clients.email is unique, preserving the #5134 guarantee that duplicate
// output (#5134). Link generation keys purely on (inbound, email), so // settings entries never fan out into duplicate profiles. Resolved clients
// same-email entries are pure duplicates and dropping them is lossless. // are primed into the per-request cache so the link generators don't parse
// settings either.
func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []model.Client { func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []model.Client {
clients, err := s.inboundService.GetClients(inbound) clients, err := s.inboundService.GetClientsBySubId(inbound.Id, subId)
if err != nil { if err != nil {
logger.Error("SubService - GetClients: Unable to get clients from inbound") logger.Error("SubService - GetClientsBySubId: Unable to get clients from inbound")
return nil return nil
} }
var out []model.Client var out []model.Client
seen := make(map[string]struct{}, len(clients)) seen := make(map[string]struct{}, len(clients))
for _, client := range clients { for _, client := range clients {
if client.SubID != subId {
continue
}
key := strings.ToLower(client.Email) key := strings.ToLower(client.Email)
if _, dup := seen[key]; dup { if _, dup := seen[key]; dup {
continue continue
@@ -170,6 +265,7 @@ func (s *SubService) matchingClients(inbound *model.Inbound, subId string) []mod
seen[key] = struct{}{} seen[key] = struct{}{}
out = append(out, client) out = append(out, client)
} }
s.primeLinkClients(inbound.Id, out, false)
return out return out
} }
@@ -253,6 +349,7 @@ func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
if err != nil { if err != nil {
return nil return nil
} }
s.primeLinkClients(inbound.Id, clients, true)
s.projectThroughFallbackMaster(inbound) s.projectThroughFallbackMaster(inbound)
hostEps := s.hostEndpoints(inbound, "raw") hostEps := s.hostEndpoints(inbound, "raw")
var out []string var out []string
@@ -362,7 +459,7 @@ func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) { func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
db := database.GetDB() db := database.GetDB()
var inbounds []*model.Inbound var inbounds []*model.Inbound
err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in ( err := db.Model(model.Inbound{}).Where(`id in (
SELECT DISTINCT inbounds.id SELECT DISTINCT inbounds.id
FROM inbounds FROM inbounds
JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
@@ -374,19 +471,34 @@ func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error)
if err != nil { if err != nil {
return nil, err return nil, err
} }
s.indexStatsByEmail(inbounds) s.indexStatsBySubId(subId)
return inbounds, nil return inbounds, nil
} }
// indexStatsByEmail records every loaded inbound's client traffic rows keyed by // indexStatsBySubId loads the traffic rows for just this subscriber's clients
// email so statsForClient can resolve a client's usage even on an inbound that // into statsByEmail so statsForClient can resolve a client's usage on any of
// doesn't own its (globally unique) client_traffics row. See statsByEmail. // its inbounds. It replaces preloading every matched inbound's ClientStats,
func (s *SubService) indexStatsByEmail(inbounds []*model.Inbound) { // which read the entire client_traffics table on every subscription fetch of
// a large inbound; statsForClient's per-email DB fallback covers any miss.
func (s *SubService) indexStatsBySubId(subId string) {
if s.statsByEmail == nil { if s.statsByEmail == nil {
s.statsByEmail = map[string]xray.ClientTraffic{} s.statsByEmail = map[string]xray.ClientTraffic{}
} }
for _, inbound := range inbounds { db := database.GetDB()
for _, st := range inbound.ClientStats { var emails []string
if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", subId).Pluck("email", &emails).Error; err != nil {
logger.Error("SubService - indexStatsBySubId: load emails:", err)
return
}
const chunk = 400
for lo := 0; lo < len(emails); lo += chunk {
hi := min(lo+chunk, len(emails))
var rows []xray.ClientTraffic
if err := db.Where("email IN ?", emails[lo:hi]).Find(&rows).Error; err != nil {
logger.Error("SubService - indexStatsBySubId: load traffics:", err)
return
}
for _, st := range rows {
s.statsByEmail[st.Email] = st s.statsByEmail[st.Email] = st
} }
} }
@@ -516,21 +628,14 @@ func (s *SubService) genWireguardLink(inbound *model.Inbound, email string) stri
if inbound.Protocol != model.WireGuard { if inbound.Protocol != model.WireGuard {
return "" return ""
} }
settings := map[string]any{} settings := s.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
secretKey, _ := settings["secretKey"].(string) secretKey, _ := settings["secretKey"].(string)
clients, _ := s.inboundService.GetClients(inbound) resolved, ok := s.clientForLink(inbound, email)
var client *model.Client if !ok || resolved.PrivateKey == "" {
for i := range clients {
if clients[i].Email == email {
client = &clients[i]
break
}
}
if client == nil || client.PrivateKey == "" {
return "" return ""
} }
client := &resolved
link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(s.resolveInboundAddress(inbound), inbound.Port)) link := fmt.Sprintf("wireguard://%s@%s", encodeUserinfo(client.PrivateKey), joinHostPort(s.resolveInboundAddress(inbound), inbound.Port))
params := make(map[string]string) params := make(map[string]string)
@@ -607,10 +712,12 @@ func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
applyVmessTLSParams(stream, obj) applyVmessTLSParams(stream, obj)
} }
clients, _ := s.inboundService.GetClients(inbound) client, ok := s.clientForLink(inbound, email)
clientIndex := findClientIndex(clients, email) if !ok {
obj["id"] = clients[clientIndex].ID return ""
obj["scy"] = clients[clientIndex].Security }
obj["id"] = client.ID
obj["scy"] = client.Security
externalProxies, _ := stream["externalProxy"].([]any) externalProxies, _ := stream["externalProxy"].([]any)
@@ -659,17 +766,18 @@ func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
} }
address := s.resolveInboundAddress(inbound) address := s.resolveInboundAddress(inbound)
stream := unmarshalStreamSettings(inbound.StreamSettings) stream := unmarshalStreamSettings(inbound.StreamSettings)
clients, _ := s.inboundService.GetClients(inbound) client, ok := s.clientForLink(inbound, email)
clientIndex := findClientIndex(clients, email) if !ok {
uuid := clients[clientIndex].ID return ""
}
uuid := client.ID
port := inbound.Port port := inbound.Port
streamNetwork := stream["network"].(string) streamNetwork := stream["network"].(string)
params := make(map[string]string) params := make(map[string]string)
params["type"] = streamNetwork params["type"] = streamNetwork
// Add encryption parameter for VLESS from inbound settings // Add encryption parameter for VLESS from inbound settings
var settings map[string]any settings := s.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
if encryption, ok := settings["encryption"].(string); ok { if encryption, ok := settings["encryption"].(string); ok {
params["encryption"] = encryption params["encryption"] = encryption
} }
@@ -683,12 +791,12 @@ func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
case "tls": case "tls":
applyShareTLSParams(stream, params) applyShareTLSParams(stream, params)
case "reality": case "reality":
applyShareRealityParams(stream, params) applyShareRealityParams(stream, params, subKey(client))
default: default:
params["security"] = "none" params["security"] = "none"
} }
if len(clients[clientIndex].Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) { if len(client.Flow) > 0 && vlessFlowAllowed(streamNetwork, security, settings) {
params["flow"] = clients[clientIndex].Flow params["flow"] = client.Flow
} }
externalProxies, _ := stream["externalProxy"].([]any) externalProxies, _ := stream["externalProxy"].([]any)
@@ -717,9 +825,11 @@ func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string
} }
address := s.resolveInboundAddress(inbound) address := s.resolveInboundAddress(inbound)
stream := unmarshalStreamSettings(inbound.StreamSettings) stream := unmarshalStreamSettings(inbound.StreamSettings)
clients, _ := s.inboundService.GetClients(inbound) client, ok := s.clientForLink(inbound, email)
clientIndex := findClientIndex(clients, email) if !ok {
password := encodeUserinfo(clients[clientIndex].Password) return ""
}
password := encodeUserinfo(client.Password)
port := inbound.Port port := inbound.Port
streamNetwork := stream["network"].(string) streamNetwork := stream["network"].(string)
params := make(map[string]string) params := make(map[string]string)
@@ -734,9 +844,9 @@ func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string
case "tls": case "tls":
applyShareTLSParams(stream, params) applyShareTLSParams(stream, params)
case "reality": case "reality":
applyShareRealityParams(stream, params) applyShareRealityParams(stream, params, subKey(client))
if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 { if streamNetwork == "tcp" && len(client.Flow) > 0 {
params["flow"] = clients[clientIndex].Flow params["flow"] = client.Flow
} }
default: default:
params["security"] = "none" params["security"] = "none"
@@ -788,13 +898,14 @@ func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) st
} }
address := s.resolveInboundAddress(inbound) address := s.resolveInboundAddress(inbound)
stream := unmarshalStreamSettings(inbound.StreamSettings) stream := unmarshalStreamSettings(inbound.StreamSettings)
clients, _ := s.inboundService.GetClients(inbound) client, ok := s.clientForLink(inbound, email)
if !ok {
return ""
}
var settings map[string]any settings := s.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
inboundPassword := settings["password"].(string) inboundPassword := settings["password"].(string)
method := settings["method"].(string) method := settings["method"].(string)
clientIndex := findClientIndex(clients, email)
streamNetwork := stream["network"].(string) streamNetwork := stream["network"].(string)
params := make(map[string]string) params := make(map[string]string)
params["type"] = streamNetwork params["type"] = streamNetwork
@@ -828,9 +939,9 @@ func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) st
userInfo = fmt.Sprintf("%s:%s:%s", userInfo = fmt.Sprintf("%s:%s:%s",
url.QueryEscape(method), url.QueryEscape(method),
url.QueryEscape(inboundPassword), url.QueryEscape(inboundPassword),
url.QueryEscape(clients[clientIndex].Password)) url.QueryEscape(client.Password))
} else { } else {
userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, clients[clientIndex].Password)) userInfo = base64.RawURLEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", method, client.Password))
} }
externalProxies, _ := stream["externalProxy"].([]any) externalProxies, _ := stream["externalProxy"].([]any)
@@ -861,15 +972,11 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin
} }
var stream map[string]any var stream map[string]any
_ = json.Unmarshal([]byte(inbound.StreamSettings), &stream) _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
clients, _ := s.inboundService.GetClients(inbound) client, ok := s.clientForLink(inbound, email)
clientIndex := -1 if !ok {
for i, client := range clients { return ""
if client.Email == email {
clientIndex = i
break
} }
} auth := encodeUserinfo(client.Auth)
auth := encodeUserinfo(clients[clientIndex].Auth)
params := make(map[string]string) params := make(map[string]string)
params["security"] = "tls" params["security"] = "tls"
@@ -928,8 +1035,7 @@ func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) strin
} }
} }
var settings map[string]any settings := s.linkSettings(inbound)
_ = json.Unmarshal([]byte(inbound.Settings), &settings)
version, _ := settings["version"].(float64) version, _ := settings["version"].(float64)
protocol := "hysteria2" protocol := "hysteria2"
if int(version) == 1 { if int(version) == 1 {
@@ -1330,7 +1436,7 @@ func hysteriaPinHex(pin string) string {
return pin return pin
} }
func applyShareRealityParams(stream map[string]any, params map[string]string) { func applyShareRealityParams(stream map[string]any, params map[string]string, clientKey string) {
params["security"] = "reality" params["security"] = "reality"
realitySetting, _ := stream["realitySettings"].(map[string]any) realitySetting, _ := stream["realitySettings"].(map[string]any)
realitySettings, _ := searchKey(realitySetting, "settings") realitySettings, _ := searchKey(realitySetting, "settings")
@@ -1356,8 +1462,31 @@ func applyShareRealityParams(stream map[string]any, params map[string]string) {
params["pqv"] = pqv params["pqv"] = pqv
} }
} }
params["spx"] = "/" + random.Seq(15) seed := ""
if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
seed, _ = spxValue.(string)
} }
params["spx"] = deriveSpiderX(seed, clientKey)
}
}
// subKey returns a stable per-client identity for deterministic derivations,
// preferring the subscription id and falling back to the (unique) email.
func subKey(c model.Client) string {
if c.SubID != "" {
return c.SubID
}
return c.Email
}
// deriveSpiderX maps the inbound's spiderX seed plus a stable client key to a
// deterministic per-client "/path"; frontend/src/lib/xray/spider-x.ts mirrors it.
func deriveSpiderX(seed, clientKey string) string {
if seed == "" && clientKey == "" {
return "/" + random.Seq(15)
}
sum := sha256.Sum256([]byte(seed + "|" + clientKey))
return "/" + hex.EncodeToString(sum[:])[:15]
} }
func buildVmessLink(obj map[string]any) string { func buildVmessLink(obj map[string]any) string {
+26 -10
View File
@@ -69,19 +69,35 @@ func TestGetSubs_DuplicateSettingsClients_Deduped(t *testing.T) {
} }
} }
// TestMatchingClients_DedupsCaseInsensitiveEmail pins the dedup KEY, not just the count: // TestMatchingClients_DedupsCaseInsensitiveEmail pins the dedup KEY, not just the count.
// the two entries differ only by email case, so dropping strings.ToLower (or keying on // clients.email is unique but case-sensitively so: two rows differing only by email case
// another field) yields two clients. The byte-identical dupes above can't catch that. // can coexist (import drift), and dropping strings.ToLower (or keying on another field)
// would emit both. The first row by id must win, matching the old settings-JSON order.
func TestMatchingClients_DedupsCaseInsensitiveEmail(t *testing.T) { func TestMatchingClients_DedupsCaseInsensitiveEmail(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
const subId = "s1" const subId = "s1"
const uuid = "11111111-2222-4333-8444-555555555555" const uuid = "11111111-2222-4333-8444-555555555555"
ib := &model.Inbound{ db := database.GetDB()
Protocol: model.VLESS, ib := &model.Inbound{Protocol: model.VLESS, Enable: true, Port: 42002, Tag: "dedup-ci", Settings: `{"clients":[]}`}
Settings: `{"clients":[ if err := db.Create(ib).Error; err != nil {
{"id":"` + uuid + `","email":"Dup@Example.com","subId":"` + subId + `","enable":true}, t.Fatalf("seed inbound: %v", err)
{"id":"` + uuid + `","email":"dup@example.com","subId":"` + subId + `","enable":true}
]}`,
} }
for _, email := range []string{"Dup@Example.com", "dup@example.com"} {
c := &model.ClientRecord{Email: email, SubID: subId, UUID: uuid, Enable: true}
if err := db.Create(c).Error; err != nil {
t.Fatalf("seed client %q: %v", email, err)
}
if err := db.Create(&model.ClientInbound{ClientId: c.Id, InboundId: ib.Id}).Error; err != nil {
t.Fatalf("seed client_inbound %q: %v", email, err)
}
}
s := &SubService{} s := &SubService{}
got := s.matchingClients(ib, subId) got := s.matchingClients(ib, subId)
if len(got) != 1 { if len(got) != 1 {
@@ -90,7 +106,7 @@ func TestMatchingClients_DedupsCaseInsensitiveEmail(t *testing.T) {
if got[0].Email != "Dup@Example.com" { if got[0].Email != "Dup@Example.com" {
t.Fatalf("first occurrence must be kept, got %q", got[0].Email) t.Fatalf("first occurrence must be kept, got %q", got[0].Email)
} }
// A wrong subId must still be excluded (guards the subId filter at service.go:127). // A wrong subId must still be excluded (guards the SQL subId filter).
if other := s.matchingClients(ib, "nope"); len(other) != 0 { if other := s.matchingClients(ib, "nope"); len(other) != 0 {
t.Fatalf("non-matching subId must yield 0 clients, got %d", len(other)) t.Fatalf("non-matching subId must yield 0 clients, got %d", len(other))
} }
+95 -6
View File
@@ -1,6 +1,7 @@
package sub package sub
import ( import (
"net/url"
"strings" "strings"
"testing" "testing"
@@ -52,10 +53,8 @@ func TestGenVlessLink_TLSParamsMapped(t *testing.T) {
} }
} }
// TestGenVlessLink_RealityParamsMapped locks the reality field mapping // Locks the reality field mapping of applyShareRealityParams; distinct pbk/sid
// (applyShareRealityParams, service.go:1147). serverNames/shortIds are single-element // catch a swap mutant. spx is now a per-client derived value (#5718 / follow-up).
// so random.Num is deterministic (index 0); spx is random so it is asserted by prefix.
// Distinct pbk/sid values catch a pbk<->sid swap mutant.
func TestGenVlessLink_RealityParamsMapped(t *testing.T) { func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
stream := `{ stream := `{
"network":"tcp","security":"reality", "network":"tcp","security":"reality",
@@ -63,7 +62,7 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
"realitySettings":{ "realitySettings":{
"serverNames":["reality.example.com"], "serverNames":["reality.example.com"],
"shortIds":["ab12cd"], "shortIds":["ab12cd"],
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox"} "settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/mypath"}
} }
}` }`
s := &SubService{} s := &SubService{}
@@ -75,7 +74,7 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
"pbk=PBKvalue", "pbk=PBKvalue",
"sid=ab12cd", "sid=ab12cd",
"fp=firefox", "fp=firefox",
"spx=%2F", // "/" + random.Seq(15), percent-encoded leading slash "spx=%2F",
} }
for _, w := range wants { for _, w := range wants {
if !strings.Contains(link, w) { if !strings.Contains(link, w) {
@@ -87,3 +86,93 @@ func TestGenVlessLink_RealityParamsMapped(t *testing.T) {
t.Fatalf("reality pbk/sid mapping crossed: %s", link) t.Fatalf("reality pbk/sid mapping crossed: %s", link)
} }
} }
// realityTwoClientInbound builds a reality VLESS inbound carrying two clients
// with distinct subIds so the per-client spx derivation can be exercised.
func realityTwoClientInbound() *model.Inbound {
return &model.Inbound{
Listen: "203.0.113.1",
Port: 443,
Protocol: model.VLESS,
Remark: "sharelink",
Settings: `{"clients":[
{"id":"11111111-2222-4333-8444-555555555555","email":"alice","subId":"subAlice"},
{"id":"22222222-3333-4444-8555-666666666666","email":"bob","subId":"subBob"}
],"decryption":"none","encryption":"none"}`,
StreamSettings: `{
"network":"tcp","security":"reality",
"tcpSettings":{"header":{"type":"none"}},
"realitySettings":{
"serverNames":["reality.example.com"],
"shortIds":["ab12cd"],
"settings":{"publicKey":"PBKvalue","fingerprint":"firefox","spiderX":"/seed"}
}
}`,
}
}
func spxParam(t *testing.T, link string) string {
t.Helper()
u, err := url.Parse(link)
if err != nil {
t.Fatalf("parse link %q: %v", link, err)
}
spx := u.Query().Get("spx")
if spx == "" || spx[0] != '/' {
t.Fatalf("spx missing or not /-prefixed in %q", link)
}
return spx
}
// spx must be stable for a given client across repeated exports (the #5718
// complaint) yet differ between clients so the value can't be fingerprinted.
func TestGenVlessLink_RealitySpiderXPerClientStable(t *testing.T) {
s := &SubService{}
inbound := realityTwoClientInbound()
aliceFirst := spxParam(t, s.genVlessLink(inbound, "alice"))
aliceSecond := spxParam(t, s.genVlessLink(inbound, "alice"))
bob := spxParam(t, s.genVlessLink(inbound, "bob"))
if aliceFirst != aliceSecond {
t.Fatalf("spx not stable for the same client: %q vs %q", aliceFirst, aliceSecond)
}
if aliceFirst == bob {
t.Fatalf("spx identical across clients (fingerprintable): %q", aliceFirst)
}
}
func TestDeriveSpiderX(t *testing.T) {
if got := deriveSpiderX("seed", "clientA"); got != deriveSpiderX("seed", "clientA") {
t.Fatalf("deriveSpiderX not deterministic: %q", got)
}
if deriveSpiderX("seed", "clientA") == deriveSpiderX("seed", "clientB") {
t.Fatal("deriveSpiderX must differ per client")
}
if deriveSpiderX("seedA", "clientA") == deriveSpiderX("seedB", "clientA") {
t.Fatal("rotating the seed must rotate a client's spx")
}
got := deriveSpiderX("seed", "clientA")
if len(got) != 16 || got[0] != '/' {
t.Fatalf("deriveSpiderX shape = %q, want /-prefixed 15-char path", got)
}
if fallback := deriveSpiderX("", ""); len(fallback) != 16 || fallback[0] != '/' {
t.Fatalf("empty-input fallback = %q, want /-prefixed path", fallback)
}
}
// Cross-language vectors shared with frontend/src/test/spider-x.test.ts: the
// panel builds these links in TS, so both derivations must agree byte-for-byte.
func TestDeriveSpiderXMatchesFrontendVectors(t *testing.T) {
vectors := map[string]struct{ seed, clientKey, want string }{
"seed and subId": {"/seed", "subAlice", "/c252fbc3ecd3e3c"},
"seed only": {"/", "", "/d08ed99bd9afc60"},
}
for name, v := range vectors {
t.Run(name, func(t *testing.T) {
if got := deriveSpiderX(v.seed, v.clientKey); got != v.want {
t.Fatalf("deriveSpiderX(%q, %q) = %q, want %q (must match frontend/src/lib/xray/spider-x.ts)", v.seed, v.clientKey, got, v.want)
}
})
}
}

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