Compare commits

...

133 Commits

Author SHA1 Message Date
Sanaei fcf60eb2e2 chore: bump dependencies and clear deprecated frontend APIs
Routine dependency refresh: telego 1.11.2, go-sqlite3 1.14.50, grpc 1.83.1,
miekg/dns 1.1.73, sing 0.8.14 and the usual indirect churn on the Go side;
react-query 5.102.2, i18next 26.4.0, react-hook-form 7.86.0, Storybook
10.5.10 and vite 8.2.2 on the frontend, which also lifts the private frontend
package to 1.0.0.

That left npm run lint:deprecated with five call sites. Zod 4 deprecates the
ZodTypeAny alias in favour of the bare z.ZodType constraint, and react-query
renamed queryClient.fetchQuery to queryClient.query ahead of removing the old
name in the next major — the two share an implementation, so the swap in the
settings test is behaviour-identical.

Also untracks internal/web/dist/.gitkeep. 1872659d dropped its gitignore
exception on the grounds that nothing under dist/ is ever meant to be
tracked, but the file was already in the index, so the rule never applied and
every frontend build that empties dist/ resurfaced it as a spurious deletion.
make dist-stub and every CI job recreate it on disk.
2026-08-24 14:56:40 +02:00
Sanaei 103b0dfe8d fix(job): expire stored client IPs of offline clients
ipStaleAfterSeconds was only applied while a row was being rewritten, and
rows are only rewritten for clients present in the current online scan. A
client that stopped connecting therefore kept its last addresses forever
in inbound_client_ips, and node_client_ips rows (including those of
deleted clients) were never revisited at all. Sweep both tables every five
minutes, dropping entries past the cutoff and deleting rows that end up
empty. The sweep runs ahead of the fail2ban and api-mode gates so
retention holds even on panels that collect nothing.

Closes #6286
2026-08-24 13:27:40 +02:00
Sanaei 2d30ab3ada fix(panel): stop one poisoned DNS answer from blocking outbound tests
SanitizePublicHTTPURL rejected a hostname as soon as any single resolved
address was blocked, so a resolver returning a bogon AAAA for the test URL
host (e.g. 2001::1 for www.google.com, inside the Teredo range blocked
since b51f0976) failed the outbound Check button outright — including TCP
mode, which never uses the test URL. Mirror SSRFGuardedDialContext instead:
one usable address is enough, because the guarded dialer skips blocked
answers at connect time; a hostname with nothing usable is still refused.

Closes #6290
2026-08-24 13:27:40 +02:00
Sanaei d175050f2e fix(job): force-disconnect over-limit Hysteria2 clients
disconnectClientTemporarily still gated on the protocol list from before
XrayAPI.AddUser learned hysteria, so an over-limit Hysteria2 client kept
its QUIC session until the fail2ban ban aged out, while a VLESS client in
the same situation was dropped at once. buildUserAccount handles hysteria
and model.Client already marshals the auth field the re-add needs, so admit
the protocol. wireguard stays excluded: its keepAlive marshals as a JSON
number, which the string-only user-field parsing rejects after the user was
already removed.

Closes #6256
2026-08-24 13:27:40 +02:00
Sanaei 7a595cb46d fix(sub): keep Hysteria2 mport on external-proxy links
genHysteriaLink only looked up the UDP hop range on the no-endpoint path,
after the externalProxy fan-out had already returned. An inbound with Hosts
therefore emitted per-host links without mport, so clients pinned themselves
to the single listening port and silently lost port hopping. Set the param
before the fan-out so every endpoint inherits it, matching the frontend
link builder and the Clash emitter.

Closes #6264
2026-08-24 13:27:39 +02:00
Sangeeth Thilakarathna f13baa9af5 fix(tgbot): split long messages at line boundaries (#6293)
Individual-link batches contain single line breaks, so the previous
blank-line-only pagination could send oversized replies unchanged.

Co-authored-by: sanmaxdev <sanmaxdev@users.noreply.github.com>
2026-08-24 13:03:37 +02:00
Kuzz007 9408424959 fix(panel): forward the panel's proxy to update.sh's own downloads (#6259)
* fix(panel): route update.sh's own downloads through the resolved proxy

startUpdate already fetches update.sh itself via a proxy-aware HTTP
client (NewProxiedHTTPClient), but the process that actually runs it
never got a proxy hint of its own -- so update.sh's own curl calls to
GitHub always went direct, even when the panel has a working proxy
path configured. This matters most for the systemd-run launch path,
which doesn't inherit the caller's environment at all (only --setenv
passes through), so a systemd host with a real ambient proxy would
silently lose it for this one hop.

curl already honors https_proxy/all_proxy natively, so no changes to
update.sh itself are needed -- only the launcher needs to forward a
proxy URL into the environment it hands to that detached process.

updateProxyEnvVars() prefers an already-set ambient proxy env var
(never silently overriding an admin's own proxy config) and only
falls back to the panel's own configured panel outbound
(PanelEgressProxyURL) when nothing is set, then forwards the result
to both launch paths.

* test(panel): cover updateProxyEnvVars' ambient-proxy path

Regression test for the fix in the previous commit -- an ambient
https_proxy must reach update.sh's own downloads, not just the
panel's own outbound requests. Scoped to the ambient-env branch only,
which never touches PanelEgressProxyURL/the database.

* fix: drop the panel-outbound fallback in updateProxyEnvVars

Per review: PanelEgressProxyURL() returns a loopback SOCKS bridge
living inside the panel's own Xray child. update.sh stops that child
partway through its run (systemctl stop x-ui, no KillMode override --
the default cgroup kill takes Xray with it) and removes the service
unit, but still needs curl afterwards for x-ui.sh and sometimes the
service unit itself. With the bridge dead, those downloads fail and
update.sh exits with no service unit installed and nothing to restart
it -- a host with a panel outbound configured and no ambient proxy
would be bricked by its next update.

Keep only the ambient-env-var forwarding, which is safe (an OS-level
var, not torn down when the panel dies), and fold in three smaller
fixes: forward no_proxy/NO_PROXY too, since install_base's apt/dnf
calls honor them; stop promoting a deliberately HTTP-only http_proxy
into https_proxy/all_proxy; and drop the now-redundant re-append on
the bash fallback path, which already inherits everything via
os.Environ().
2026-08-24 03:01:56 +02:00
Turan f204997c98 chore(i18n): update tr-TR translations (#6288)
Co-authored-by: tarihcituranx <tarihcituranx@users.noreply.github.com>
2026-08-24 02:47:45 +02:00
Kuzz007 effcccceac feat(amneziawg): add native AmneziaWG protocol support (#6105)
* feat(amneziawg): add native AmneziaWG protocol backend

AmneziaWG (WireGuard plus DPI-resistant obfuscation) needs no Docker
here — it runs as a genuine kernel interface via awg-quick/awg, managed
the same way internal/mtproto manages mtg: one Inbound row is one
desired Instance, and a Manager reconciles running interfaces toward
the database every 10s (internal/web/job/amneziawg_job.go) plus
immediately after a client edit (applyLocalAmneziaWG).

Clients reuse model.Client verbatim (the same PrivateKey/PublicKey/
PreSharedKey/AllowedIPs fields WireGuard already uses), so bulk
operations, the QR/share-link modal and subscriptions come from the
shared inbound infrastructure instead of a parallel implementation.
internal/amneziawg owns the obfuscation param generator/validator
(ported from coinman-dev/3ax-ui, upgraded to AmneziaWG 2.0's S3/S4
padding and I1 signature packet) and the exec wrapper around
awg-quick/awg, with fingerprint-based reconcile (noop / reload-via-
syncconf / full restart) mirroring mtproto.Manager so a same-protocol
edit doesn't force an unnecessary interface bounce that would drop
every peer's connection.

Frontend and install.sh's DKMS/awg-tools setup are tracked separately;
this is backend-only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): add frontend support and fix a Go->Zod generator gap

Wires the amneziawg protocol through the panel UI the same way every
other protocol is registered: a Zod settings schema (nested
{server, clients}, matching the Go JSON exactly), the protocol enum,
the inbound-form's per-protocol fields component and its
tab-visibility allowlist, the default-settings factory, the client
schema dispatcher, and the sniffing-capability exclusion (no Xray
inbound exists for amneziawg, same as mtproto).

Client key/allowedIPs fields are reused rather than duplicated: since
AmneziaWG clients are wire-identical to WireGuard clients (same
model.Client fields), ClientFormModal renders one shared field block
for both, switching only the visible label by which protocol is
active. The private-key input also gets a live public-key sync via a
new useEffect, because unlike WireGuard's Xray-native inbound (which
re-derives its public key at runtime and never stores one),
AmneziaWG's server.publicKey is a real persisted field the Go backend
reads directly — free-typing a new private key without this would
silently save a mismatched keypair.

Adds a downloadable per-client .conf (amneziawgConfig.ts, mirroring
wireguardConfig.ts) with the obfuscation lines, and an
InboundOption.AwgServer field on the Go side so the config builder
gets the full server block in one round trip.

Along the way, running tools/openapigen surfaced a real bug: it
doesn't flatten anonymously-embedded Go structs the way encoding/json
does, so ServerSettings embedding Obfuscation20 produced a Zod schema
with a nested `obfuscation20` key that never matches the real wire
JSON. Fixed by un-embedding (flat fields + an accessor method) and
registering internal/amneziawg in the generator's own package list,
which had been silently emitting a dangling schema reference.

English and Russian translations are complete; the other 10 locale
files still fall back to English for the new keys.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): complete frontend parity for the Inbounds list page

The Clients page (form, CRUD, QR/config) already worked from the
prior commit; this closes the remaining gap on the Inbounds side and
in a couple of protocol allowlists that a plain search for existing
wireguard/mtproto handling turned up.

lib/xray/inbound-link.ts gets amneziawg-specific link/config builders
(genAmneziaWGLink/genAmneziaWGConfig, plus the *s fan-out variants)
mirroring the wireguard ones — AmneziaWG has no legacy peers-array to
fall back to, so these read settings.clients directly and add the
obfuscation lines every client must share with the server. Wired into
genInboundLinks generically, and into three consumers that call the
wireguard builders directly rather than through that dispatcher:
QrCodeModal, InboundInfoModal, and InboundsPage's bulk export.

ClientInfoModal, ClientBulkAddModal, and the bulk attach/detach modals
each had their own protocol allowlist that needed amneziawg added
alongside wireguard/mtproto.

Two real gaps surfaced by grepping every remaining 'wireguard' /
Protocols.WIREGUARD hit in frontend/src rather than trusting the
checklist was exhaustive:
- useInbounds.ts's TRACKED_PROTOCOLS gates the deactive/depleted/
  expiring/online client counts shown per inbound on the list page;
  without amneziawg those counts would silently read zero.
- inbound-tag.ts is an explicit client-side mirror of the Go backend's
  port_conflict.go (the file says so itself: "Keep in sync"). It still
  only special-cased wireguard for UDP, so an amneziawg inbound would
  have fallen through to the TCP default and disagreed with the
  backend's own port-conflict math.

Also finishes translating the AmneziaWG UI strings into the 11 locale
files that were still falling back to English (ar-EG, es-ES, fa-IR,
id-ID, ja-JP, pt-BR, tr-TR, uk-UA, vi-VN, zh-CN, zh-TW), matching
en-US/ru-RU key-for-key (26 new keys, verified by count in every file).

Not run anywhere: npm run typecheck / build. This machine has neither
Node nor npm, so nothing here has compiled — reviewed by hand plus
brace/paren balance checks and cross-referencing the generated Zod/TS
types. Treat this as needing a real typecheck before shipping.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(install): note that AmneziaWG kernel module install is still manual

Tracked separately (not yet ported into this script) — see
coinman-dev/3ax-ui's install_amneziawg for the reference approach
(ppa:amnezia/ppa). Also serves as a real, path-filter-matching change
to get the previous empty commit's CI trigger to actually fire —
release.yml's push trigger is paths-scoped and an empty commit changes
no files, so it never matched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): add a button to randomize obfuscation parameters

Mirrors the existing key-regenerate button next to the private key
field. Client-side randomization matches the ranges/constraints of
GenerateObfuscation20's "default" preset (internal/amneziawg/params.go)
closely enough for a form suggestion — the user can still hand-edit any
field afterward.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(install): auto-install the AmneziaWG DKMS module + amneziawg-tools

Ports install_amneziawg from coinman-dev/3ax-ui's install.sh, adapted to
this script's broader distro coverage and NONINTERACTIVE convention:

- Ubuntu/Debian/Armbian: ppa:amnezia/ppa (primary, tested path), with a
  reachability pre-check for the Launchpad PPA host — often blocked by
  hosting providers, especially Russian VPS — so a flaky network skips
  the feature instead of hanging apt through several retries.
- Fedora/RHEL-family, Arch/Manjaro/Parch: best-effort fallback to plain
  wireguard-tools (+ AUR amneziawg-dkms via yay/paru when available),
  with a manual-install pointer.
- Everything else: manual-install pointer only.

Also installs ndppd and persists IPv4/IPv6 forwarding (for the future
IPv6/NDP phase, not yet wired into the panel) and adds a Secure Boot
warning at the end of the run, since a DKMS-built module is unsigned
and won't load while it's enabled — a common trap on cloud VPS images.

Never fatal: the panel installs and runs fine either way, an AmneziaWG
inbound just won't bring up its tunnel until the module is present.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): resolve all 3 real CI failures (typecheck/lint/codegen)

Found by checking the fork's Actions tab after the last two pushes —
the release build passed (it doesn't run these checks) but the
separate CI workflow caught three real issues:

- golangci-lint (noctx): every internal/amneziawg/manager.go exec.Command
  call is now exec.CommandContext with a 30s timeout, so a hung
  awg-quick/awg invocation can't block the reconcile job indefinitely
  (mirrors internal/mtproto/process.go's own CommandContext usage).
- tsc --noEmit: frontend/src/schemas/client.ts's hand-maintained
  InboundOptionSchema (used by the useClients hook, separate from the
  auto-generated one in generated/) never got an awgServer field added
  when the AmneziaWG frontend work was done — every read of
  inbound.awgServer.* in amneziawgConfig.ts was typing as {}. Added
  AwgServerOptionSchema, nested (not flattened like wg*) to match what
  amneziawgConfig.ts already expects. Also guarded server.publicKey in
  inbound-link.ts's genAmneziaWGLink against the schema's optional type.
- codegen staleness: frontend/public/openapi.json is produced by a Node
  script (gen:api) this machine can't run; hand-applied the exact diff
  the CI failure log already showed (amneziawg protocol enum entry,
  ServerSettings schema, InboundOption.awgServer, one example payload),
  verified as valid JSON.

Also confirmed independently by this run: install_amneziawg (previous
commit) installed and loaded the DKMS module successfully on both amd64
and arm64 CI runners. The two "Deploy Smoke Tests" failures are
unrelated to this change — this fork has only ever published the
dev-latest pre-release, and GitHub's /releases/latest API deliberately
excludes pre-releases, so the smoke test's no-argument install path
(which resolves "latest") has nothing to find. Not a regression; needs
an actual tagged release whenever that's wanted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): Phase 2a — IPv6 support + NDP proxy

Adds native dual-stack IPv6 to AmneziaWG inbounds, ported from
coinman-dev/3ax-ui's approach:

- ServerSettings gets ipv6Enabled/ipv6Subnet/ipv6ExternalInterface;
  Instance carries the server's own IPv6 address (first host of the
  subnet) alongside its IPv4 one.
- defaultAmneziaWGClients allocates an IPv6 host address per client
  (second AllowedIPs entry) when the server has IPv6 enabled, reusing
  allocateWireguardAddress — which needed a real fix along the way: it
  always suffixed "/32" regardless of address family, which is wrong
  for an IPv6 host address (needs /128). Now family-aware.
- generateServerConfig's PostUp/PostDown gains IPv6 forward-accept
  rules, proxy_ndp sysctl, and one `ip -6 neigh add/del proxy` entry per
  enabled peer with an IPv6 address — the lightweight per-client
  method, not the ndppd-daemon whole-subnet method (not worth the
  config-file-management complexity at this scale; ndppd itself is
  still installed by install.sh in case that changes later).
- ValidateIPv6Subnet rejects a malformed subnet before save.
- Frontend: ipv6Enabled/ipv6Subnet/ipv6ExternalInterface fields on the
  AmneziaWG inbound form, EN+RU translations, openapi.json/generated/*
  regenerated (the latter via `go run ./tools/openapigen`, pure Go).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): fill in IPv6 fields missed by the Phase 2a commit

Two real gaps the CI caught (both new fields, both my miss):

- inbound-defaults.ts's createDefaultAmneziawgInboundSettings() built a
  server object literal predating ipv6Enabled/ipv6Subnet/
  ipv6ExternalInterface — AmneziawgServer's inferred type now requires
  them (zod .default() fields are non-optional post-parse), so this
  didn't typecheck at all.
- openapi.json's ipv6Enabled property was missing the description the
  real generator attaches (the Go doc comment covering all three IPv6
  fields is attached to the first one) — a one-line diff, but git
  diff --exit-code doesn't care how small.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): Phase 2b — per-client port-forwarding

Admins can now set a per-client ForwardedPorts string (e.g. "80, 443,
8000-8100") that gets DNAT'd + FORWARD'd to that peer's tunnel address
via iptables rules in PostUp/PostDown, ported and simplified from
coinman-dev/3ax-ui's shared/portfwd.

Two decisions worth flagging for future readers:

- The iptables --comment tag on each rule is awg-fwd-<fnv32a(email)>,
  not the raw client email. Email is admin/API-supplied free text that
  ends up embedded in a shell-executed PostUp/PostDown line; a hash
  can never carry a shell metacharacter through where raw
  interpolation could.
- The reconcile manager gained a third fingerprint (portFwdFP, next to
  the existing structural/peers ones). `awg syncconf` only touches the
  WireGuard peer table — it never re-applies PostUp/PostDown iptables
  rules — so a port-forward-only change has to force a full
  awg-quick down+up bounce, same as a structural change, rather than
  the lighter sync a plain peer add/remove can use.

Also fixes a real pre-existing bug found while wiring up IPv6 client
allocation in the previous commit's spirit: allocateWireguardAddress
always suffixed "/32" regardless of address family, which produced
invalid host bits for IPv6 (needs "/128").

ForwardedPorts flows through model.Client -> model.ClientRecord
(gorm column wg_forwarded_ports, auto-migrated) -> ToRecord/ToClient/
MergeClientRecord, mirroring the awgServer field's earlier lesson
that new fields need checking against a second, hand-maintained
persistence-layer struct.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): route a client's traffic through Xray via the Routing page

Every enabled AmneziaWG inbound gets its own Xray TPROXY bridge
automatically, with no toggle to enable first: a loopback
dokodemo-door inbound (sockopt.tproxy) tagged with the AmneziaWG
inbound's own real tag, so it's already selectable in the existing
Routing page's inbound-tag picker — the same trick the mtproto
sidecar's own bridge already relies on (InboundService.GetInboundTags
is a plain, protocol-blind SELECT over every inbound row's tag, no
dedicated UI plumbing needed).

internal/amneziawg's defaultPostUpDown TPROXYs every peer's traffic
into that bridge unconditionally; the bridge's port is derived
deterministically from the inbound's id (EgressPortForInbound) so the
kernel-side reconcile loop and the Xray-config generator never need to
negotiate a runtime value between them.

injectAmneziawgEgress never generates a routing rule itself — whether
a client's traffic goes anywhere beyond Xray's default routing is
entirely up to whatever rules the admin adds through the existing
Routing UI (pick the AmneziaWG inbound's tag as source, optionally a
specific peer's IP via that page's own Source-IP field, and an
outbound), exactly the same workflow as routing any other protocol.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): recover orphaned interfaces after an ungraceful exit

Two gaps left an AmneziaWG interface stuck outside the manager's
control after a crash (kill -9/OOM/panic skips StopAll):

- ensureRestart's teardown was gated on the in-memory `exists` map,
  which is always empty on a fresh process, so a survived interface
  never got interfaceDown before interfaceUp tried `ip link add`
  against a name the kernel already had — failing forever and never
  populating m.ifaces, so traffic accounting silently stopped and the
  inbound could never be removed. Gate on isInterfaceUp instead, which
  checks real kernel state rather than this process's own bookkeeping.

- An inbound deleted from the database entirely while the panel was
  down has no entry in `desired` ever again, so it never reaches the
  per-id cleanup loop in Reconcile (which only walks m.ifaces). Add a
  one-time sweepOrphansLocked scan of configDir, mirroring
  mtproto.Manager.sweepOrphansLocked, that tears down and removes any
  leftover interface/config not in the current desired set.

Found by the automated review on MHSanaei/3x-ui#6105 (Finding 1).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* i18n(amneziawg): backfill IPv6/obfuscation/port-forwarding keys in 11 locales

Only en-US/ru-RU ever got these 9 keys as each AmneziaWG feature landed
(the regenerate-obfuscation button, then Phase 2a's IPv6 fields, then
Phase 2b's per-client ForwardedPorts) — the other 11 locale files were
never backfilled, so i18next has been silently falling back to English
for all of them since Phase 1. Cosmetic-only (never broke anything),
but now closed for every shipped locale.

* fix(amneziawg): resolve 7 Medium findings from the automated PR review

Each is independently reproducible; fixed together since one review pass
found all of them.

- manager.go: the shared "ip rule add fwmark" policy route had no
  existence check, so it duplicated in "ip rule show" on every interface
  bounce (which hostRulesFingerprint forces on any client add/remove/
  re-IP). Now checked via "ip rule list | grep -q ..." first. (Finding 2)

- params.go: ExternalInterface, IPv6ExternalInterface, and subnetIp/
  subnetCidr are interpolated unescaped into a shell-executed PostUp/
  PostDown line, but only obfuscation and the IPv6 subnet were validated
  before save. Added ValidateInterfaceName (a strict charset+length
  pattern) and ValidateSubnetIPv4 (netip.ParsePrefix), wired into
  normalizeAmneziaWGSettings. (Finding 3)

- amneziawg_job.go: IsAwgInstalled() existed but nothing ever called it,
  so a host without awg/awg-quick (the Docker image, RHEL, Arch, a failed
  install.sh PPA step) logged a reconcile failure every 10s forever. Now
  checked once an inbound actually needs it, warning once instead of
  spamming. (Finding 4)

- client_inbound_apply.go: the WireGuard/AmneziaWG credential
  carry-forward (added so a metadata-only client edit doesn't rotate
  keys) never covered ForwardedPorts, so a partial edit -- an API call or
  Telegram-bot toggle that omits the field -- silently wiped a client's
  port-forwarding spec. Carried forward and written back the same way the
  key fields already are. (Finding 5)

- manager.go: hostRulesFingerprint keyed each peer on its IPv4 address
  only, and structuralFingerprint omitted IPv6Enabled/IPv6ExternalInterface
  entirely, so an IPv6-only change could pick the syncconf reload path
  (which never re-runs PostUp, leaving a stale NDP-proxy entry) or be a
  complete no-op. Both fingerprints now cover the IPv6 fields. (Finding 6)

- port_conflict.go: the AmneziaWG egress bridge (injectAmneziawgEgress)
  binds 127.0.0.1:63100+id with no collision check anywhere, since it
  isn't a database row the ordinary port-conflict query can see -- same
  blind spot the reserved Xray API port already has its own check for.
  Added the equivalent check for the AmneziaWG bridge port. (Finding 7)

- install.sh: install_amneziawg ran unconditionally for every install/
  update, building a DKMS kernel module and enabling host-wide IPv4/IPv6
  forwarding whether or not the feature is ever used. Gated behind a new
  should_install_amneziawg (XUI_INSTALL_AMNEZIAWG=true/false, or an
  interactive y/N prompt defaulting to no). Also replaced the deprecated
  apt-key adv with a dedicated keyring + signed-by= on the Debian branch,
  and guarded its sources.list appends against duplication on a retried
  install. (Finding 8)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(amneziawg): make the Xray TPROXY bridge a per-inbound opt-in

Addresses Finding 10 from the automated PR review: an always-on TPROXY
bridge makes every AmneziaWG tunnel hard-depend on Xray being up (all
traffic, including DNS, drops whenever Xray restarts), and forces a full
awg-quick down+up bounce on any client add/remove/re-IP, permanently
losing the syncconf fast path.

Adds ServerSettings.RouteThroughXray (off by default):

- defaultPostUpDown only emits the TPROXY/policy-route rules when it's
  on; a plain AmneziaWG tunnel now has zero Xray dependency out of the
  box.
- structuralFingerprint covers it (toggling it changes whether PostUp/
  PostDown contain any TPROXY rules at all -- structural, not a
  per-peer host-rule). hostRulesFingerprint's IPv4 tracking is now
  itself conditional on RouteThroughXray (and IPv6 tracking on
  IPv6Enabled), so an instance that never uses either keeps the
  syncconf fast path for a plain peer re-IP.
- injectAmneziawgEgress only creates a bridge for inbounds that opted
  in; checkAmneziawgEgressConflict (the Finding-7 fix) now parses each
  candidate through InstanceFromInbound so a non-routed inbound's port
  is correctly never treated as reserved.
- New inbound-level Switch in the AmneziaWG form; the actual outbound
  decision is still made entirely through the panel's stock Routing
  page, same as before -- only whether the bridge exists at all is now
  a choice.

Translation keys added to all 13 locales in the same commit this time,
not backfilled later (see Finding 9's lesson).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): resolve 4 Low findings from the automated PR review

- manager.go: serverAddress assumed subnetIp always ends in ".0"; a
  base like "10.8.1.5" was used verbatim as the server's own address,
  eventually colliding with peer allocation (which starts at .2
  upward). Now derives the first host of the actual subnetIp/subnetCidr
  network via netip, matching serverAddressV6's own approach. A /32
  base (no host bits at all) is still used as-is. (Finding 12, partial
  -- the /16 pool-widening half of this finding only exists on the
  upstream-pr/amneziawg branch's merged client_wireguard.go, not here;
  handled separately on that branch.)

- manager.go: ensureLocked carried the previous per-peer traffic
  counters (`last`) forward even through a full restart, but
  awg-quick down+up resets the kernel's own counters to zero -- the
  next CollectTraffic computed a large negative delta (clamped to 0),
  silently discarding real traffic. Extracted the decision into
  nextTrafficBaseline: only a reload (syncconf) preserves the
  baseline. (Finding 13)

- portfwd.go: exported ForwardedPortsInclude; inbound_amneziawg.go's
  new checkForwardedPortsConflict uses it to reject, at save time, a
  client's forwardedPorts that would DNAT the panel's own port or
  another enabled inbound's port to the tunnel client --
  portForwardLines has no destination restriction, so this collision
  was previously silent. Wired into both the single-client update path
  and the add-client path (client_inbound_apply.go), plus
  normalizeAmneziaWGSettings for the whole-inbound save path. (Finding 14)

- inbound.go: InboundOption.AwgServer sent the whole ServerSettings
  struct including PrivateKey to GetInboundOptions callers -- a
  shared, admin-wide dropdown-filling endpoint the frontend's own
  AwgServerOptionSchema never reads that field from. Redacted it
  before assigning. (Finding 11)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): don't widen the peer address pool past AmneziaWG's own subnet

Completes Finding 12 from the automated PR review (the serverAddress half
of this finding was already fixed on main and cherry-picked here). This
half is specific to this branch: allocateWireguardAddress's /16
pool-widening fallback is an independent addition from upstream's own
main that this branch inherited during the cherry-pick rebase -- it
doesn't exist on the fork's own main at all, so this fix can't be
cherry-picked the normal way and is committed directly here.

Widening is safe for WireGuard's own Xray-native inbound (AllowedIPs
isn't tied to a strict kernel interface subnet), but AmneziaWG's kernel
interface Address is exactly the configured subnet -- an address
allocated from the containing /16 once the /24 fills up would be
silently unroutable. allocateWireguardAddress now takes an explicit
allowWidening bool: WireGuard's own caller passes true (unchanged
behavior), AmneziaWG's passes false (fails loudly on exhaustion instead).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(docker): note that AmneziaWG doesn't work in this image

Investigated: the image is Alpine-based, and AmneziaWG's own packaging
(DKMS module + amneziawg-tools) doesn't target Alpine/musl at all --
unlike the Debian/Ubuntu/Fedora/Arch paths install.sh already handles,
there's no package to apk add even with full host network/capabilities.
The panel already degrades gracefully (IsAwgInstalled() logs one warning
instead of retrying forever), so no code change is needed -- just made
the reason explicit at the point where a user would reach for cap_add/
network_mode to try to work around it.

* fix(sub): include amneziawg inbounds in subscription links

getInboundsBySubId's SQL protocol allowlist never had 'amneziawg' added,
so every AmneziaWG client was silently excluded from all three
subscription formats (plain/individual links, JSON, Clash) and from the
Telegram bot's QR/individual-link buttons, which fetch through the same
path. genAmneziaWGLink itself was already fully implemented and already
wired into GetLink's dispatch switch -- it just never got a chance to
run. Same bug shape as the earlier TRACKED_PROTOCOLS frontend gap: a
hardcoded protocol list one entry short.

Found while investigating whether the Telegram bot needed AmneziaWG-
specific client-management code -- it doesn't (the bot itself is fully
protocol-agnostic), but this is the actual root cause of "can't share
an AmneziaWG client's config via the bot."

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(inbound): enforce node-eligibility server-side, not just in the UI

Investigated multi-node interaction with AmneziaWG: the master's own
reconcile (DesiredAmneziaWGInstances) and Xray config generation
(injectAmneziawgEgress, the GenXrayInboundConfig protocol skip) all
correctly filter on NodeID IS NULL, so a node-assigned AmneziaWG (or
MTProto) inbound would never be managed by the master. But nothing
stopped one from being created that way: NODE_ELIGIBLE_PROTOCOLS
(frontend/src/pages/inbounds/form/InboundFormModal.tsx) only hides the
node picker client-side -- a direct API call could set nodeId on an
AmneziaWG inbound, which every node then reconciles as an ordinary
local inbound (nodes run the identical binary, full cron suite
included), leaving it running unmanaged and untracked by the master's
own AmneziaWG bookkeeping.

Added isNodeEligibleProtocol (inbound_protocol.go), mirroring the
frontend's allowlist, and enforced it in both AddInbound (the actually
exploitable path -- nodeId comes straight from the request) and
UpdateInbound (defense in depth; NodeID is already restored from the
stored row there before this check, so it mainly guards against a
protocol change on an existing node-hosted inbound).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): allow TPROXY-marked traffic through a default-deny INPUT chain

TPROXY never rewrites a packet's own destination address, only the routing
decision. A default-deny firewall whose INPUT chain sanity-checks "is this
destination actually local" (UFW's ufw-not-local, via addrtype --dst-type
LOCAL, is a concrete example) silently drops the redirected packet before
Xray's socket ever sees it -- RouteThroughXray looked fully configured
(TPROXY rule present and counting, Xray listening with IP_TRANSPARENT set)
yet every peer's traffic vanished with no trace on either side.

Adds an idempotent, never-torn-down "iptables -I INPUT 1 -m mark --mark
<fwmark> -j ACCEPT" alongside the existing shared policy route, so this
works regardless of which firewall manager owns the rest of the INPUT chain.

* fix(frontend): give AmneziaWG the same UDP tag and its own tag color

The Inbounds list only special-cased isWireguard/isHysteria for the "UDP"
network badge, so an AmneziaWG row showed just the bare protocol tag with
no transport badge next to it. Added the missing isAmneziawg flag (mirrors
isWireguard exactly) and wired it into the same branch.

Client-row protocol-color maps in ClientsPage/HostList had no amneziawg
entry, silently falling back to grey -- ClientInfoModal already had
amneziawg: 'yellow' from earlier work, these two just never got it.

* feat(logs): show which AmneziaWG client an access-log line belongs to

The dokodemo-door TPROXY bridge every AmneziaWG peer's traffic is routed
through has no per-user identity, so Xray's own access log never carries an
"email:" token for these lines -- the Access Logs modal showed a blank
Email column for every in-*-udp row, even though every other protocol's
rows show the client normally.

The peer's decapsulated tunnel IP does survive as the log's "from" address,
and that IP deterministically maps to exactly one configured peer. Builds a
"<inbound tag>|<ip>" -> email index from the same AmneziaWG inbounds already
parsed elsewhere (amneziawg.InstanceFromInbound), and fills in Email from it
whenever the raw log line didn't have one.

* fix(amneziawg): enable sniffing on the TPROXY bridge

Domain-based Routing rules could never match RouteThroughXray traffic: an
AmneziaWG peer resolves DNS itself, through the tunnel, before ever sending
a packet, so the decapsulated traffic TPROXY hands to the bridge is already
a bare destination IP with no domain name attached at the network layer.
Every other inbound recovers this via sniffing (confirmed working for the
stock wireguard inbound, which does have it configured); the bridge never
got a sniffing block at all, so only tag/IP/network-based rules could ever
match it -- any domain rule above it in the list was silently unreachable.

* docs: add an AmneziaWG config page and list it as a supported protocol

Closes the PR checklist gap: the feature shipped with zero mention on
the docs site. Mirrors reality.mdx's structure (key settings, setup
steps, config excerpt) and notes the Docker/multi-node/Telegram-bot
caveats the PR itself is honest about not having confirmed.

* fix: address the fresh review round on PR #6105 (8 findings)

1. hostRulesFingerprint didn't account for ForwardedPorts when
   RouteThroughXray was off, so re-IPing a peer with port-forwarding
   configured left stale DNAT rules pointing at an address the next
   peer could be handed.
2. Server/client config values (keys, email, I1) were never validated
   for control characters before being written into the generated
   .conf; a newline could smuggle a PostUp hook into awg-quick's
   parser. Added ValidateConfigValue at save time and a
   sanitizeConfigValue backstop at render time.
3. checkForwardedPortsConflict didn't scope to node_id IS NULL, so a
   port used only on a different node produced a false collision; also
   hoisted the panel-port/inbounds lookup out of the per-client loop
   (portConflictContext) so N clients cost one query, not N.
4. PostDown commands were ";"-joined and abort on the first failure;
   appendOrTrue makes teardown best-effort so an external firewall
   flush can't leave DNAT rules to accumulate across bounces.
5. The "ip rule list | grep -q" existence check could SIGPIPE under
   pipefail and re-add a duplicate rule; switched to grep -c >/dev/null.
6. Ported the vpn:// share-link format (base64url of the plain .conf
   text, matching the real AmneziaVPN app) onto this branch -- it had
   only ever landed on our own fork's main, so this PR branch was still
   on the old amneziawg://+query-params scheme our own docs no longer
   described. Also corrected the docs' install.sh claim (opt-in/
   interactive, not automatic) and stale pre-opt-in comments in
   route_egress.go.
7. install.sh: Arch's ndppd install used pacman -Syu (full system
   upgrade) instead of -Sy like every other call in the script; and
   should_install_amneziawg re-prompted on every `x-ui update` even
   when awg was already installed.
8. CollectTraffic could clobber a concurrent restart's freshly-reset
   (empty) traffic baseline with stale pre-restart counters, since
   getPeerStats runs lock-free; now checks pointer identity before
   writing back. sweepOrphansLocked permanently disabled itself on a
   transient os.ReadDir failure instead of allowing a retry.

go build/vet/test and frontend typecheck/lint/build/vitest all pass.

* fix(install.sh): check the live sysctl value, not sysctl.conf text

Reviewer feedback (cherts, PR #6105): grepping /etc/sysctl.conf for the
setting name is unreliable -- many distros split sysctl config across
/etc/sysctl.d/*.conf, and /etc/sysctl.conf can be a symlink into that
directory, so the check can miss an already-active setting (harmless
duplicate append) or match a disabled/commented line (forwarding
silently stays off). Query the live value via `sysctl -n` instead,
which is accurate regardless of which file set it. Applied the same
fix to both the IPv6 and IPv4 checks for consistency.

* fix: update inbound_amneziawg.go to the split buildInboundForLocalRuntime

Same fork-only-file blind spot as the one caught on our own main after
the 3.6.0 sync: upstream split buildRuntimeInboundForAPI into
buildInboundForNodePush / buildInboundForLocalRuntime (part of the
node-sync client-deletion fix, 5bc81dfd), updating every call site it
could see. This file doesn't exist upstream, so it kept calling the
old name even after the branch merged in that commit.

* fix(frontend): recognize AmneziaWG's vpn:// scheme in share-link labels

The shared link-tag/label helper (used by the client info modal, QR
modal, and subscription page) had no entry for the vpn:// scheme
AmneziaWG links use, so it fell through to the generic fallback: a
plain "Vpn" tag with no color, and an empty remark/port that made the
row's title fall back to "Link N" instead of the inbound's actual
name:port — unlike every other protocol, which shows its real tag and
label.

vpn:// links are base64url of a plain .conf text (matching the real
AmneziaVPN app's own share-link format), not a structured URL, so
there's no query string or #hash to read a remark/port from. Decode
the payload and pull the remark/endpoint back out of the .conf text
directly instead.

* fix(xray): force a full restart for TPROXY inbounds, never hot-add them

Real incident: an AmneziaWG inbound with RouteThroughXray enabled lost
all internet on that connection after a migration. Root-caused on the
live box -- iptables TPROXY counters were incrementing (packets
correctly redirected to 127.0.0.1:63110), but nothing was actually
listening there (ss showed nothing on that port) until a full
`systemctl restart x-ui`, after which the bridge came up immediately.

Xray-core's gRPC AddInbound reports success for a new sockopt.tproxy
inbound (internal/amneziawg's own Xray egress bridge is the only kind
this fork ever generates) but doesn't reliably bind a working listener
for it outside of process startup -- the bridge silently never comes
up, and RouteThroughXray traffic goes nowhere until the next full
restart happens to occur for an unrelated reason.

diffInbounds already has this exact defensive pattern for REALITY
inbounds ("a gRPC remove+add does not reliably rebuild the REALITY
authenticator"), just never extended to TPROXY, and only in the
already-existing-then-changed branch -- the "brand new inbound" branch
had no such guard at all, which is exactly the path a freshly-enabled
RouteThroughXray bridge takes. Added inboundUsesTproxy and wired it
into both branches.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): flag Xray for resync when a peer edit changes qualifying state

Real production bug, root-caused on iiadmin-vps: updateAmneziaWGInbound/
AddInbound/DelInbound only ever updated the kernel interface via
amneziawg.GetManager() -- they never called SetNeedRestart the way every
other protocol's mutation path does (client_crud.go, inbound.go, etc. all
do). injectAmneziawgEgress's TPROXY bridge inbound depends on
InstanceFromInbound finding at least one qualifying peer plus
RouteThroughXray, so an edit that flips that (first peer added, last one
removed, RouteThroughXray toggled on) previously required a full panel
restart before the bridge actually got created, with no error anywhere:
the kernel interface would handshake fine, but traffic redirected into the
bridge's TPROXY port went nowhere because nothing was listening there.

diffInbounds/inboundUsesTproxy already correctly force a full restart for
a brand new TPROXY inbound (bdee0a20) -- that part was never the bug. The
gap was entirely upstream: nothing ever told Xray a resync was even needed.

* fix(clients): reject AllowedIPs already used on another WireGuard/AmneziaWG inbound

defaultWireguardClients/defaultAmneziaWGClients only ever checked uniqueness
against their own inbound's client list, so two inbounds sharing a subnet
(same protocol or not) could silently hand out or accept the same address --
the exact scenario behind a real duplicate-IP incident where a WireGuard and
an AmneziaWG client both ended up on the same address. otherTunnelAllowedIPs
now collects every address already claimed on every other tunnel inbound and
folds it into both the auto-allocation pool and the manual-entry collision
check, naming the other inbound in the error when it fires.

* fix(frontend): add the missing AmneziaWG config download on the sub page

The subscription page already gave WireGuard links their own "Config"
block (copy/download/QR of the actual .conf, via wireguardConfigFromLink
reversing the wireguard:// query params) but had no equivalent for
AmneziaWG's vpn:// links -- its isWireguardLink gate never matched them,
and no reverse-parse helper existed for this page specifically. Every
other surface (InboundInfoModal, ClientInfoModal, ClientQrModal) already
had this parity; this was the one page that didn't.

Fixed by adding amneziawgConfigFromLink (inbound-link.ts), simpler than
its WireGuard counterpart since a vpn:// payload already *is* the plain
.conf text -- just base64url-decode it, no query-param reconstruction
needed -- and wiring it into SubPage.tsx alongside the existing WireGuard
block, reusing the same pages.clients.amneziaWgConfig label the other
three surfaces already use.

* fix(xray): force a full restart for password-auth SOCKS5 hot-apply

Real production incident: editing a client under an AmneziaWG inbound
left its embedded SOCKS5 relay's settings byte-different (a new account
list), and Xray's gRPC remove+add hot swap silently dropped the account
for a peer whose email contained non-ASCII characters -- its tunnel kept
handshaking fine but all its traffic got rejected at the SOCKS5 layer,
while every other peer on the same relay was unaffected. A full restart
(reading the same JSON straight from disk) always produced the correct
account list. socks isn't in userDiffableProtocols (that only covers
vless/vmess/trojan's clients+email shape, not accounts+user), so any
settings drift on this inbound fell through to the generic remove+add
path. Forces a restart instead, the same defensive choice already made
for REALITY and TPROXY -- scoped to auth:"password" specifically so the
other, noauth SOCKS5 bridges (panel/node/mtproto egress) keep the cheaper
hot path.

* Fix Attach reusing one identity's address across wg/awg inbounds

ClientService.Attach deliberately copies one identity's stored
AllowedIPs into every WireGuard/AmneziaWG inbound it's attached to
in the same call, so the same person gets the same tunnel address
on every protocol they use. Its loop calls addInboundClient once per
inbound, and each of those independently computes
otherTunnelAllowedIPs -- so by the second inbound in the batch, the
first inbound's just-written copy of this identity's own address
looked like a cross-inbound collision against itself.

Real production symptom this caused: detaching then re-attaching a
client to both wg and awg failed with "wireguard: allowedIPs entry
X is already used by a client on inbound 'awg' (#N)" -- the exact
address the identity is supposed to keep, rejected as if it belonged
to someone else.

Add a selfEmails exclusion to otherTunnelAllowedIPs and populate it
from the client(s) being processed at the one real call site. Safe
unconditionally: ClientRecord.Email is globally unique, so a match
can only ever be this same identity's own entry on a sibling inbound,
never a genuine different client's address.

Reproduced the underlying mechanism live (manual entry correctly
rejected as a cross-inbound collision; fresh auto-allocation
correctly avoided a used address) before writing the fix, to confirm
the guard itself works and the bug is specifically in how Attach's
per-inbound calls interact with it.

* Attach: allocate fresh when re-attaching with no active tunnel

The previous fix (82cc69f5) made Attach's own address-reuse
correctly not collide with itself across inbounds -- but it still
always reused an identity's stored AllowedIPs verbatim, even when
that identity currently has zero WireGuard/AmneziaWG attachments at
all. A real report from testing this live: an identity fully
detached from both its wg and awg inbounds, then re-attached, got
its old address back even though several lower addresses were free
-- because nothing about being fully detached ever cleared the
stored value Attach copies from.

Add hasTunnelAttachment, checked once against the identity's CURRENT
inbound set before Attach's loop runs: if none of its current
inbounds is WireGuard/AmneziaWG, clear the stored AllowedIPs so this
attach allocates fresh (matching what a brand-new client would get)
instead of resurrecting an address nothing reserves anymore. Left
alone when the identity already has an active tunnel elsewhere, so
extending it to a second protocol still keeps a consistent address.

* Fix TestOtherTunnelAllowedIPsExcludesSelfEmail's own test setup

CI caught this: the "genuinely different client" (other@wg) was
seeded onto the SAME inbound passed as excludeID, which
otherTunnelAllowedIPs already excludes entirely regardless of the
selfEmails fix -- so the assertion that its address is still
reported could never have passed, proving nothing either way. Move
it onto the sibling inbound alongside shared@id, which is what the
test actually needs to exercise (two clients on one sibling, one
excluded by email, one not).

* Attach: never inherit an address that doesn't fit the target inbound

hasTunnelAttachment (from the earlier fix, commit 51067f16) only
asked "does this identity have ANY tunnel attachment", treating that
as license to reuse its stored address verbatim on every inbound
being attached. Real production case this missed: an identity's
stored address came from WireGuard's own fallback subnet
(10.0.0.0/24, used when that inbound has no other clients to infer a
base from), then got attached to a second, AmneziaWG inbound
configured for a completely different subnet (10.8.1.0/24).
defaultAmneziaWGClients's already-set-AllowedIPs branch only checks
for collisions, never subnet membership, so the mismatched address
was accepted silently -- producing a peer that can never actually
connect, since an AmneziaWG address must fall inside the kernel
interface's own configured subnet to be routable at all.

Add addressesFitAmneziaWGInbound, checked per inbound inside Attach's
loop: if the inherited address doesn't fit the SPECIFIC inbound being
attached, clear it just for that one so it gets a fresh, valid
allocation instead, while other already-attached inbounds keep their
existing values. WireGuard has no equivalent strict subnet
requirement (allocateWireguardAddress can widen to a fallback pool
for it), so this only ever constrains AmneziaWG targets.

* Give WireGuard an explicit, admin-configurable subnet field

WireGuard previously had no configurable subnet at all -- only an
implicit one, either inferred from existing clients' own addresses
(wireguardAllocationBase) or a hardcoded 10.0.0.0/24 fallback when
none exist yet. AmneziaWG, by contrast, has always had a real
server.subnetIp/subnetCidr field in its settings, editable in the
UI. User request: give WireGuard the same treatment.

Backend: explicitWireguardSubnetBase reads an optional subnetIp/
subnetCidr pair from the inbound's own settings JSON (mirroring
AmneziaWG's defaultAmneziaWGSubnetBases). defaultWireguardClients
checks it first; only when unset does it fall back to today's
inference-from-existing-clients behavior, so an inbound saved before
this field existed keeps working exactly as it always has.

Frontend: subnetIp/subnetCidr added to WireguardInboundSettingsSchema
and the inbound form (mirroring AmneziaWG's own field layout/labels),
with a real default (10.0.0.0/24, the same value the backend already
fell back to) seeded for newly created inbounds so the field starts
populated and editable rather than blank. Translated across all 13
locales.

This also structurally closes the class of bug fixed in
82cc69f5/291c47b3: with wg and awg subnets explicit and
independently controllable, an admin who wants matching addresses
across both protocols can configure them to actually agree, instead
of one silently inheriting the other's incompatible range.

* Split the client edit form's AllowedIPs into per-protocol fields

A client attached to both WireGuard and AmneziaWG shared one AllowedIPs
form field with a dynamically-switching label, so its two genuinely
different addresses could never both be shown or edited correctly.
Worse, Update/Create broadcast that one shared value to every attached
wg/awg inbound with no subnet-fit check, so an ordinary edit save could
silently overwrite one protocol's address with the other's -- the same
bug class already fixed for Attach, but reachable from any client edit.

model.Client gains an optional AllowedIPsByInbound map so a caller can
send distinct values per inbound; Update/Create honor it and, when it's
absent, clear a shared value that doesn't fit an AmneziaWG inbound's own
subnet instead of writing it through. A new TunnelAllowedIPsByInbound
read path feeds the real per-inbound address to the client edit form via
GET, which now renders two separate, correctly-labeled fields whenever
both protocols are attached (unchanged single dynamic field otherwise).

* Regenerate openapi.json for the new allowedIPsByInbound field

Follow-up to 878ee839: gen:zod (frontend/src/generated) was already
regenerated and committed, but gen:api (frontend/public/openapi.json)
wasn't, so CI's codegen drift check failed.

* Fix build breakage from merging upstream main: Update() gained a limitHwid param

Two of our own AllowedIPs tests (not present upstream, so the merge never
flagged them as conflicting) still called the old 3-arg Update(inboundSvc,
id, client) -- upstream's hardware-ID-limit feature added a required
limitHwid parameter that every other caller in this package already
passes. Also drop createDefaultInboundSettings from InboundsPage.tsx: the
merge conflict resolution kept the import, but upstream's clone-payload
refactor (buildClonePayload, inbound-clone.ts) already calls it
internally now -- this file doesn't need it directly anymore.

* Fix real bug: AmneziaWG clients rejected as "empty client ID" in 3 places

Three switch statements on inbound.Protocol handle "wireguard" explicitly
(checking client.PublicKey) but fall through to the default case for
"amneziawg" (checking client.ID, which AmneziaWG clients never set --
they use PublicKey/Email like WireGuard, not the VMess/VLESS UUID field).
This is what the 4 AllowedIPs tests were actually catching:
UpdateInboundClient's newClientId derivation hit this same default branch,
so every Update() on an AmneziaWG client returned "empty client ID"
before ever reaching the AllowedIPs logic being tested.

Fixed by adding "amneziawg" alongside "wireguard" in each switch:
addInboundClient's per-client validation, UpdateInboundClient's
newClientId derivation, and AddInbound's per-client validation (the
third one wasn't hit by these tests, but has the identical bug -- creating
a brand-new AmneziaWG inbound with a client attached would fail the
same way).

* refactor(amneziawg): rename Obfuscation20 to Obfuscation31, drop the dead mobile preset

Mechanical rename ahead of the AmneziaWG 3.1 parameter work: the type,
generator and prose all said 2.0, and the "mobile" generator preset was
reachable only from its own test. No behavior change.

* feat(amneziawg): AmneziaWG 3.1 obfuscation parameters (backend + generated schemas)

Adds the 3.1 parameter surface to the inbound settings and both Go config
emitters: I2-I5 signature packets, HeaderProtectionKey (base64 32-byte,
shared server<->client), ContentPaddingAddition, the five handshake-timing
randomization ranges (RekeyAfterTime/RekeyTimeout/RejectAfterTime/
KeepaliveTimeout/MaxHandshakeAttempts), and the RandomTrailers/
DisableCookies switches. Freshly generated sets fill everything except
I2-I5 (matching Amnezia's own generator) with jittered ranges bracketing
WireGuard's stock timing constants; every reject window starts >= 30s
above the rekey window by construction. Empty fields stay off the wire,
so blanking a field disables just that feature.

Validation generalizes the H1-H4 range checker for the new uint32-range
fields, requires min 1 on timers, cross-checks rekey-vs-reject, and
demands a real 32-byte base64 header-protection key. The manager warns
once per process when the installed awg tools predate 3.1 but an inbound
uses 3.1 parameters (awg-quick rejects unknown keys with a generic
error otherwise); apply still proceeds.

Requires amneziawg-tools v3.1.20260812+ / module or amneziawg-go
v3.1.20260814+ on the host.

* feat(amneziawg): emit and randomize 3.1 parameters in the frontend

Both client-config emitters (the vpn:// link builder and the clients-page
.conf builder) now carry the 3.1 [Interface] lines in the same order as
the Go emitters. The obfuscation randomizer moves out of InboundFormModal
into a shared lib/xray/amneziawg-obfuscation.ts that also fills the new
fields, and createDefaultAmneziawgInboundSettings switches from static
values to that generator — a fresh inbound now really gets the unique
fingerprint the docs promise instead of the same jc=5/jmin=10 set on
every install.

Schema parse-time defaults for the new fields stay ''/false on purpose:
real values come only from the generator, so resaving an inbound never
mutates its stored parameters. A new parity test pins the hand-written
AmneziawgServerSchema to the generated ServerSettings key set, so a field
added on one side can no longer silently vanish from configs.

* feat(amneziawg): 3.1 form fields and translations

Inbound form gains inputs for I2-I5, HeaderProtectionKey (filled by the
existing obfuscation Regenerate button), ContentPaddingAddition, the five
timing ranges, and the RandomTrailers/DisableCookies switches; the MTU
input picks up the min=1 its schema already enforced. All 13 locales get
the 19 new keys and drop the "2.0" branding from the s3/s4/i1 labels.

* docs(amneziawg): document 3.1 parameters; install.sh kernel/version notes

The AmneziaWG page's obfuscation section moves from the 2.0 to the 3.1
parameter set: table rows for I2-I5, HeaderProtectionKey,
ContentPaddingAddition, the timing-randomization ranges and the
RandomTrailers/DisableCookies switches, a requirements callout (tools
v3.1.20260812+, module/awg-go v3.1.20260814+, Linux 6.7+ for the DKMS
path), and a sample client .conf that matches what the panel actually
emits (including the DNS defaults and PersistentKeepalive it always had).

install.sh warns before a DKMS build on a pre-6.7 kernel and after any
install that left pre-3.1 amneziawg-tools on PATH.

Also updates the hosts API operation paths ({id} -> {groupId}) in the
stale ru/zh/fa reference pages: syncing docs/public/openapi.json for the
new AmneziaWG schema fields surfaced that rename, which had never been
copied over, and the docs build fails on paths missing from the spec.

* fix(amneziawg): reject control characters and canonicalize 3.1 range values

Adversarial review of the 3.1 work surfaced a validation gap:
base64.DecodeString silently ignores CR/LF, so a header-protection key
that picked up a line wrap in transit decoded to a valid 32 bytes,
passed validation, and was emitted verbatim into every client config —
where the orphan second line breaks the import while the server (whose
emitter strips control chars) keeps running with the correct key. The
key and range validators now reject control characters outright.

Also from the same review: range values are canonicalized on save
("110 - 140" -> "110-140", whitespace-only collapses to feature-off,
closing a case where the server conf rendered an invalid blank-value
line the client emitters omitted); the rekey/reject invariant is now
enforced against WireGuard's 120s/180s defaults when only one side is
set; and the structural fingerprint joins on "\n" instead of "|",
which is a legal I1-I5 character and made adjacent free-text fields
join-ambiguous.

* fix(install): resolve latest release tag via web redirect to dodge API rate limits

The non-interactive install smoke test resolved the release version through
the unauthenticated GitHub API (api.github.com/.../releases/latest), which
allows only 60 requests/hour per IP. The test installs twice in one run, and
on shared CI runner IPs the second call gets rate-limited, returns no
tag_name, and install.sh treats an empty version as fatal (exit 1) — the same
"Failed to fetch x-ui version" real users hit behind CGNAT/shared addresses.

resolve_latest_tag() now reads the tag from the github.com releases/latest
web redirect (not subject to the API rate limit), falling back to the API
only if the redirect yields nothing. Verified with the real
deploy/test/smoke-noninteractive.sh (two installs, both green).

* fix(amneziawg): three review findings on #6105, plus a comment trim

1. A peer's allowedIPs reached the generated .conf unvalidated and
   unsanitized, unlike email/publicKey/preSharedKey which
   normalizeAmneziaWGSettings already guards. A newline in an entry let a
   following "[Interface]" re-open the interface section, whose "PostUp = ..."
   awg-quick then runs as root on the next apply. Reproduced end to end
   against generateServerConfig. The save path now rejects and canonicalizes
   through normalizeWireguardAllowedIPs, and the render path sanitizes as a
   backstop for rows predating the validation (an upgrade, a restored backup,
   a direct DB edit). H1-H4 get the same render-time sanitize, and the two NIC
   name fields a plausibility check, since stripping control characters alone
   would still let a shell metacharacter into a root-executed PostUp line.

2. EgressPortForInbound is 63100 + inbound id, so an id past 2435 derives a
   port above 65535 -- and Xray rejects the whole generated config over one
   invalid port, taking every other protocol down with it. It now reports
   ok=false past the range, and both the Xray bridge and its TPROXY rules are
   skipped instead of emitting an impossible port.

3. The downloadable AmneziaWG .conf read ClientRecord.allowedIPs, a single
   shared column that holds the WireGuard address for an identity attached to
   both protocols -- the exact ambiguity tunnelAllowedIPs was added to resolve
   for the edit form. The info and QR modals already hydrate that field, so
   they now pass this inbound's own address to the builder.

Also trims the comment blocks in the files touched here to the 2-line
guidance in CLAUDE.md: internal/amneziawg alone carried 423 comment lines in
over-long blocks against 118 for the comparable internal/mtproto, and is now
at 110. Every non-obvious constraint is kept (the kernel S1/S2 rule, why
PostDown is best-effort, why grep -c and not -q, why the fingerprints split
three ways); the narration is gone. Two hot_diff.go comments pointed at an
internal/amneziawgnet package and an injectAmneziawgnetSocks function that
exist nowhere in the tree; the checks themselves are unchanged.

* feat(logs): add an AmneziaWG log view to the overview

The overview has an access-log view for Xray but nothing for AmneziaWG, so
when a tunnel misbehaves there is no way to see it from the panel at all. A
kernel tunnel logs no per-request lines, so the equivalent view is built from
the two things it does expose:

- Live per-peer activity from `awg show <iface> dump`, joined to the client
  email through the desired peer set: last handshake, endpoint, allowed IPs,
  cumulative transfer and online state, newest handshake first.
- The panel's own AmneziaWG event lines (interface up/down, awg-quick
  failures, the pre-3.1 tools warning), which are what actually explain a peer
  being absent from the table.

POST /panel/api/server/amneziawglogs/:count serves both, with the same
count + filter contract GetXrayLogs uses, and the modal mirrors XrayLogModal's
toolbar, auto-update, mobile cards and download. The action-bar button is
gated on a new status.amneziawg.configured, which stays true while an inbound
exists but its interface is down -- exactly when the event lines matter.

Verified against a running panel: the endpoint returns the peer table and
real event lines ("awg/awg-quick not found on PATH", "create config dir:
permission denied"), and count and filter both narrow as documented.

One of those lines surfaced a Debugf that had been rendering as
"for inbound1:amneziawg:"; fixed here since it is now user-visible.

* fix(amneziawg): stop double-counting a routed inbound's traffic

injectAmneziawgEgress tags its Xray bridge with the AmneziaWG inbound's own
tag, so the stock Routing page can target it. Xray therefore reports that
bridge's bytes under the inbound's tag, and XrayTrafficJob feeds them to
AddTraffic -- which accumulates -- on top of the same bytes AmneziaWGJob
already reported from `awg show dump`. An inbound with routeThroughXray on
counted roughly twice its real traffic, which also inflates the quota checks
that read the same counters.

The awg counters are the complete measure: every peer, whether or not TPROXY
routed it, and the same wire bytes the per-client totals are built from, so
they stay and the Xray rows are dropped. Per-client stats were never affected
-- a dokodemo-door bridge has no per-user identity, so Xray emits no
user>>>email rows for it.

Filtering happens before every consumer, so the DB totals, the external
traffic inform and the dashboard's live speed all read one source per inbound.
The set of bridge tags now comes from a predicate shared with
injectAmneziawgEgress itself, with a test that pins the two together -- naming
one tag too few doubles the traffic again, one too many makes real traffic
vanish.

* fix(amneziawg): align the three .conf emitters on one peer field order

The panel builds an AmneziaWG client .conf in three independent places, and
they disagreed: buildAmneziaWGClientConfig put PresharedKey right after
PublicKey (wg-quick(8)'s own order, and what both WireGuard emitters on the
clients side already use), while genAmneziaWGConfig and the Go
amneziaWGConfigText put it after Endpoint. A user comparing a subscription
link against a downloaded .conf sees the difference immediately, and the
generators are exactly the kind of parallel implementation CLAUDE.md warns
about drifting.

Moves the two outliers onto the wg-quick order. Also drops the stray trailing
newline that only appeared when PersistentKeepalive was set, so a config now
always ends on its last set field whichever that is -- the same shape all
three emitters produce for the same client.

Parsing is unaffected either way (the format is order-insensitive, and the
AmneziaVPN app reads it as a flat key-value bag), so this changes only the
rendered text. Adds a test on each side that pins the peer block's field
order, since nothing previously asserted it.

* refactor(amneziawg): switch to the embedded amneziawg-go/gVisor architecture

Replaces the kernel-module (DKMS) + awg-quick + TPROXY backend with the
fork's own embedded design: amneziawg-go runs in-process over a userspace
gVisor netstack, and each peer's decapsulated traffic relays into its own
loopback Xray SOCKS5 inbound, so Xray's native stats/sniffing/routing work
for free instead of through hand-rolled bridges. No kernel module, no DKMS,
no Secure Boot conflicts, works the same in a container as on bare metal.

- internal/amneziawgnet: new package (Device/UAPI, gVisor netstack, TCP/UDP
  forwarding, SOCKS5 relay, peer identity, IPv6 host-alias egress identity,
  per-client port-forwarding) - amneziawg-go v3.1.20260814 + gvisor.
- internal/amneziawg: keep the reusable protocol-shape types/validation
  (Instance/Peer/Obfuscation, InstanceFromInbound); drop the OS-shellout
  half (awg-quick, TPROXY policy routing, NDP proxy, peer-stats parsing).
- internal/web/service: rewire the 5 integration points (job, runtime,
  client-apply, web shutdown, xray config) from the old manager to the new
  one; the AmneziaWG log view is rebuilt on the embedded Device's own UAPI
  dump (extended to carry endpoint/AllowedIPs) instead of `awg show dump`.
- install.sh: drop DKMS/ndppd/TPROXY/Secure-Boot installer code (~250
  lines) - an entire recurring class of installer fragility goes away.
- frontend: drop the now-meaningless routeThroughXray toggle (the relay is
  always on); keep the field in the Zod schema, unexposed, so it isn't
  silently stripped from stored settings on next save - two regression
  tests deliberately depend on the Go struct still carrying it.
- docs/i18n: rewrite amneziawg.mdx for the new architecture; drop the
  dead routeThroughXray translation keys across all 13 locales.

Real production throughput (embedded core datapath, isolated bench, same
box the kernel-module path was measured on): ~296 Mbit/s up, ~640 Mbit/s
down, vs. 414.69 MB/s (~3.3 Gbit/s) for the kernel module on the same
hardware - a real gap, tempered by this being single-stream/no-SOCKS5-hop
and most VPN traffic being latency-bound rather than throughput-saturating.

* fix(amneziawg): restore the branch's own Obfuscation31 shape + 2 CodeQL findings

The previous push's wholesale-copy of types.go/params.go from the fork's
main branch pulled in that branch's own independent (and incompatible)
naming for the same AWG 3.1 feature set: Obfuscation20/GenerateObfuscation20
instead of this branch's already-shipped Obfuscation31/GenerateObfuscation31,
and a missing CanonicalizeUintRange -- broke every Go CI job (the whole
matrix fails to compile when any one package doesn't, which is why govulncheck/
golangci/postgres-durable-first/race all failed identically, not just go-test).

Restores params.go/params_test.go verbatim from this branch's own last
commit (a strict superset of validation: it already cross-checks rekey vs.
reject timing windows, which the copied version never did) and folds the
3.0/3.1 fields (HeaderProtectionKey, ContentPaddingAddition, the 5 timing
fields, RandomTrailers/DisableCookies) into Obfuscation31 itself, matching
the original struct exactly instead of as separate top-level Instance
fields. instance.go, the two amneziawgnet call sites, and 7 amneziawgnet
test files updated to match. Also drops the one test (sanitizeConfigValue)
that only ever served the retired kernel-module .conf writer -- correctly
not ported, so the test testing it shouldn't have been copied either.

Also fixes 2 CodeQL findings the same push surfaced: a clamped uint64->int64
conversion for the new log view's live byte counters (server.go), and an
unneeded len+len sum feeding a slice pre-size in the v6-egress outbound
merge (xray.go) -- append already grows correctly without it.

* chore(amneziawg): regenerate frontend schemas for updated doc comments

npm run gen was missed after the previous commit's types.go doc-comment
edits (Obfuscation20 -> Obfuscation31, ValidateHeaderProtection ->
ValidateObfuscation in the prose) -- openapigen bakes those comments
into the generated schema's description field, so the committed
frontend/src/generated/schemas.ts and openapi.json still had the old
wording. codegen's git-diff-exit-code check caught it correctly.

* fix(amneziawg): narrow 2 test fixtures that collided with MaxForwardedPorts

TestCheckForwardedPortsConflict_CollidesWithEnabledInboundPort and
..._NoCollisionWhenPortsDontOverlap used "8000-8100"/"9000-9100" as their
ForwardedPorts fixture -- 101 ports each, one over MaxForwardedPorts (100).
The cap check (checkForwardedPortsConflict, added this session alongside
the SOCKS-phantom-port check) fires first, so both tests got "more than
100 forwarded ports" instead of ever reaching the collision logic they're
actually testing. The cap itself has its own dedicated boundary test
already; these two just needed a narrower range that still covers/misses
port 8080 as intended -- 8075-8085 and 9075-9085, 11 ports each.

* fix(amneziawg): checkAmneziawgnetSocksConflict had no receiver in its new home

My merge-conflict resolution kept this as a method call (s.checkAmneziawgnetSocksConflict)
inside checkPortConflictTx, a plain function with no *InboundService receiver --
upstream's #6225 fix moved the port-conflict check out of the (s *InboundService)
method and into this new tx-scoped free function, and I didn't notice the call
site needed to change shape too. CI caught it immediately (undefined: s); nothing
in this specific package can be locally verified past internal/database's own
unrelated, pre-existing CGO build issue on this dev machine.

Since the signature had to change either way, folded in the fix already flagged
as a separate follow-up: checkAmneziawgnetSocksConflict now takes the caller's
db handle instead of fetching its own via database.GetDB(), so it actually runs
inside the same serialized transaction #6225 introduced -- previously it sat
right next to that race fix without benefiting from it.

* fix: address the review findings on the embedded AmneziaWG PR

5 blocking findings:

- Floor S3/S4 at 12 in both obfuscation generators (Go and frontend) and
  reject a hand-edited value below that when HeaderProtectionKey is set --
  IpcSet requires it, and ~39% of previously-generated sets violated it
  silently.
- Guard PrivateKey/PrimaryDNS/SecondaryDNS/remark against newline injection
  in the AmneziaWG .conf builder (both the Go subscription-link path and
  the frontend downloadable-config path) -- unguarded, any of them could
  inject an arbitrary config line into a subscriber's client.
- Bound the derived AmneziaWG SOCKS relay port to <= 65535 once an
  inbound's id is known, and check the reverse direction (does the relay
  port collide with an existing inbound's port) on both create and update
  -- previously only port -> relay collisions were checked, not relay ->
  port.
- Gate injectAmneziawgV6Egress on the same V6AliasesActive predicate
  desiredV6Aliases already uses, so the two can't disagree about whether a
  peer's IPv6 identity is actually active at the OS level.

2 minor findings:

- Fix the forwarded-ports cap check's off-by-one (a spec covering exactly
  the cap was rejected as if it were over it).
- Correct docker-compose.yml's stale comment describing the retired
  DKMS/kernel-module architecture.

* chore: retrigger CI

build (armv5) failed on a transient Go module proxy network error
(INTERNAL_ERROR stream reset on sagernet/sing), unrelated to this PR's
changes.

* docs: fix doc comments still describing the retired DKMS/awg-quick design

A few doc comments (and one illustrative test log line) survived the
embedded-architecture cutover unchanged and now contradict the code
they sit next to:

- internal/amneziawg/types.go's package comment claimed this package
  still owns a Manager that reconciles OS-level interfaces via
  awg-quick/DKMS -- that Manager was removed; the reconcile loop lives
  in internal/amneziawgnet now, and this package is protocol-shape-only.
- internal/amneziawg/params.go's ValidateObfuscation/ValidateConfigValue
  comments cited "awg-quick up" / "awg-quick executes as root" as the
  reason to validate -- the server itself never calls awg-quick in this
  architecture; the same value still reaches a real rendered .conf that
  a client app or an admin's own awg-quick CLI applies downstream, so
  the validation is still warranted, just for a different consumer.
  Mirrored the same fix in inbound_amneziawg.go's matching comment and
  its test's comment.
- internal/amneziawgnet/manager.go's Manager doc comments (x3) pointed
  readers at "internal/amneziawg.Manager" for comparison -- that type no
  longer exists in this diff at all. Repointed at internal/mtproto.Manager,
  the pattern this was actually modeled on and the one that's still real.
- Swapped one test's illustrative "awg-quick up awg2 failed" log line for
  a message shaped like this architecture's actual amneziawgnet logging,
  so a reader skimming the test doesn't wonder whether the server still
  shells out to awg-quick.

No behavior change.

* fix(docs): re-run codegen for xray-settings.mdx after conflict merge

The automated conflict-resolution hand-merge for this generated file
was content-correct but didn't byte-match a real regen (different
YAML long-string folding style). Re-ran npm run gen + docs' gen:api
and kept that canonical output instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(amneziawg): drop the dead access-log email backfill

amneziawgEmailIndex keyed peers by "<tag>|<tunnel IP>", a scheme built
for the retired TPROXY bridge where the peer's decapsulated tunnel
address survived as the access log's from-address. The embedded
architecture relays through a loopback SOCKS5 dial, so every AmneziaWG
log line's from-address is 127.0.0.1:<ephemeral> and the lookup could
never match: the index was rebuilt on every log view just to miss.
Remove the index, its GetXrayLogs wiring and its test. If per-line
emails are wanted back, the relay would have to publish a
local-port->email registry for the viewer to resolve loopback sources.

* fix(api): generate AmneziaWGLogs/PeerActivity schemas instead of hand-writing them

The amneziawglogs endpoint's response structs were missing from
openapigen's StructAllow, so they were silently absent from every
generated schema/example, the endpoints.ts entry carried a hand-written
response, and AmneziaWGLogModal.tsx duplicated the shapes as local
interfaces - the exact drift the allowlist rule exists to prevent.
Allowlist both structs with example tags, point the endpoint at the
generated schema, import the generated types in the modal, and sync
docs/public/openapi.json.

* chore(amneziawg): drop the unreferenced quiccapture package

Nothing imports internal/amneziawg/quiccapture and no route exposes it;
its package doc justifies the code as a port of
frontend/src/lib/xray/i1Generators.ts, which does not exist in this
repository, and promises an API round-trip that also does not exist.
1,110 lines of unreachable code with misleading provenance claims.
Revert this commit to bring the package back when the live-capture I1
feature and its frontend counterpart actually land.

* fix(clients): re-run cross-inbound conflict checks on the serialized writer

The new client-level checks - cross-inbound AllowedIPs collisions and
AmneziaWG forwardedPorts conflicts - read a fresh DB snapshot, decide,
and only then enter runSerializedTx, while lockInbound only serializes
writers on the SAME inbound. Two concurrent client creates on two
different tunnel inbounds both passed the read and both committed,
yielding two peers with one address: the exact check-then-claim race
81cfd857 (#6225) closed for AddInbound, which this PR's own
checkAmneziawgnetSocksReverseConflict already cites. Keep the pre-tx
pass for fail-fast UX and re-validate inside the transaction, where the
single writer makes the answer authoritative. The race test drives two
goroutines at two inbounds and demands exactly one winner; it fails
with committed=2 when the in-tx re-check is removed.

* fix(amneziawg): hot-apply depletion disables like mtproto does

applyTrafficMutationBatch special-cases MTProto so a quota/expiry
depletion cuts the sidecar immediately, but AmneziaWG fell through to
runtime AddUser/RemoveUser - explicit no-ops for this protocol - so a
depleted peer kept tunneling until the next 10s reconcile tick. Route
it through applyLocalAmneziaWG, whose own contract (re-read committed
settings, filter depleted clients, push to the interface) is exactly
this case; the comment claiming it mirrors applyLocalMtproto is now
true for the depletion path too.

* fix(amneziawg): persist cleared DNS fields instead of resurrecting defaults

PrimaryDNS/SecondaryDNS marshaled with omitempty, so clearing them
persisted settings with no key at all - and the frontend re-parses
stored settings through a Zod schema whose .default('8.8.8.8') /
.default('8.8.4.4') fire on missing keys, silently repopulating the
form on every load and re-persisting the defaults on the next save.
Blank is a documented, meaningful state (no DNS line in client
configs); drop omitempty so a cleared value survives the round-trip.
The regression test normalizes a server block with cleared DNS and
fails when the keys are dropped.

* fix(amneziawg): accept cleared numeric obfuscation/subnet fields in the form

AntD InputNumber emits null when cleared, Zod .default() only replaces
undefined, and unlike wireguard.ts - whose optionalClearedInt comment
documents exactly this failure mode - the AmneziaWG schema declared
subnetCidr and jc/jmin/jmax/s1-s4 as bare z.number() defaults. Clearing
any of the eight fields made safeParse reject the null and block the
save until the user retyped a value. Absorb null into undefined while
keeping each field's schema default, so a cleared field refills its
documented default and legacy blobs with absent keys behave as before.

* fix(amneziawg): guard the third .conf emitter against newline injection

The review-round fix added the newline guard to amneziaWGConfigText (Go)
and buildAmneziaWGClientConfig, but genAmneziaWGConfig in inbound-link.ts
- the third of the three emitters its own comment says must not drift -
still rendered privateKey/primaryDns/secondaryDns/remark unescaped, so a
newline there injected a config line (e.g. a rogue PostUp) into the
inbound form's downloaded .conf. Add the same guard, plus the regression
tests the original fix shipped without: all four fields on the Go and
both frontend emitters go red if any guard is removed.

* test(amneziawg): pin the S3/S4 floors the TS drift guard claims to mirror

The test's docstring says it mirrors internal/amneziawg/params_test.go,
but it asserted S3>=8/S4>=4 while the Go test and both generators pin
12/12 - the floor ValidateObfuscation enforces whenever a header
protection key is set, which this generator always sets. A regression
narrowing the TS floors into 8-11/4-11 would have passed the drift
guard and produced configs the backend rejects on save.

* docs: restore the pia repo-map entry and document the AmneziaWG subsystem

Merging main dropped CLAUDE.md's internal/pia/ bullet (added by #6272)
while resolving the repo-map conflict - the package itself is untouched.
Restore it, add the missing map entries for the two packages this branch
introduces (internal/amneziawg/, internal/amneziawgnet/), bump the cron
count, and give amneziawg_job its row in architecture.md's 5.4 table.

* chore(amneziawg): correct comments stranded by the architecture pivot

ae77c7e9's cutover to the embedded gVisor path deleted the kernel-module
code but left several comments describing it in the present tense:
hot_diff.go cited the removed service.amneziawgEgressStreamSettings and
wrongly claimed AmneziaWG is the only sockopt.tproxy source (tunnel's
TProxy mode is the live one the guard protects), socks_config.go pointed
at the deleted EgressBasePort/EgressPortForInbound, manager.go referred
to the deleted Manager and its fingerprinting as live code, web.go's
cron registration claimed the job scrapes traffic (its own doc says it
does not), and types.go capped ContentPaddingAddition at uint16 when
validation and upstream both use uint32.

* style(lint): satisfy gofumpt/goimports so make verify is green

json_service.go's two 'Tag: "proxy"}' literals came in with main's own
cc245a90 formatting commit and fail the repo's gofumpt gate for everyone;
the import grouping in inbound_amneziawg.go is from the serialized-writer
fix on this branch.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2026-08-24 02:41:15 +02:00
Sanaei d9b599b9aa fix(sub): forward tlsSettings.cipherSuites into the JSON subscription
tlsData rebuilds the client-side tlsSettings from a whitelist of keys
and never copied cipherSuites, so an inbound configured with e.g.
"TLS_AES_256_GCM_SHA384" handed clients a config that negotiated any
suite. Copy it through when non-empty; it is a real xray-core
tlsSettings field, unlike the non-standard "cs" share-link param.
2026-08-24 02:38:40 +02:00
Sanaei cc245a908e style: format struct literals and whitespace
Clean up trailing braces, commas, and unnecessary blank lines in struct initializations across sub and network packages.
2026-08-24 00:06:01 +02:00
Sanaei c26ff59b47 chore(sub): drop the inlined externalLinkEnabled test helper
81fcacab applied the helper's own //go:fix inline directive, rewriting its
only call site to new(false). The function was left behind with no callers.
2026-08-23 23:18:49 +02:00
mrchatam 6f7a305239 fix(node): stop stale expiry sync from undoing client extensions (#6228) (#6231)
* fix(node): stop stale expiry sync from undoing client extensions (#6228)

After an expired client is extended on the master, a lagging node could
overwrite client_traffics with an older absolute expiry and latch
enable=false. Reject older absolute expiries on merge, ignore
expiry-stale disables when the master is not over quota, lift stale
lifecycle fields out of adopted settings, stamp reconcile fingerprints
from the pre-lift node blob, and mark the node dirty so the next tick
re-pushes.

* fix(node): lockstep client_traffics expiry/enable SQL with review fixes (#6228)

Make expiry merge keep any master absolute (node only activates when master
is unset/duration). Include this tick's up/down deltas in the enable
stale-disable quota check so a crossing-tick disable is not dropped.

* fix(node): add settings absolute helper for renew/lift guards (#6228)

Expose settingsClientAbsoluteExpiry so traffic merge can tell a real
node auto-renew (settings+stats later) from lagging ClientStats after a
master shorten. Trim lift godoc to the invariant.

* fix(node): authority-aware lifecycle merge for multi-node sync (#6228)

While config_dirty, accumulate traffic only — do not adopt node
expiry/enable/total/reset (and preserve dipped baselines so a false
renew cannot fire after clear). On clean ticks, master absolute expiry
wins; node auto-renew still goes through nodeClientRenewed when settings
also show the later deadline. Defer settings lifecycle lift until after
traffic deltas land, align SyncInbound via applyMasterClientLifecycle,
and avoid re-MarkNodeDirty when already dirty.

* fix(node): clear config_dirty only after the post-reconcile traffic merge (#6228)

After a successful ReconcileNode, keep the node dirty through the same
tick's SetRemoteTraffic so lagging ClientStats cannot clobber the
just-pushed master lifecycle, then ClearNodeDirty.

* test(node): cover dirty-gate, master-absolute, and renew false-positives (#6228)

Add regressions for extend/shorten while dirty, clean-sibling shorten,
settings vs lagging disable, renew recovery after dirty, renew with
matching settings, and shorten+Reset lagging stats not treated as renew.

* fix(node): address the review findings on the lifecycle merge (#6228)

The automated review on #6231 flagged a blocking regression and six smaller
issues. All of them are fixed here.

Blocking: making the master's absolute expiry always win left nodeClientRenewed
as the only channel for a node-side auto-renew, and that required a counter dip.
A client that used no traffic in the period never dips, so its renewal was
dropped, the master kept the expired deadline and disableInvalidClients removed
it with no way back (master-side autoRenewClients skips node inbounds). The node
bumps reset_count on every renewal, so that counter is now an independent
renewal signal and is persisted with the renewal so it keeps converging.

The deferred ClearNodeDirty made every reconcile-success tick merge in dirty
mode, which suppressed inbound adoption, new client_traffics rows, the orphan
sweeps and the whole SyncInbound record loop -- and left the node dirty forever
whenever SetRemoteTraffic errored. The clear goes back to where it was; a
separate justPushed flag now freezes only the client lifecycle merge for the
tick whose push just landed.

staleNodeDisable only recognised a lagging disable by an older expiry, so a
quota top-up (raise totalGB, leave the expiry alone) was re-latched to disabled
by the next lagging snapshot -- the #6228 symptom on a second axis. The
reviewer's suggestion of dropping the expiry precondition outright fails
TestNodeQuotaDisable_SameExpiryStillLatches, because the master's own counters
legitimately sit below a node's after a seeded-at-zero adoption. nodeDisableIsStale
instead compares the limits the node judged the client against with the master's
own: matching limits mean a genuine verdict that still latches (#4917), differing
limits mean the node has not seen the master's change yet. It also now measures
the master deadline against wall-clock now, so an expired master row no longer
looks "extended" merely because the node's copy is older still.

Also: the settings lift now writes enable in both directions, so a blob fetched
before a master disable cannot carry enable=true back into central settings and
on to the node; the renewal guard parses the inbound settings once per inbound
instead of once per renewing client; the adoption loop only writes settings when
they actually changed; and two comments that described mechanisms the code does
not use were corrected.

The test deadlines are now relative to the run: the merge compares against now,
so fixed timestamps would have rotted into the wrong side of it.

---------

Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-23 23:17:56 +02:00
DIMFLIX da01b7637d feat(sub): client-side balancers for the JSON subscription (#6243)
* feat(sub): add SubBalancer model and migration

Client-side JSON-subscription balancer row: remark, strategy, member inbound ids, sort order, enabled. Registered in allModels and migrationModels so AutoMigrate and SQLite->Postgres copy pick it up.

* feat(sub): add SubBalancer service

List/Get/Create/Update/Delete over the sub_balancers table with remark trim, strategy allowlist (leastLoad/leastPing/random) and sort-order floor. Rows are read per request by the subscription builder, so mutations need no xray restart.

* feat(sub): add SubBalancer API controller and routes

GET/POST /panel/api/sub-balancers, POST /:id (update), DELETE /:id and POST /:id/del alias. inboundIds bind from repeated form keys. Mounted under the /panel/api group so the existing API token + CSRF middleware cover it.

* feat(sub): emit client-side balancers in JSON subscription

For each enabled balancer, append one config document whose outbounds are the selected inbounds' proxy outbounds retagged under a per-balancer prefix, with routing.balancers + burstObservatory selecting it. Balancer entries interleave with inbound entries by sort order; on equal numbers the balancer follows the inbound. Skipped when disabled or no member outbound is present.

* test(sub): cover SubBalancer service and JSON output

Service: validation gates (remark/strategy/inbound ids/sort order) and CRUD round-trip. JSON: balancer document shape, sort interleaving with inbounds, disabled/empty skip, and member tag dedup.

* feat(sub): add sub-balancers i18n keys

pages.settings.subBalancers.* block (menu, title, add, desc, field labels, strategy names, sort-order help, validation messages) added to all 13 locales.

* feat(sub): add SubBalancer schema and API queries

Zod schema (entity + form, strategy enum, validation messages wired to i18n keys), react-query hooks for list/create/update/delete, and the sub-balancers query key.

* feat(sub): add subscription balancers settings tab

SubscriptionBalancersTab lists balancers (sort order, remark, strategy, inbound count, enabled toggle, edit/delete) with a form modal (remark, strategy, sort order, multi-select inbounds filtered to multi-client protocols, enabled). Wired into SettingsPage under #subscription-balancers, and the sidebar shows the entry only when JSON subscription is enabled.

* test(sub): add SubBalancer form modal test

Covers add-mode (no validation errors, confirm with parsed values) and edit-mode (seeds from the balancer, preserves strategy/sort order/enabled).

* feat(sub): register sub-balancers in API docs and OpenAPI

Adds the sub-balancers endpoint group to endpoints.ts (list/create/update/delete + POST del alias) and regenerates frontend/public/openapi.json from it.

* docs: sync openapi.json with frontend

docs/public/openapi.json had fallen behind frontend/public/openapi.json (fewer paths/schemas). Copy the current frontend spec so the docs site renders the full API.

* docs: add subscription balancers API reference

Registers the sub-balancers page (generated MDX) and adds the sub-balancers paths to docs/public/openapi.json so the page renders the list/create/update/delete operations.

* feat(sub): accept roundRobin balancer strategy

Add roundRobin to the model oneof tag and the service strategy allowlist, alongside leastLoad/leastPing/random. Covered by a service-level create test that fails on the old allowlist.

* feat(sub): add roundRobin strategy label

pages.settings.subBalancers.strategyRoundRobin added to all 13 locales.

* feat(sub): expose roundRobin in balancer form

Zod strategy enum, form modal label key, and table strategy colour for roundRobin.

* docs(sub): list roundRobin in strategy description

The create/update strategy param description now mentions roundRobin alongside the other three.

* feat(sub): add subJsonObservatory setting

Panel-wide JSON string carrying the burstObservatory ping config (destination, connectivity, interval, sampling, timeout, httpMethod) emitted into client-side balancer docs. Stored like subJsonMux/Rules/FinalMask.

* feat(sub): wire observatory config through sub controller

WithSUBJsonObservatory option; the controller calls SubJsonService.SetObservatoryConfig after construction.

* feat(sub): emit observatory conditionally with configurable probes

burstObservatory is emitted only for leastPing/leastLoad; random/roundRobin get none (no fallback, so an observatory would only probe for nothing). Probe params come from the subJsonObservatory setting, falling back to the built-in defaults when empty or partial. Test covers the conditional emit and the override.

* feat(sub): add subJsonObservatory to AllSetting model

Frontend AllSetting model and Zod schema carry the new panel-wide observatory config string.

* feat(sub): add balancer observatory config card

New Sub Formats tab editing destination/connectivity/interval/sampling/timeout/httpMethod, stored as JSON in subJsonObservatory. Toggle off clears the setting; the backend then falls back to defaults.

* fix(sub): hide save/restart header on sub-balancers tab

Sub-balancer mutations are incremental (own CRUD API, no Save, no restart), so the page-wide 'every change needs to be saved / restart the panel' banner is misleading there. The in-tab alert already explains it correctly.

* feat(sub): add observatory config i18n keys

pages.settings.subBalancers.observatory.* (title, desc, probe field labels and help texts) added to all 13 locales.

* feat(sub): regenerate openapi for subJsonObservatory

openapigen picks up the new AllSetting field; openapi.json synced into docs.

* feat(sub): add observatory tab to sub-balancers

Mirrors the Xray Balancers page: two tabs (Balancers + Observatory).
Wires allSetting/updateSetting into the tab and adds tabBalancers /
tabObservatory labels to all locales. The page Save header is shown
again on this tab so the observatory config can be saved.

* refactor(sub): drop observatory tab from sub-formats

Now that the observatory config lives under sub-balancers, remove the
duplicate tab plus its state and defaults from sub-formats.

* fix(sub): add missing inboundsCount i18n key

The sub-balancers table rendered the raw key path in the Inbounds
column because pages.settings.subBalancers.inboundsCount was not
defined. Added it to all 13 locales.

* test(sub): pin disabled-inbound exclusion from balancer

The balancer builds its members from the subscriber's already-filtered
entry set, so an inbound disabled for that user can never surface as a
member. Adds tests for both shapes (one of several disabled, and the
only selected one disabled).

* fix(sub): make observatory toggle honest, default connectivity off, add balancer fallback

Three coupled defects on the balancer observatory surface, flagged in PR review:

- The Observatory Switch wrote '' which the Go side treats as "use built-in defaults", so leastPing/leastLoad still shipped a burstObservatory the admin could no longer see or edit. The observatory is mandatory for these strategies (Xray refuses to start leastPing/leastLoad without one — verified against Xray 26.7), so the switch is relabelled to "customise probe parameters vs built-in defaults" rather than on/off: '' keeps the defaults, a stored JSON overrides them. An info Alert explains this.

- Connectivity defaulted to http://www.google.com/generate_204 and an explicit {"connectivity":""} restored it, so the UI's "Leave empty to skip" was unreachable and the direct pre-check was dead on arrival on censored client networks. Default to "" and honour an explicit empty value.

- routing.balancers had no fallbackTag, so a leastPing/leastLoad balancer whose probes all fail selects nothing and dispatch fails. Emit fallbackTag pointing at the first member so a probe outage degrades instead of breaking.

Also skip balancer entries (kind!=0) in the member scan so a balancer can never match another balancer's row id. Tests cover each fix and fail without it.

* fix(sub-balancer): localize controller toasts and reject malformed ids

Route the new controller's user-facing messages through I18nWeb so non-English admins get localized toasts like every other controller, and switch parseID to strconv.Atoi rejecting ids < 1 so "12abc" and negative ids no longer coerce to a silent no-op delete that reports success.

* fix(sub-balancer): enforce remark length cap server-side

The model's validate:"max=256" tag was never enforced (parseSubBalancerForm binds an ad-hoc struct without validate.Struct), so a scripted API client could store an unbounded remark that is emitted verbatim as the remarks field of every affected subscriber's config. Reject len > 256 in validate() to match the frontend Zod cap.

* fix(sub-balancer): exclude mtproto from balancer member picker

SubJsonService.getConfig has no mtproto case, so an mtproto inbound's first outbound is "direct" and the buildBalancerConfig "tag != proxy" guard drops it — an admin could select it, save without error, and get a balancer that silently omits it (or no document at all). Drop it from the picker and fix the comment.

* docs(sub-balancers): add nav entry, fix tab pointer, note mirror scope

- Add "subscription-balancers" to the en reference/api meta.json pages array so the new MDX page is reachable from the sidebar (fa/ru/zh have no MDX — gen-openapi.ts emits into en only).

- Fix the endpoints.ts section description from "Settings -> Subscription" to "Settings -> Sub Balancers" (the feature's own tab) and regenerate the OpenAPI spec + MDX.

- Note in docs/lib/xray/subscription.ts that balancer documents are intentionally out of scope for that mirror.

* style(model): trim SubBalancer comment to 2-line cap

CLAUDE.md caps committed Go comment blocks at 2 lines; this one was 3.

* fix(sub-balancer): parse enabled explicitly and preserve it on partial update

parseSubBalancerForm treated any non-"false" value as true (so "bogus"
silently enabled) and always overwrote Enabled on update, so a PATCH that
omitted the toggle reset a disabled balancer back to enabled. Parse the
field with strconv.ParseBool and return *bool: absent means "no change"
on update and "true" on create; a malformed value is rejected as 400.
Update keeps the stored Enabled when the pointer is nil.

* fix(sub-balancer): clear deleted inbound from sub_balancers.InboundIds

DelInbound cascaded hosts but left the deleted inbound id in every
sub_balancers.InboundIds, so the balancer kept emitting a member no
subscriber could resolve — a dangling outbound tag with no proxy behind it.
Strip the id inside the existing delete transaction (same shape as the hosts
cascade, #5648); with the last member gone the balancer stops emitting.

* fix(sub-balancer): return not-found when deleting a missing balancer

Delete returned the gorm result error only, which is nil when no row matched,
so the controller reported success:true for an id that never existed — a stale
UI row looked like a clean delete. Check RowsAffected and return a not-found
error on 0 so the toast reflects reality.

* style(sub): shorten leastPing/leastLoad observatory comments

The observatory-emission guard comment and its test comment ran a few
lines long; trim them to a couple of lines each without dropping the
invariant that leastPing/leastLoad require a burst observatory.

* fix(sub): validate observatory setting instead of silently dropping it

SetObservatoryConfig applied whatever survived json.Unmarshal with no checks,
so a bad probe URL ("not-a-url"), non-duration interval/timeout, or even
unparseable JSON was either silently applied or silently ignored. Validate
each field: parse durations with time.ParseDuration, require http(s) URLs for
destination/connectivity, and log a warning naming the field and the bad value
on every fallback — including the unmarshal error, which was a quiet return.
Bad values now keep the built-in defaults instead of leaking into the emitted
burstObservatory.

* fix(sub): deduplicate burst-observatory defaults across Go and frontend

The burst-observatory ping defaults lived in three places that had drifted:
Go defaultSubBalancerObservatoryConfig (http probe, sampling 3), the Zod
PingConfigSchema, and DEFAULT_BURST_OBSERVATORY (both with a connectivity
pre-check URL). Align them to one set: https probe destination, sampling 2,
and empty connectivity (skip the direct pre-check). The settings tab now
parses the stored JSON through PingConfigSchema and seeds its default from
DEFAULT_BURST_OBSERVATORY instead of carrying its own literal.

* refactor(sub): extract proxy outbounds once before the balancer loop

buildBalancerConfig unmarshalled every inbound document and re-extracted its
first outbound on each balancer, so with B balancers and N inbound docs the
same document was parsed B*N times. Pull each doc's proxy outbound in a single
pre-pass over the entries and cache it per entry; buildBalancerConfig now
clones the cached map before retagging, so one parse serves every balancer.
Output is byte-for-byte unchanged.

* fix(sub): form balancer member tags from the inbound protocol, not tcp→vless

balancerTransport derived the bal-N tag suffix from the outbound's transport
network and hard-coded tcp→vless, so a vmess/tcp or trojan/tcp member was
mislabelled "vless" in every client config — the tag lied about the proxy
type. Use the outbound's real protocol as the suffix (bal-1-vmess, bal-1-vless,
bal-1-trojan, …) so the tag names the actual proxy; the selector prefix and
dedup suffix are unchanged. Update the existing tag assertions and add a vmess
case that fails under the old mapping.

* fix(sub-balancer): default strategy to random in the create form

The create-balancer form seeded strategy to 'leastLoad', but the service
validate() defaults an empty strategy to 'random' and the API docs say the
default is 'random' — so a freshly opened form showed leastLoad while saving
without touching the field silently stored random. Align the form default to
'random' so what the admin sees is what gets persisted.

* feat(api-docs): document the SubBalancer response schema

The five sub-balancer endpoints carried no responseSchema, so the API docs
page rendered them without a typed example. Add example: tags to every
SubBalancer field, allow the struct through openapigen, and point the list
(responseSchemaArray) and single-row endpoints at 'SubBalancer'. Regenerate
the Zod/JSON schemas and OpenAPI doc and mirror openapi.json into docs/.

* style(sub-balancer): drop whitespace-only separator lines, add final newline

subBalancer.ts and SubBalancerFormModal.tsx used single-space blank lines as
separators between statements and had no trailing newline. Replace them with
clean empty blank lines and end each file with a newline.

* fix(i18n): translate sub-balancer toasts and observatory note

The sub-balancer toast messages (list/create/update/delete/invalidId) and
the observatory note were left in English across 11 non-English locales
(ar, es, fa, id, ja, pt-BR, tr, uk, vi, zh-CN, zh-TW) while every other key
in the subBalancers block was already translated. Translate them to match the
meaning and terminology of the surrounding keys in each file; the JSON
structure and keys are unchanged.

* fix(sub-balancer): hide disabled inbounds from the member picker

The picker offered every protocol-eligible inbound regardless of its enable
flag, but getInboundsBySubId filters `AND inbounds.enable = true`. A disabled
member is therefore dropped from every subscriber's entries, and when it was
the balancer's only member the balancer document silently stops being emitted
— with nothing in the UI explaining why. TestSubJson_BalancerSkippedWhenAll
MembersDisabled already documents that backend behavior.

Filter the way the sibling client picker has since #5645: hide disabled
inbounds, but keep one that is already selected so editing an existing
balancer cannot silently drop a member.

Drop the `?? []` on the useWatch result so the new useMemo dependency stays
referentially stable.

* style(sub): trim the balancerMemberSuffix comment to the 2-line cap

Comment blocks in committed Go are capped at 2 lines; the name already carries
what the function picks, so keep only the why.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
2026-08-23 22:34:20 +02:00
Sanaei 81fcacab11 chore(build): bump Go toolchain to 1.27.0
Go 1.27.0 shipped on 2026-08-19. Raise the go directive and the builder
image so Docker and release builds pick it up; every CI job already reads
the version from go.mod, and golangci-lint v2.13.1 release binaries are
themselves built with go1.27.0, so the lint job needs no pin change.
2026-08-23 21:57:03 +02:00
Zane 02002dc1c3 feat(routing): add client picker to user rules (#6271)
* feat(routing): add client picker to user rules

Replace the free-text user criterion with a searchable multi-select backed by existing panel clients. Preserve saved values that no longer exist so editing legacy rules remains lossless.

* feat(routing): polish user picker states

Align the routing user selector with the inbound-tag multi-select, including search, clear, loading, empty, and error states. Localize the new copy across every supported locale and cover legacy saved users with a regression test.

* fix(routing): keep custom user identifiers

Use tags mode with comma tokenization so the user picker suggests panel clients without rejecting HTTP, Mixed, or raw-template identifiers. Restore the comma hint and cover custom entries with a regression test.
2026-08-22 23:13:34 +02:00
n0ctal 326009e9d3 fix(traffic): clear cross-panel rows only for clients actually renewed (#6263)
autoRenewClients collects every expired client that carries a reset interval,
but three of them never reach a new window: one may be missing from its
inbound's settings, one may resolve to no whole interval, and one may still
land in the past once the reset cap truncates the catch-up. All three keep
their counters and their expiry on purpose.

clearGlobalTraffic was still called with the full candidate list, so those
three lost their cross-panel rows while their local counters stayed. The next
push recreates the rows, and the expiry branch of the depletion check cuts
these clients regardless, so nothing is served past its limit — but between the
delete and the next push the cross-panel view under-reports them, and since the
expiry never advances that repeats on every poll.

Pass only the clients whose counters this pass reset. clearGlobalTraffic
already early-returns on an empty list, so a poll that renews nobody stays a
no-op rather than deleting every row. The renewed count returned to the caller
now counts the same set, instead of reporting candidates as renewals.

Tests cover both directions: a capped catch-up keeps its rows, and an actually
renewed client still loses them, since stale pushed totals would otherwise
re-deplete the fresh window at once.
2026-08-22 23:12:33 +02:00
Matt Van Horn 585f4ecdc0 fix: reject Hysteria inbound updates with empty client auth (#6268)
Fixes #6232

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-08-22 23:11:42 +02:00
Masterain bd6a6aba43 feat(pia): add PIA login-and-add WireGuard outbounds (#6272)
* feat(pia): add login-and-add WireGuard outbounds (#2)

* fix(pia): keep PIA outbounds identifiable after the editor strips hostname

The outbound editor drops piaHostname, so last-segment matching failed for hyphenated servers. Identify rows by the computed tag, re-encrypt stored tokens onto the active key, skip unusable catalog rows, and always release the catalog refresh latch.
2026-08-22 23:11:06 +02:00
Sanaei a3e617215c fix(ci): pin the head the review job checks out
The review job checked the pull request out through refs/pull/N/head, a
ref the author can move after a maintainer types "@claude review". Code
scanning flagged it twice on the issue_comment path: an untrusted
checkout in a privileged context (alert 111) and the time-of-check /
time-of-use race that ref creates (alert 110).

Resolve the head once, up front, and refuse the run when the fork was
pushed to after the request that vouched for it, mirroring the freshness
gate resolve-conflicts already uses; the checkout then names that
immutable SHA. pull_request_target runs take the head SHA straight from
the payload, so they skip the comparison. The trailing "posted nothing"
check no longer fires on top of a refusal, which would otherwise report
a second, misleading failure.
2026-08-22 21:09:24 +02:00
yzxcj797 a255ab7c65 fix(node): don't stamp InboundsAdoptedAt when the sync adopted nothing (#6284)
* fix(node): don't stamp InboundsAdoptedAt when the sync adopted nothing

Onboarding a node in selected mode with an empty tag list empties the
traffic snapshot via FilterNodeSnapshot before the merge sees it, so
the first clean sync adopts nothing — yet syncOne stamped
InboundsAdoptedAt regardless. The flag is documented as the first
clean sync that imported the node's pre-existing inbounds; stamping it
in this state arms the reconcile sweep (gated on the flag since
200ea091, the fix for #5898) to delete the node's pre-existing
inbounds on their next real sync: registering first and choosing tags
afterwards destroyed the node's inbounds.

Gate the stamp on the sync actually being able to adopt: in selected
mode, at least one selected tag or adopted alias must exist for the
snapshot filter to keep anything.

Fixes #6283

* restore atomicBool tests; trim comment to repo 2-line cap

The new test file unintentionally replaced the existing
node_traffic_sync_job_test.go, dropping its four atomicBool tests;
restore them and keep only an additive diff. Trim the syncCanAdopt
doc comment to the repository's 2-line comment cap.

* trim syncCanAdopt comment to the 2-line cap
2026-08-22 20:37:55 +02:00
ilyusha af3e6c11b6 docs(api): document WireGuard and mtproto secret generation on clients/add (#6282)
* docs(api): document WireGuard and mtproto secret generation on clients/add

The POST /panel/api/clients/add summary enumerated the protocols whose
secrets the server fills in, and that list stopped being complete when
WireGuard gained per-client keys and mtproto gained a FakeTLS secret.
Read literally it says the endpoint is unusable for WireGuard without a
hand-made keypair and address, while defaultWireguardClients in fact
generates the keypair, derives the public key from a supplied private
one, and allocates a free /32.

Rather than extend an enumeration that goes stale on every new protocol,
the summary now states the rule alone and the per-protocol detail moves
into the operation description - a field Endpoint already declares and
build-openapi.mjs already maps, but that no endpoint used until now.
Swagger UI in the panel and the docs site both render it.

The attach operation gets the rule added for #5785 that nothing
documented: a client already carrying allowedIPs brings them into the
new inbound instead of being given a fresh address, and is rejected when
another client of that inbound holds it.

Closes #6276

* docs(api): correct the clients/add generation rules flagged in review

Three claims in the new description did not hold:

Shadowsocks does not keep every supplied password. fillProtocolDefaults
regenerates it when validShadowsocksClientKey rejects it, which on a
2022-blake3-* inbound means any password that does not base64-decode to
16 or 32 bytes - the call still returns success, so the caller has to
read the client back to notice. Split off from Trojan and spelled out.

The UUID is not always fresh: re-adding an email that already exists,
with the stored subId, reuses the stored id, password, auth and secret
so the identity stays in sync across its inbounds. That branch was
documented nowhere.

The mtproto secret falls back to www.cloudflare.com when the inbound
carries no fakeTlsDomain.
2026-08-22 20:37:39 +02:00
dawn b73ceae081 fix(frontend): refresh subscription settings after save (#6287)
The derived defaults query is cached indefinitely, so subscription links kept using the old path after settings saves. Invalidate it only after successful saves so inbounds and clients refetch generated subscription URLs.
2026-08-22 20:11:51 +02:00
Kuzz007 1250fbb734 feat(clients): allow removing a single HWID device (#6265)
* feat(clients): allow removing a single HWID device

Only "list" and "clear all" existed for registered HWID devices, so
freeing one slot under a client's HWID limit meant clearing every
device and waiting for the ones you kept to re-register. Adds a
per-device delete: DELETE /panel/api/clients/hwids/:email/:id, scoped
to the client's own sub_id (device ids are a global auto-increment,
not per-subID, so this also prevents deleting another client's
device), plus a delete button next to each device in the existing
HWID modal.

Addresses MHSanaei/3x-ui#6245.

* feat(clients): surface HWID limit + device log in the client info card

Mirrors the existing IP-limit row/eye-icon-modal pattern that's
already in this card. The HWID devices modal reuses the same
list/clear-all/per-device-delete UI already shipped for the edit
form's own HWID modal, so a device can be removed without opening the
edit form at all.

* i18n: add HWID single-delete strings to all 13 locales

deleteHwid/deleteHwidConfirm/hwidDeleted were only added to en-US and
ru-RU in the previous commit; backfilling the other 11 locales the
project's own translation set covers.

* fix(clients): address automated review of HWID single-delete PR

- ClientInfoModal: use the existing dateLabel() helper (Jalali-aware)
  for HWID first/last-seen instead of a raw dayjs format, matching
  every other timestamp in the same modal.
- Add okText/cancelText to the delete-device Popconfirm in both
  ClientInfoModal and ClientFormModal so all 13 locales get a
  translated confirm dialog instead of Antd's English default.
- deleteHwid controller: stop reusing the success toast key on both
  error paths, which rendered a red "Update successful" toast on a
  real (not just theoretical) failure such as a stale HWID modal.
- Trim DeleteClientHwid's doc comment to the repo's 2-line cap and
  correct it: deletion is scoped by sub_id, which can span more than
  one ClientRecord, not strictly "this client only".
- Add TestDeleteClientHwid covering cross-sub_id id rejection, unknown
  id rejection, and a real successful delete.

* chore: retrigger CI (previous run stuck installing Playwright Chromium)

* fix(clients): address the arbiter review on the HWID single-delete PR

- Extract the HWID device list into a shared frontend/src/lib/clients/
  hwid-log.ts type/normalizer, a shared useClientHwids hook, and a
  shared ClientHwidListModal component, mirroring the existing IP-log
  pattern. ClientInfoModal and ClientFormModal both render the same
  component now, so the two copies can no longer drift the way they
  already had (different date formatting, different tag styles).
- Add a Popconfirm to the HWID "Clear all" button (previously
  unconfirmed, unlike the per-device delete right next to it) — closes
  the confirm/no-confirm asymmetry the review flagged as the main risk.
- Sync docs/public/openapi.json with the two hwids paths and regenerate
  clients.mdx. Scoped to just those two paths rather than a full copy
  from frontend/public/openapi.json: the docs copy is far enough behind
  on unrelated paths (a host-group API rename) that a full sync breaks
  the Next.js build on locale pages referencing the old shape — out of
  scope for this PR.

* fix(clients): trim HWID list comment blocks to 2 lines

Repo convention caps comment blocks at 2 lines; both were 1 line over.

* chore: retrigger CI

build (arm64) and build (armv6) failed on a transient Go module proxy
network error (INTERNAL_ERROR stream reset), unrelated to this PR's
changes.
2026-08-21 14:17:05 +02:00
Sanaei 5321665d5b feat(ci): give the review bot a severity scale and a tally
REVIEW.md said what blocks and what does not, but never how to mark a finding,
so every review invented its own shape and none carried a severity. It now
names the three markers the hosted Code Review service uses - Important, Nit,
Pre-existing - and keys them to what the pull request did rather than to how
alarming a defect looks alone: a defect it introduces or worsens is Important,
one it merely brought into view is Pre-existing and cannot be a reason to hold
it. Pre-existing was missing entirely, and checking what this panel emits means
reading far outside the diff, so those findings had nowhere to go except a
wrong Important or silence.

The volume cap said how many and never which. It now collapses a nit repeated
across files into one finding, prefers a nit in code the pull request wrote
over one in code it only moved, caps pre-existing findings at three, and states
that Important findings are never capped - a section listing two caps otherwise
reads as licence to trim what matters. The review opens with a tally so the
author sees the shape before the detail.

Two contradictions went with it. The file told the reviewer to skip what CI
enforces and then to check that a new i18n key reaches all 13 locales, which
i18n-dead-keys.test.ts pins in both directions - the rule moves to "Do not
report" with the reason. "Anything CI already enforces: npm audit" overstated
what runs; CI audits production dependencies at high and above, so a
dev-dependency advisory is out of scope by design.

The reviewer could not read its own CI. Only postgres-durable-first runs
against PostgreSQL, and XRAY_E2E_BINARY and XUI_SCALE_TEST are set by no job,
so a dialect or migration change can carry a wall of green while the paths it
touches never executed. That belongs to the verification bar, next to the rule
that a behaviour claim needs a file:line citation, and "CI passed" now needs a
run actually read. Also names the two house choices no linter defends: neither
golangci-lint nor oxlint rejects a testify or Tailwind import.

Both kinds of claim rot on a rename, so a test pins them the way
repo-context.md's claims are already pinned - the CI jobs REVIEW.md names must
exist in ci.yml, the skip gates it calls unset must stay unset, and the locale
count must match the directory.

The review itself moves from high to max effort, and the prompt records why it
names REVIEW.md at all: the code-review skill reads CLAUDE.md on its own but
not REVIEW.md, so dropping that clause would silently stop the file applying.
Drops a CLAUDE.md reference to tools/seedperf/, which no longer exists - the
review reads that file as project context, so a stale path there misleads it.
2026-08-21 03:37:12 +02:00
Sanaei 73a971c2d1 fix(ci): give the review bot the pull request's own code and CI verdict
Three consecutive review runs (#6105, #6265, #6272) posted accurate findings
but ended with the same "nothing was verified" paragraph, and the transcripts
show why: under pull_request_target the only checkout is the base branch, so
every Read of a changed file returned the pre-merge version and the agent
fell back to fetching blobs one at a time through the API — 452 Bash calls on
#6105 alone. It tried `git fetch origin pull/N/head` in all three runs and was
denied every time.

Check the head out read-only beside the base tree and say so in the prompt, so
the reviewer greps the code actually under review. Nothing builds or executes
from pr-head/: this job carries a write-scoped token, which is exactly the
pwn-request REVIEW.md classes as blocking.

CI had already run the full gate on each head SHA, but no run ever looked —
`check-runs` appears in none of the three transcripts. Point the reviewer at
it so a red or missing required check becomes a finding instead of a
disclaimer.

Also pass an explicit review level: with none given the skill reuses the last
one typed, which in CI does not exist (ReportFindings recorded level=null on
#6272). And allow WebFetch/WebSearch — the PIA review was denied both while
trying to confirm the bundled PIA public key, then had to file that same check
as unverified.
2026-08-20 23:12:35 +02:00
Sanaei 19a2c23c01 fix(ci): repair the review comment and the conflict-resolution guard
Two failures from the same afternoon, both in the bot workflow.

The review of #6272 ran for 34 minutes across four subagents and posted
"No issues found. Checked for bugs and CLAUDE.md compliance." — three
lines for a 73-file diff. The agent had written a per-area coverage
summary in its own last turn and then dropped it on the floor, because
the code-review skill's comment template carries findings and nothing
else. A comment that cannot distinguish a thorough clean review from a
run that died early is not evidence, so REVIEW.md now states what the
posted comment must show and the system prompt points the run at it.

The same run logged 67 permission denials. Only the inline-comment MCP
tool was named in --allowedTools, so `gh api`, writing the diff to a
scratch file, and reading it back were all auto-denied: agents spent
turns hunting for a writable directory, and the openapi.json copy check
REVIEW.md calls blocking could not be run at all ("gh api was
unavailable in this sandbox"). Name the tools the review actually uses.

The conflict resolution on #6243 resolved both conflicted files
correctly and was then rejected by its own guard: "Edits outside the
conflicted set: CLAUDE.md". The agent never touched CLAUDE.md — it had
Edit rights on exactly two paths and no shell. claude-code-action
deletes and restores CLAUDE.md, .claude/, .mcp.json and friends from
the base branch before it runs, because the PR head is untrusted, and
that restore is what dirtied the tree. Name that set once, exclude it
from the stray-edit check, and hand back rather than resolve when a
conflict lands inside it — the restore would silently overwrite the
resolution and stage the base copy.
2026-08-20 20:14:24 +02:00
Sanaei e4798a027c chore(lint): adapt to staticcheck v0.8.0 under golangci-lint v2.13.1
golangci-lint v2.13.0 pinned honnef.co/go/tools v0.8.0-rc.1, whose
staticcheck never terminates on internal/web/service/tgbot: the run pins
~520% CPU with RSS climbing past 700MB rather than deadlocking, so it
reads as a hang. controller/, job/ and service/... only appeared stuck
because they pull tgbot into the analysis graph. v2.13.1 ships the final
v0.8.0 and clears it — that package goes from unbounded to 0s, and a
cold full run to 22s. CI needs no pin; it already tracks latest.

The same bump reworded SA1019 from parser.ParseDir to go/parser.ParseDir,
which silently voided the openapigen exclusion, so the pattern now
matches either spelling.

fasthttp Client.RetryIf is deprecated in favour of RetryIfErr. The old
path left resetTimeout at its zero value, so returning false preserves
the existing retry timing exactly.

The rest are gofumpt redundant-paren removals from the stricter
formatter — semantic no-ops.
2026-08-20 19:37:40 +02:00
Sanaei 845abc380e fix(ci): make the review bot post its findings and acknowledge mentions
Three separate ways the bot went silent after the move to the official
code-review skill:

- The skill skips a PR it has already commented on without comparing the
  reviewed head to the current one, so #6272 got no review of the commits
  pushed after the first pass. A prior review now only justifies a skip
  when its "Reviewed head:" SHA matches the current head, and never when
  the run came from an explicit "@claude review".
- The review agent launched its subagents in the background and ended its
  turn to wait for them. A headless run terminates on end_turn, so the
  findings were discarded and the job still reported success. The prompt
  now requires foreground subagents, and a new step fails the job when a
  run posts nothing for the current head, instead of passing green.
- A custom prompt puts claude-code-action in agent mode, which never adds
  the eyes reaction, so a mention gave no sign it had been picked up.
2026-08-20 15:59:51 +02:00
Sanaei 58669f6146 refactor(ci): replace the in-house review lanes with the official code-review skill
The four pull_request_target review jobs in claude-bot.yml (Senior
Developer / QA / Tester / Arbiter and their shared rubric) are replaced by
a single review job running the official code-review plugin - the same
skill behind Anthropic's hosted Code Review and the review workflow
/install-github-app generates. The hosted service needs a Team/Enterprise
organisation, so the plugin runs in CI on the maintainer's subscription
instead: inline findings on PR open and ready-for-review, plus manual
(re-)review when the owner or a collaborator comments "@claude review".

The official example triggers on pull_request, but GitHub withholds
secrets from fork runs and essentially every 3x-ui pull request is from a
fork, so the job keeps the lanes' pull_request_target posture: the
workspace is the base revision and nothing from the pull request is
checked out or executed.

What the lanes uniquely knew is distilled into REVIEW.md, handed to the
skill via --append-system-prompt and pinned by bot_context_test.go the way
repo-context.md is: the runtime.Runtime dispatch rule, migration and
upgrade safety, the four-step route contract chain including the unchecked
docs copy, the i18n rule, the three link implementations, and the
wire-format verification bar. The mention job now ignores "@claude
review" comments on pull requests so the review trigger does not also
wake the generic bot, and the lane-only rubric file goes with the lanes.

The remaining prompts also lose their tone micro-rules (no emoji, no
exclamation marks, no filler) and the workflow's comment banners are
removed.
2026-08-20 15:09:48 +02:00
Sanaei 19e71d9acc refactor(ci): move the bot's repository briefing into versioned files a test pins 2026-08-20 05:18:13 +02:00
Sanaei f7db247b07 perf(clients): write client_inbounds deltas and check identity from the clients table
Client CRUD latency scaled with the number of client-inbound edges rather
than with the size of the change. On a 5k-client / 8-inbound / ~56k-edge
PostgreSQL panel, creating one client took 60-120s (#6252).

Two independent causes, both confirmed by the reporter's pg_stat_statements
and reproduced locally at their topology.

SyncInbound deleted every client_inbounds row for an inbound and re-inserted
the whole set, so a one-client edit rewrote thousands of unrelated rows. The
dominant caller was not user CRUD: the node traffic poll re-syncs every node
inbound from its snapshot every 5s, so the panel churned the entire
membership table continuously in the background. SyncInbound now reads the
current links and writes only the difference - insert missing, update a
changed flow_override, delete departed. Callers are unchanged, so every
reconciliation path benefits, and the four hot client CRUD paths additionally
pass only the clients they touched via ApplyInboundClientDelta.

The insert needs clause.OnConflict: the unconditional delete it replaces also
serialized concurrent syncs of one inbound, and the node poll commits in its
own transaction outside the serialized writer, where a duplicate key would
abort the whole poll on PostgreSQL.

Identity and membership questions expanded every inbound's settings.clients
JSON - 5.75s per call under the reporter's load. They now read the indexed
clients and client_inbounds tables, which every read path already trusts,
over just the emails being checked. A LOWER(email) expression index keeps
the case-insensitive matching indexed; a struct tag cannot declare one.

Measured on PostgreSQL 17 at 8 inbounds x 6000 clients, rows written to
client_inbounds per operation, before -> after:

  create across 8 inbounds   48008 ins / 48000 del  ->  8 ins / 0 del
  update the client          48008 ins / 48008 del  ->  0 ins / 0 del
  detach from 4 inbounds     24000 ins / 24004 del  ->  0 ins / 4 del
  delete the client          24000 ins / 24004 del  ->  0 ins / 4 del

Two behavior changes worth naming. An email seen with two different subIds
across two inbounds' JSON used to be locked so that no add could claim it,
including the one with the correct subId; the clients row now adjudicates.
And on an install whose settings JSON holds an email with no matching link,
"is this email on another inbound" now answers no, so deleting it elsewhere
purges its traffic rows; compactOrphans and the startup heal already
converge such drift.

Every added test was verified against a hand-written mutation of this change,
so none of them pass regardless of the fix. One mutation survives on purpose:
swapping OnConflict DoUpdates for DoNothing is only observable when two
transactions race the same row, and a timing-dependent test would be flaky.

Per-node batching of remote pushes and the metadata-only inbounds list from
the same report are deliberately not in this change.

Closes #6252
2026-08-20 04:09:57 +02:00
Sanaei c8a3a2d723 fix(security): require a 2FA code to replace the stored TOTP secret
The confirmation gate in updateSetting only covered the true -> false
transition, so a settings save that kept twoFactorEnable=true while
carrying a non-blank twoFactorToken silently rebound the authenticator.
preserveRedactedSecrets restores the stored secret only when the
submitted one is blank, so a non-blank value went straight through
without any branch asking for a code.

Not reachable pre-auth or cross-site (CSRFMiddleware rejects unsafe
methods without the session token), but it matters after a session
hijack or with an admin API token, which sets api_authed and
short-circuits the CSRF check: the attacker gains persistence and locks
the legitimate operator out of their own authenticator.

Now a code is required whenever 2FA is currently on and the submitted
secret differs from the stored one. Enabling from off is untouched, as
no code exists yet to verify, and a blank secret still means
"unchanged", so the panel's normal save path is unaffected.

Reported by @n0ctal (GHSA-xqqw-jqqv-99h6).
2026-08-19 19:54:15 +02:00
Sanaei b51f09768b fix(netsafe): classify IPv6 transition and CGNAT ranges as internal
IsBlockedIP leaned entirely on Go's net.IP predicates, which judge an
address by its own range only. 6to4 (2002::/16), NAT64 (64:ff9b::/96 and
64:ff9b:1::/48) and Teredo (2001::/32) each tunnel an arbitrary IPv4
destination inside an IPv6 address, so all five predicates returned false
for e.g. 64:ff9b::7f00:1 and the SSRF guard waved it through. CGNAT
(100.64.0.0/10) and the deprecated site-local block were unclassified for
the same reason. Reported as GHSA-cfpf-wmjp-gh6c.

Reaching the embedded IPv4 needs a 6to4 tunnel, NAT64 gateway or Teredo
client on the host, none of which exist by default, so this is hardening
rather than a live path off a stock install. The guard backs outbound
subscription fetches, node sync, reality scan, the tgbot API URL and the
xray setting test URL, which is reason enough to close the gap.

The deprecated and local-use prefixes are blocked outright since nothing
public routes through them. The NAT64 well-known prefix is judged by the
IPv4 it embeds instead: on a DNS64 network every public IPv4 host resolves
into it, so blocking it wholesale would break legitimate fetches.
2026-08-19 19:37:14 +02:00
Sanaei 3c087f6fd9 chore(docs): update dependencies and adapt to zbsearch 4
fumadocs-core 16.14.5 switched its search engine from Orama to zbsearch 4,
so the panel docs follow it up to the same major.

zbsearch 4 still rejects locale codes as tokenizer languages ("en" throws,
only "english" is accepted), so the custom search dialog that forces an
English index stays necessary — verified by loading the built static index
for all four locales and searching it through fumadocs' own client.

Around that:
- use `staticClient`, as `oramaStaticClient` is now a deprecated alias
- drop @orama/orama, which nothing depends on or imports any more
- correct the two comments that still described Orama and pointed at its
  docs and tokenizer package, one of them suggesting a language zbsearch
  does not have
- restore the corepack integrity hash on `packageManager`, which CI reads
  through pnpm/action-setup
- prune minimumReleaseAgeExclude entries for versions no longer installed

The API reference MDX changes are serialization-only: fumadocs-openapi
11.2.4 emits plain scalars where it used folded ones. Parsed frontmatter
and page bodies are unchanged.
2026-08-19 18:38:40 +02:00
Sanaei ce63bf3e66 fix(frontend): restore the two rolldown bindings npm dropped from the lockfile
The from-scratch lockfile regeneration in b9eda09d bumped rolldown 1.2.4 ->
1.2.5 but wrote back only 14 of its 16 optional platform bindings: npm
removed the old @rolldown/binding-darwin-x64 and
@rolldown/binding-linux-arm64-gnu entries and never added the 1.2.5 ones.
Both are still listed in rolldown's optionalDependencies, so the packages
section no longer matches the dependency graph.

npm ci validates the whole ideal tree, not just the packages installable on
the current platform, so it aborted with EUSAGE everywhere and took down all
four workflows that install the frontend - CI, Release, CodeQL and Docs
Deploy - each at its first npm ci step. The Go jobs were unaffected.

Regenerated with a clean npm install --package-lock-only, which resolves from
registry metadata alone and keeps every optional binding regardless of the
host platform. The diff is purely additive - the two missing blocks, no
version changes.
2026-08-19 18:18:49 +02:00
Sanaei b9eda09da9 chore(frontend): update dependencies and adapt to oxlint 1.79
npm install was failing with ERESOLVE: the lockfile pinned storybook 10.5.7
and vitest 4.1.10 as peers while package.json asked for ^10.5.9 and ^4.1.11,
and npm would not move either. Neither npm update, a targeted install, nor
--package-lock-only broke the cycle, so node_modules and package-lock.json
were regenerated from scratch (601 packages, 0 vulnerabilities).

oxlint 1.79.0 then promoted five React Compiler rules into the correctness
category, flagging 101 pre-existing sites. 1.78.0 exits 0 on the same tree,
so nothing in our code changed - the rule set grew. They are fixed rather
than suppressed:

- refs (31): latest-value ref writes moved out of render into an effect.
  onlineClientsRef turned out to be write-only and is gone; expireDiffRef
  and trafficDiffRef were replaced by reading the values directly.
- set-state-in-effect (55): reset-on-open modals now adjust state during
  render; where an effect mixed a synchronous reset with an async fetch, the
  reset moved to render and the effect kept only the request. useMediaQuery
  became useSyncExternalStore.
- preserve-manual-memoization (11): optional-chained deps the compiler cannot
  match, hoisted to locals or dropped where the memo wrapped a string concat.
- purity (3): Date.now() in render replaced by a state-backed clock, which
  also refreshes the expiry tag every 60s instead of freezing it until the
  next unrelated re-render.
- immutability (1): applyClientStatsEvent merged websocket traffic into
  DBInbound rows in place; it now rebuilds only the rows it touches.

Two things fell out of that. clientCount is derived with useMemo instead of
an imperative rebuildClientCount() called from five sites, which also fixes a
staleness bug where changing the expiry or traffic threshold left the counts
alone until some later rebuild. statsVersion existed only to force a
re-render after an in-place mutation, is meaningless now that rows are
replaced, and nothing read it, so it is removed.

Also adds a lint:fix script - oxlint --fix was previously only reachable
through the lint-staged hook.
2026-08-19 17:48:28 +02:00
Sanaei 92fb94d856 Move to TypeScript 7 and the oxc toolchain (oxlint + oxfmt) (#6262)
* chore(frontend,docs): move to TypeScript 7 and replace ESLint with oxlint

TypeScript 7 is the native Go port and ships no programmatic compiler
API, so typescript-eslint cannot run at all: it peer-pins
typescript >=4.8.4 <6.1.0 (canary too) and hard-crashes with
"typescript-eslint does not support TS 7.0". Upstream support is
tracked in typescript-eslint#10940 and targets TS >=7.1.

Rather than wait, or carry Microsoft's side-by-side alias (which keeps
a second TS 6 install alive purely to feed the linter), both projects
move to oxlint, which never depended on the TypeScript API.

Typecheck drops from ~9.7s to ~2.2s and 167 packages leave frontend/.

oxlint has no no-restricted-syntax, so the #6121/#6127 cleared-
InputNumber guard is reimplemented as a JS plugin in
frontend/tools/oxlint/. It was verified to still fire in
pages/settings/** and pages/xray/** and to stay exempt in *Modal.tsx.

The type-aware @deprecated sweep survives too, as
`npm run lint:deprecated`: oxlint's type-aware mode runs on
oxlint-tsgolint, which drives the TS 7 typescript-go checker, so the
TS 7 move is what makes it possible.

Behaviour is preserved rather than tightened. jsx-a11y/prefer-tag-over-role
is off in both configs because it was never part of the recommended sets
ESLint actually ran, and oxlint honours the existing eslint-disable
comments, so no source churn was needed.

Two real fixes fell out of the stricter linting:
- outbound-link-parser.test.ts used `out?.streamSettings` behind an `as`
  cast, which hid the optional chain from ESLint and would throw on a
  null parse; the rest of the file already used `out!`.
- InputAddon's conditional role/tabIndex/onKeyDown is genuinely
  accessible but oxlint cannot evaluate it, so it gets a scoped disable.

* chore(docs): replace Prettier with oxfmt

oxfmt is the oxc project's Prettier-compatible formatter, so this pairs
with the oxlint move and drops the last JS-based tool from the docs
toolchain.

The swap is behaviour-preserving. Running Prettier and oxfmt over the
same files, with the existing .prettierrc.json settings migrated via
`oxfmt --migrate=prettier`, produces byte-identical output on every
file. (Comparing them outside the project directory is misleading:
Prettier silently falls back to its defaults when it cannot find its
config, which looks like a mismatch but is not one.)

The 18 files reformatted here were already failing `pnpm format:check`
before this change — Prettier wanted the exact same edits. The check is
not part of docs-ci.yml, which is why the drift went unnoticed.

.prettierignore becomes ignorePatterns in .oxfmtrc.json, keeping the
deliberate MDX exclusion: reflowing MDX prose merges headings into
paragraphs and collapses lists inside Steps/Callout components. Both
that and the generated fumadocs-openapi reference output were verified
untouched.

oxfmt is pinned to 0.63.0 rather than latest. pnpm 11's built-in
minimumReleaseAge policy rejects same-day releases, and 0.64.0 would
have made pnpm silently append 20 waiver lines to pnpm-workspace.yaml.

* style(frontend): adopt oxfmt and format src

frontend/ has never had a formatter, so this reformats 344 of 497 files
in src/. The change is purely whitespace, quoting and line wrapping —
no logic is touched. It is kept in its own commit so it does not bury
the TypeScript 7 / oxlint migration or the git blame for the code
itself.

Settings match docs/ and the code as it was already written: single
quotes, semicolons, trailing commas, 2-space indent, 100 columns. That
was measured rather than assumed — src/ was already uniformly
single-quoted and 2-space indented, with p90 line length at 75.

Formatting is scoped to src/ (mirroring `oxlint src`) and
.oxfmtrc.json ignores src/generated. Both matter: `make gen-check`
compares src/generated and public/openapi.json, and
`make msw-worker-check` byte-compares public/mockServiceWorker.js
against the installed MSW runtime, so reformatting any of them breaks
the gate.

Reflowing also moves `eslint-disable-next-line` comments off the line
they guard, which broke two suppressions that had been silently
correct before:
- clone-inbound-modal.test.tsx: the object literal became multi-line,
  leaving `} as any;` four lines below its no-explicit-any disable.
- ClientsPage.tsx: the useMemo dependency array moved onto its own
  line, out from under its exhaustive-deps disable.
Both comments were relocated onto the line they actually guard, and
verified to still suppress by removing them and watching the errors
return.

* ci: enforce formatting in CI and make verify

Adding oxfmt in the previous two commits gave both projects a formatter
but nothing that checks it, which is how docs/ had already drifted to 18
unformatted files: docs-ci.yml runs typecheck, lint, test and build, but
never format:check, so Prettier's complaints were only ever visible to
whoever ran it by hand.

Wire `format:check` into the frontend job in ci.yml and the docs job in
docs-ci.yml, and add a `format-check` target to `make verify` so the
local gate keeps mirroring CI as the Makefile header promises.

Verified the step actually bites rather than passing vacuously: adding
a badly formatted line to a source file in each project makes both
`make format-check` and `pnpm format:check` fail, and reverting it makes
them pass again.

No workflow referenced ESLint or Prettier by name — they all invoke the
package scripts — so the tooling swap needed no other CI changes.

* ci: trigger CI on Makefile changes

The path filters listed **.go, go.mod, go.sum, frontend/**, .nvmrc and
ci.yml itself, but not the Makefile — so a change to the canonical task
runner that ci.yml is meant to mirror could land without any job
running. The previous commit, which edits both, only triggers because
it happens to touch ci.yml too.

* fix(frontend): replace deprecated Ant Design 6 APIs in the geo components

`npm run lint:deprecated` reported five uses of props Ant Design 6 has
deprecated. All five are gone, and the matching runtime warnings no
longer appear in the test output.

Tag `bordered={false}` becomes `variant="filled"` and Space `direction`
becomes `orientation`; both are the one-to-one replacements named in
antd's own deprecation messages, and `direction`/`orientation` share the
same Orientation type.

Input `addonAfter` is the one that is not a rename. It becomes a
`Space.Compact block` wrapping the Input and the browse Button, which is
antd's documented migration. `block` keeps the field filling its form
row as the addon did. Note this is a deliberate visual change: the
button used to be a borderless `type="text"` icon sitting inside the
addon's grey box, and is now a regular button whose border joins the
input. The tooltip, aria-label, ref, id and onBlur wiring are unchanged,
so the react-hook-form binding in RuleFormModal and the existing tests
still address it the same way.

Only these five were deprecated. The other `bordered` props in the tree
sit on QRCode, Table, Descriptions and Alert, where the prop is not
deprecated, and these were the only two Space `direction` uses in the
codebase.

* fix(frontend): restore lint rules lost in the oxlint migration, and test the guard

Addresses the review on #6262.

The frontend config re-enabled only no-explicit-any and no-unused-vars
and left the rest of tseslint's recommended set to oxlint's correctness
category. It does not cover all of it. Confirmed by linting one probe
file against both configs: docs/ (which enumerates the rules) reports
all nine, frontend/ reported four. So ban-ts-comment,
no-empty-object-type, no-namespace, no-require-imports and
no-unsafe-function-type had silently stopped being enforced — a `//
@ts-ignore` or a `namespace` block would have landed unflagged. The ten
rules are now mirrored from docs/.oxlintrc.json, and src/ still passes.

The #6121/#6127 guard was 57 lines of hand-written AST walking with no
test. It now has one: fixtures for the three banned shapes plus an
onNumber()-wrapped control, asserting the rule fires three times and
that .oxlintrc.json still wires it to the right paths. Verified it fails
for the right reason by making walk() enumerate nothing, which is the
silent-death mode the review described — the traversal depends on
Object.keys() seeing AST children as own enumerable properties.

The fixtures deliberately violate the rule, so their oxlint config is
named guard.oxlintrc.json rather than .oxlintrc.json: oxlint discovers
nested configs by directory, which would otherwise turn the fixtures
into three lint errors. The test passes it explicitly with -c.

Also from the review:
- lint and format now cover tools/ as well as src/, so the one piece of
  hand-written lint logic in the repo is no longer the least covered
  file in it.
- lint-staged runs oxfmt before oxlint --fix. Formatting became a hard
  CI gate in this PR while the hook only ran the linter, so a commit
  could pass the hook and fail CI on formatting alone.
- .oxfmtrc.json ignores public/, so the artefacts that make gen-check
  and make msw-worker-check byte-compare stay safe even if oxfmt is
  invoked without a path argument.
- The MDX and generated-reference rationales that .prettierignore
  carried are back as comments in docs/.oxfmtrc.json — oxlint and oxfmt
  both accept JSONC, so relocating them was unnecessary.

Not applied: the review also suggested restoring ../internal/web/dist to
the ignore lists. Both tools reject `..` patterns outright ("patterns
are resolved within the config file's directory"), and being outside
frontend/ it is unreachable anyway.
2026-08-19 15:36:27 +02:00
Duxxie 380aff4d82 Add remote routing URL support (#6168)
* Add remote routing URL support

* Harden remote routing refresh

* fix(sub): harden remote routing fetch and accept Mihomo src rule flag

Remote routing bytes reach the YAML/JSON parsers from goroutines that run
outside Gin's recovery, so a parser panic on crafted input would take down
the whole panel. Contain it in fetch() (a panic now degrades to a failed
refresh that keeps the last-good value and releases the in-flight slot)
and start the refresh, cache-load and startup-warm goroutines through
common.GoRecover like the other background workers.

The route-graph validator only skipped a trailing no-resolve flag, so a
valid Mihomo rule like IP-CIDR,x,DIRECT,no-resolve,src was rejected as an
unknown target; skip both option flags.

Also deduplicate the HTTPS-source classification into
common.ParseRemoteRoutingURL so the save-time validator and the resolver
can never drift (internal/sub imports internal/web/service, so the copy
existed only to avoid the import cycle), move the test-only
mergeRemoteClashRulesYAML helper into the test file, and trim oversized
comment blocks.

---------

Co-authored-by: Duxxie <yelloduxx@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 16:02:11 +02:00
korsun009 3a2f9b48da feat(web): add network-only PWA installability (#6190)
* feat(web): add network-only PWA installability

Serve the manifest, registration script, network-only service worker, and icons under the runtime web base path so panels remain installable at arbitrary configured URLs.

This does not add offline caching or change panel, API, database, or Xray behavior.

* chore(docs): remove development planning notes

Keep the pull request focused on the PWA implementation, tests, and user-facing verification documentation.

* feat(web): adopt the 3X logo PWA icon set from #1865

Replace the two placeholder SVG icons with the six-size PNG set
(16/24/32/64/192/512) contributed by @Incognito-Coder in PR #1865.
The PNGs have transparent rounded corners, so the manifest entries
drop the maskable purpose claim and rely on the default any.

---------

Co-authored-by: korsun009 <277924786+korsun009@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 15:33:20 +02:00
n0ctal 3f1dd4bf5a fix: follow-ups from the post-merge reviews of #6221, #6227, #6230 and #6239 (#6250)
* fix: follow-ups from the post-merge reviews of #6221, #6227, #6230 and #6239

Six defects the automated reviews found after those PRs merged. Each is
verified rather than taken on trust — two by experiment, the rest by
reading the merged code.

**Import restore never wrote an empty local value** (#6227). GORM builds
the assignment map from the struct passed to Assign and drops zero-valued
fields, so `Assign(model.Setting{Value: ""})` produced an empty Updates
and the imported row survived. Empty is the normal state: UpdateAllSetting
writes a row for every AllSetting field including the blank ones. That is
exactly the case the PR existed for — a destination with no certificate
inheriting the source machine's path. Confirmed with a throwaway test
before changing anything: the value stayed "IMPORTED". Now uses
saveSetting, which is not zero-filtered.

**Import destroyed node mTLS material** (#6227). The "no local row means
the default applied, so drop the import" branch fires for the five
nodeMtls* keys, which are minted on demand and deliberately absent from
AllSetting, so a fresh install has no row for them. Reinstall-then-restore
therefore deleted the CA certificate and its private key — and the backup
was the only copy, since neither is surfaced in the UI or the export.
Those keys are now kept.

**The clients-list enable toggle wiped renewal state** (#6239, #6238).
setEnable hand-builds the update payload and carried reset but not
resetDay or resetMax, so one click on the switch turned calendar mode off
and lifted the renewal cap permanently. The form-modal tests could not
catch it because that path does send both fields.

**"Delete depleted clients" deleted calendar clients** (#6239). The
predicate read `reset = 0` as "does not auto-renew", which is exactly the
calendar shape, in two places. Both now share one constant that also
requires `reset_day = 0`.

**Allowlist validation and parsing disagreed** (#6230). Save used net,
scan used netip, and they differ: `198.51.100.0/024` saves without
complaint and is silently dropped at scan — the failure the PR set out to
remove. Verified by running both parsers. An IPv4-mapped prefix parsed but
could never match, because contains() unmaps the query while the prefix
stayed 128-bit; it is unmapped at parse now. A test asserts the two
acceptance sets agree.

**A comment stated the opposite of the truth** (#6221). GetInbounds has no
enable filter, so a node reports a disabled inbound normally; the row in
that bug report was missing only because it was never delivered. Reworded
to the real invariant.

Also trims two comment blocks in ip_limit_allowlist.go to the repo's
two-line maximum.

Not included: the reviewer's suggestion to lift the node hand-off out of
`if inbound.Enable` in AddInbound. It is the right root-cause fix, but it
changes delivery behaviour on multi-node deployments and belongs in its
own change with its own testing, not in a cleanup batch.

One reported finding is not real: BulkCreate does call
validateClientResetDay, validateClientResetMax and
validateClientTrafficReset — verified in the merged tree.

* fix(netsafe): wrap both errors so errorlint passes

Unrelated to this PR's subject and in a file it does not otherwise touch.
It is here only because CI lints the merge result, and `main` has been red
since #6242 landed: `fmt.Errorf("%w; %v", ...)` wraps the first error and
formats the second, which errorlint rejects. Go 1.20 allows more than one
%w, so both are wrapped now and `errors.Is` works against either.
2026-08-18 15:24:59 +02:00
jason zhang abd320994a Add per-client external link controls (#5650)
* Add enable toggle for external client links

* Document external link enable API fields

* Extend external client link metadata

* Fix external subscription cache status updates

* fix(sub): address the review on per-client external link controls

Blocking: the expiry filter dropped legacy rows. expiry_time was added
without a default, so AutoMigrate makes it nullable and backfills NULL,
and `expiry_time = 0 OR expiry_time > ?` is false for NULL under
three-valued logic — every external link written before the upgrade
vanished from all subscriptions. Add `default:0` on expiry_time and
last_fetch_at, make the predicate NULL-tolerant, and backfill the NULLs
a pre-fix build could already have written.

Rework fetch-status recording. It ran inside the singleflight in-flight
window, so every goroutine parked on the shared fetch waited for a DB
write to commit on the public, unauthenticated subscription path — and
because it was keyed on the row id, waiters and cache hits recorded
nothing, leaving rows that lost the race stuck on "Not fetched yet"
forever. fetchSubscriptionLinks now reports whether it did the network
fetch and expandEntry records afterwards, off the serving path, keyed on
kind+value so every row sharing the URL is stamped by the one fetch.
Keying on value also closes the recycled-rowid hazard: saves delete and
re-insert rows, and SQLite reuses rowids, so an in-flight write could
land on an unrelated client's row. The write no longer discards its
error either.

Drop the inert id round-trip. The panel never sent it, and the byId
branch was guarded by the exact kind+value equality that byKindValue
already keys on, so it could not change an outcome. Matching on
kind+value alone is what actually preserves fetch status across saves.

Reject a negative expiryTime instead of storing a row that is silently
invisible in every subscription — elsewhere a negative expiryTime means
"a duration from first use", so an API caller reusing that convention
got no error and no links.

Drop the ~50 lines of .client-form-* / .client-inbounds-field CSS that
no component renders; it is leftover from the WireGuard PR this one was
split from.

i18n: reuse the already-translated pages.inbounds.leaveBlankToNeverExpire
instead of shipping an English duplicate under pages.clients, and
translate namePrefix, lastFetchAt, lastFetchError and neverFetched into
all 12 non-English locales.

Cover the persistence path that had no test: the fetch-status writer over
a real DB against a failing then a succeeding server, a cache hit writing
nothing, and the negative-expiry rejection.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-08-18 13:55:04 +02:00
shustovTE 708a69acde fix(reality): make the REALITY target check usable on a private network (#6242)
* fix(reality): make the REALITY target check usable on a private network

The probe dials through netsafe.SSRFGuardedDialContext, so a fronting service
reachable only inside the deployment (a Docker service name, a LAN address)
always failed with "blocked private/internal address": the inbound itself
works, because the guard sits in the probe path only, so the panel reported a
red verdict on a healthy configuration. Instead of a panel-wide setting that
lifts the guard for good, the guard is now lifted per probe and only after the
operator confirms the local-network warning in a modal; the verdict keeps
privateTarget set, so a passing local check stays a warning rather than a
green success.

The probe also sent the target host as SNI. Clients dial the target but send a
name from serverNames, so a fronting proxy answered with its default
certificate — a Traefik front reached as "traefik" reported "certificate is
valid for <hash>.traefik.default, not traefik" on a deployment whose clients
get a valid chain. The panel now sends the first configured serverName as SNI
and the certificate is verified against it; empty serverNames keeps the old
fallback. The reported target stays the dialled address, so a passing check no
longer rewrites the target field with the SNI host.

The result panel reports what was actually seen: the SNI used, the certificate
subject/issuer and its expiry stay visible when the chain is untrusted (with
"Not trusted" appended) instead of being replaced by that verdict alone.
Certificate names are copied into the SNI field only when the chain verified —
the names on a proxy's default certificate would otherwise become the SNI of
the next check.

The bulk/CIDR scanner keeps the guard unconditionally: honouring the opt-in
there would turn it into an internal network scanner.

* fix(reality): recover from a stale SNI and report a refused address reliably

Review follow-up on the REALITY target check.

The probe sends the stored serverNames as SNI, and the panel only wrote names
back when the whole chain verified, so switching Target while the SNI field
still held the previous target's names failed every rescan: the new target's
real names came back from the probe but were discarded with the verdict. The
certificate is now checked in two steps — chain first, then the name — and a
trusted chain presented for other names is enough for the panel to offer those
names, so the next scan passes. Picking a row in the bulk scanner replaces the
names outright, since keeping the previous target's SNI leaves a REALITY config
that cannot work.

SSRFGuardedDialContext kept the refusal only in lastErr, so on a dual-stack
name a refused private address followed by a failing public one lost the
sentinel and the panel silently skipped the confirmation. The refusal is now
tracked separately and reported alongside the last dial error.

Honouring the opt-in is logged with the target and the resolved address, since
it bypasses the SSRF guard on an authenticated endpoint. The read-only SNI row
in the result is labelled "SNI used" so it no longer collides with the SNI
field below it, and the comment blocks are back within the 2-line limit.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-18 13:47:59 +02:00
n0ctal f75ea08ab4 fix(frontend): keep the MSW worker in step with the lockfile (#6222)
The tracked frontend/public/mockServiceWorker.js is generated by msw and pinned
at 2.14.7, while package-lock.json installs 2.15.0. msw rewrites the worker on
postinstall, so npm ci leaves the tree dirty on a clean checkout and every
contributor either commits an unrelated 30-line diff or discards it.

Regenerate the worker for the locked version and add a check that compares it
against the installed runtime, wired into make verify and CI so the pair cannot
drift again.
2026-08-18 13:44:55 +02:00
n0ctal 5c7ca5b579 feat(clients): give each client its own traffic reset cycle (#6240)
* feat(clients): give each client its own traffic reset cycle

Traffic reset is configured on the inbound, so every client sharing an
inbound resets together. An operator running a monthly 1000GB plan and a
weekly 200GB plan side by side has to press Reset Traffic by hand.

Clients now carry the same trafficReset / trafficResetDay pair the
inbound already has, with the same vocabulary and the same monthly
due-day rule, and PeriodicTrafficResetJob makes a second pass over the
clients whose own cycle matches the period it is running for. A client
that leaves the field at never behaves exactly as before: only its
inbound's schedule can reset it.

The fields live on ClientRecord as well as in the inbound settings JSON,
so an ordinary edit does not write the cycle back as empty, and an
unknown period is rejected rather than coerced, since a coerced value
would read as configured while no job would ever select the client.

Cron expressions and a custom post-reset quota from the issue are left
out: both are separate decisions, and neither has an inbound-level
counterpart to stay consistent with.

* fix(clients): make the per-client reset cycle editable and safe to run

Review found three things wrong with the first cut, one of them mine and
worse than the bug it replaced.

The cycle could only be set at creation. ClientService.Update writes the
columns directly only for a client with no inbounds; the normal path goes
through SyncInbound and applyClientRecordMerge, which this change had not
extended, so an edit updated the settings JSON while the clients column
kept the old value and the job kept applying the old cycle. The earlier
test passed because it asserted the value survived an unrelated edit,
which it did precisely because nothing ever wrote it. Replaced with a
test that changes the cycle and switches it off again.

Avoiding the re-enable that ResetTrafficByEmail performs was wrong.
Depletion disables clients.enable and the settings JSON as well as
client_traffics.enable, so lifting only the quota gate left a depleted
client out of the generated config with zeroed counters, which no longer
match the depleted predicate: locked out permanently. The rule is now
about cause, not state — a client the quota switched off is restored, one
disabled below its quota was switched off by hand and is skipped.

The bulk path also bypassed node propagation and the MTProto sidecar
quota that ResetTrafficByEmail handles, so it silently did nothing on
node-backed inbounds. Dropped in favour of the integrated path, whose
needRestart is now collected and turned into a single SetToNeedRestart.

Also adds the AutoMigrate NULL backfill, guards the merge so a stale node
snapshot cannot erase a configured cycle, validates the bulk-create and
import paths, normalizes the day the way the inbound path does, marks the
fields omitempty so existing clients match the published contract, and
shares one TRAFFIC_RESETS tuple between the three forms.

* fix(clients): validate renew fields on the bulk and import paths too

BulkCreate and ImportClients insert client records without going through
Create, so the resetDay/resetMax checks added with the calendar renewal
(#6239) and the renew cap (#6238) never ran there. An API caller could
store resetDay 45 or a negative resetMax, values the renewal query then
mishandles silently. Mirror Create's validation on both batch paths, next
to the trafficReset check they already carry.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 13:08:44 +02:00
n0ctal b8903fadf4 feat(clients): renew on a calendar day instead of a rolling interval (#6239)
* feat(clients): renew on a calendar day instead of a rolling interval

Auto-renew advances the expiry by a fixed number of milliseconds, so a client
set to 30 days drifts against the calendar: renewing on 31 January lands on
2 March, and by the end of the year the billing day has wandered a fortnight
from where the operator's own plan resets.

Add a per-client renewal day. When set, the expiry steps whole calendar months
at midnight in the panel's time zone. A month too short for the chosen day
renews on its last day and the following month returns to the chosen one, so
the 31st does not decay into the 28th permanently.

Zero keeps the interval mode, so existing clients are untouched.

The interval branch now also refuses a zero step. It is unreachable while the
selection filter holds, but that loop runs on the single traffic writer, and a
zero interval there would hang every panel mutation behind it.

* fix(clients): persist the calendar renewal day on the client record

resetDay lived only in the inbound settings JSON and client_traffics, so
every path that rebuilds a client from the clients table wrote it back as
zero: an ordinary edit, an attach to a second inbound, a traffic reset on
a disabled client. Calendar mode turned itself off during normal use and
the operator only found out a month later.

Adds reset_day to ClientRecord and threads it through ToRecord, ToClient,
applyClientRecordMerge and the record update map, so the value survives
the round trip. The clients page filter and ClientSlim now recognise the
mode, nodeClientRenewed classifies a calendar renewal as a renewal, the
node snapshot merge carries reset_day, and the service layer rejects a
day outside 0-31 rather than clamping it silently.

Also renames the label keys to renewOnDay to keep them apart from the
existing renewDays, translates them and the new RESET_DAY subscription
placeholder in all 13 locales, adds the field to the bulk-add modal, and
drops the stray internal/web/dist/.gitkeep build stub.

* fix(clients): let the billing day be changed after creation

ClientService.Update writes the record columns directly only for a client
with no inbounds. The normal path goes through SyncInbound and
applyClientRecordMerge, which this change had not extended, so moving a
client from the 20th to the 5th updated the inbound settings JSON while
clients.reset_day kept the old value and the renewal kept using it.

The existing test did not catch it: it asserted the day survived an
unrelated edit, and it survived precisely because nothing on that path
ever wrote it. TestClientEditChangesTheBillingDay moves the day and then
switches calendar mode off again; removing the record write turns it red.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 12:46:00 +02:00
Sanaei 1872659d83 chore(gitignore): fully ignore internal/web/dist, build stub included
The !internal/web/dist/.gitkeep exception kept the dist build stub
permanently visible as untracked noise and let it slip into commits four
separate times (each reverted with a 'drop the accidentally committed
dist build stub' commit). Nothing under dist/ is ever meant to be
tracked — make dist-stub and CI recreate the stub on disk — so drop the
whole exception block and let the plain dist/ rule cover it.
2026-08-18 12:42:49 +02:00
Sanaei 6638ac4a1e i18n: translate importKeepHostSettings keys
Translate the `importKeepHostSettings` and `importKeepHostSettingsDesc` keys from English placeholders into 10 locale files (ar-EG, es-ES, fa-IR, id-ID, ja-JP, pt-BR, tr-TR, vi-VN, zh-CN, zh-TW).

Also removes `main_test.go` which contained a test for a `commandHelp` function.
2026-08-18 12:27:33 +02:00
n0ctal d6472740dc feat(limitip): let operators exempt trusted addresses from the IP limit (#6230)
* feat(limitip): let operators exempt trusted addresses from the IP limit

Behind a shared address — an office gateway, a campus NAT, a residential
carrier — every user looks like the same client. One of them trips the IP
limit and the address is disconnected and handed to fail2ban, taking the
others with it. Today the only way out is editing jail.d by hand, which an
update overwrites.

Add an allowlist setting of addresses and networks. A matching address is
neither banned nor counted towards the limit: counting it would still cut the
shared network the entry exists to protect.

Entries are validated on save rather than skipped at scan time — a typo would
otherwise leave the address unprotected until someone noticed the bans.

* fix(limitip): keep each doc comment on its function and one grammar for the list

Three review follow-ups. loadAllowlist landed between hasLimitIp's doc comment
and hasLimitIp itself, so godoc showed one function's rationale above another's
body; it now sits after that function with its own comment.

The parser advertised semicolons and whitespace as separators while the
settings validator accepts commas only, making those forms unreachable through
the panel and the API — a promise the software never keeps. Both sides now read
the same comma-separated grammar.

The dist stub was a build artifact and does not belong in the tree.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

* chore(i18n): translate the IP limit allowlist strings into the remaining locales

Ten locales carried the English source text verbatim; only ru-RU and uk-UA
were translated. The i18n dead-key test only checks that a key exists in every
file, so an untranslated value passes it silently.

Wording follows each locale's existing terms: the ipLimit noun already in the
file, and the comma-separated IP/CIDR phrasing from trustedProxyCidrsDesc.

* refactor(limitip): share one IP/CIDR list validator and read the allowlist only when enforcing

The allowlist check in CheckValid was a line-for-line copy of the trusted-proxy
loop directly above it. Both now call one helper, each passing its own message,
so the two lists cannot drift apart.

Run() read the allowlist on every 10s scan, including the majority of panels
where no client carries an IP limit and the value is discarded. It is now read
only once enforcement is known to apply.

CheckValid had no test for either list. The new one pins that a malformed entry
is rejected and that each list still names itself in the error, which is what
the shared helper could otherwise break.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 12:23:10 +02:00
n0ctal 6e80a468e3 feat(server): keep this machine's own settings when importing a database (#6227)
* feat(server): keep this machine's own settings when importing a database

Import replaces the database wholesale, so the uploaded file's listen
addresses, ports, base path, certificate paths and node identity land on the
destination. Moving a configuration to a new host therefore leaves the panel
answering on an address it does not own, presenting certificates it does not
have, and claiming the source machine's identity towards its nodes.

Capture the host-bound settings before the swap and write them back once the
imported database opens. Everything else — inbounds, clients, templates, the
rest of the settings — still comes from the file.

A checkbox controls it, defaulting to keeping this machine's values; clearing
it restores the old behaviour for anyone deliberately cloning a host.

* fix(server): drop imported host settings this machine never had, and cover Postgres

Two gaps in the previous commit. The snapshot only recorded rows that existed,
so a key with no row here — the default for every certificate path, both listen
addresses and all the node mTLS material — kept the imported value: exactly the
case the change is meant to fix. The snapshot now records which keys were
absent and deletes the imported row for them, letting the default apply again.

The PostgreSQL path took the flag and ignored it, so a dump restore still
adopted the source machine's settings. It now captures and restores the same
way the SQLite path does.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-18 12:03:52 +02:00
n0ctal e940f30bb8 feat(clients): cap how many times a client may auto-renew (#6238)
* feat(clients): cap how many times a client may auto-renew

Auto-renew today runs forever: a prepaid or fixed-term client keeps being
handed new periods until an operator remembers to switch it off. There is no
way to say "renew this three times, then let it lapse".

Add a per-client maximum. Zero keeps today's behaviour, so nothing changes for
anyone who does not set one. When the count is reached the client is simply
left to expire, like any client without auto-renew.

Catching up several missed periods spends one allowance per period. A client
that was away for three cycles must not receive three of them free of the cap,
and the catch-up stops at the last period the cap paid for rather than jumping
to the present.

* fix(clients): persist the auto-renew cap and stop the capped churn

resetMax lived only in the inbound settings JSON and client_traffics, so
every path that rebuilds a client from the clients table wrote it back as
zero. The edit dialog showed 0 for a capped client, and saving an
unrelated comment change lifted the cap; an attach or a traffic reset did
the same with no operator action at all.

Adds reset_max to ClientRecord and threads it through ToRecord, ToClient,
applyClientRecordMerge, the record update map and ClientSlim, so the cap
survives the round trip.

When the cap truncates a catch-up the client is still expired, but the
renewal side effects fired anyway: counters were zeroed for periods it
can never use, and it was enabled and pushed to xray only for
disableInvalidClients to undo both in the same transaction. Those are now
skipped when the new expiry has not reached the present.

Also makes any non-positive resetMax mean unlimited instead of silently
meaning "never renew again", rejects a negative one at the service layer,
surfaces renewals used against allowed in the client info modal so the
operator can see what to raise, adds the field to the bulk-add modal,
translates the labels in all 13 locales, and drops the stray
internal/web/dist/.gitkeep build stub.

* fix(clients): let the renewal cap be changed after creation

ClientService.Update writes the record columns directly only for a client
with no inbounds. The normal path goes through SyncInbound and
applyClientRecordMerge, which this change had not extended, so raising a
cap from 3 to 6 — the natural action when a customer buys another block
of periods — updated the inbound settings JSON while clients.reset_max
kept the old value and the renewal query kept enforcing it.

The existing test did not catch it: it asserted the cap survived an
unrelated edit, and it survived precisely because nothing on that path
ever wrote it. TestClientEditChangesTheRenewalCap raises the cap and then
lifts it entirely; removing the record write turns it red.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-08-18 11:53:11 +02:00
n0ctal 6a674c7f0c fix(node): keep disabled inbounds the node snapshot cannot report (#6221)
* fix(node): keep disabled inbounds the node snapshot cannot report

A node builds its traffic snapshot from the inbounds Xray is actually running,
so an inbound with enable=false is never in it. The central sweep reads that
absence as "the node no longer has this inbound" and deletes the row, its
clients' traffic history and its port reservation — on a perfectly healthy
node, with no way to tell it apart from a real deletion.

Disabling an inbound in the panel and waiting one sync interval is enough to
lose it. Skip disabled inbounds in the sweep: their absence carries no
information, and an explicit delete still removes them.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.
2026-08-18 11:50:09 +02:00
n0ctal 81cfd8570e fix(inbounds): close the port check-and-claim race on the serial writer (#6225)
* fix(inbounds): close the port check-and-claim race on the serial writer

AddInbound reads the port conflict outside its transaction and then commits in
a bare db.Transaction, so two overlapping creates both pass the read and both
insert. UpdateInbound already runs on the single traffic writer, and so does
the node snapshot path; AddInbound is the one inbound writer left out.

Move it onto runSerializedTx and evaluate the conflict inside the transaction,
in both AddInbound and UpdateInbound. The check and the claim then commit
together on one goroutine, which closes the window on SQLite (immediate write
lock) and PostgreSQL alike without new schema, locks or configuration.

The wildcard/specific pair is the case worth naming: those are two distinct
rows, so no unique index can reject them — only the semantic check can, and
only if nothing can interleave between it and the insert.

* fix(inbounds): restore the port check UpdateInbound lost

The previous commit deleted UpdateInbound's pre-flight conflict check and never
added the in-transaction one, so editing an inbound onto an occupied port was
accepted outright. No test covered that path, so CI stayed green.

Evaluate the conflict inside the transaction, as AddInbound already does, and
add the regression test that fails without it.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-08-18 11:48:40 +02:00
n0ctal 5c9268c431 feat(i18n): translate the log levels, access events and calendar labels (#6226)
* feat(i18n): translate the log levels, access events and calendar labels

The log-level selector, the access-log event tags, the Sub Formats sidebar
entry and the calendar choices were hardcoded English, so a fully translated
locale still showed them in English on core screens.

Add eleven keys across the 13 locales and reference them. Russian and
Ukrainian are translated; the remaining locales carry the English string, the
same convention the existing files already use for untranslated entries.

Two module-level constants had to move: the calendar list and the access-event
map were built outside the component, where t is not in scope. The event map
now stores keys and resolves them at render.

* fix(i18n): keep the log export language-independent and fit the translations

Three follow-ups from review. The downloaded x-ui.log had started carrying the
translated event text, so its contents depended on the panel language and the
Russian value for PROXY contains a space in a field format whose other values
are single tokens. The export keeps DIRECT/BLOCKED/PROXY; only the on-screen
tag is translated.

The log-level select had a fixed 95px width sized for "Warning", which clips
"Предупреждение"; it now grows with its content.

The three access filters stayed English while the tags they filter became
translated, so they use the same keys.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-08-18 11:43:59 +02:00
n0ctal 2b1fe1fd02 ci: actually run the PostgreSQL schema and migration tests (#6224)
* ci: actually run the PostgreSQL schema and migration tests

TestHostAutoMigrateCreatesColumns_Postgres and TestMigrate_Postgres skip
unless XUI_DB_TYPE and XUI_DB_DSN are set. CI sets them only for the
durable-first step, so both tests have never run: a green pipeline says
nothing about the PostgreSQL schema or the migration path.

The job already has a PostgreSQL service. Point those two tests at it and
fail if either skips, the same guard the durable-first step uses.

* ci: make the PostgreSQL guard fail on a renamed test, and self-test the workflow

The guard asserted the absence of `--- SKIP`, which only catches a test that
ran and skipped. A renamed or deleted test makes `-run` match nothing, so
`go test` prints "no tests to run" and exits 0 — the step stays green while
testing nothing, which is the exact failure this PR set out to close.

Both steps now count `--- PASS` lines and require the expected number: at
least one for durable-first, exactly two for the schema tests.

Also adds `.github/workflows/ci.yml` to both `paths` filters so a change to
the workflow runs the workflow — without it this PR's own CI never fired and
the new step would first execute on main after merge — and hoists the
duplicated DSN to job-level `env`.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-08-18 11:38:14 +02:00
n0ctal dc1979a14c ci(release): stamp released binaries with their source revision (#6223)
* ci(release): stamp released binaries with their source revision

The release job builds `main.go`, which Go records as a file list rather than a
package, so the binary carries no VCS metadata at all: `go version -m xui-release`
reports command-line-arguments and nothing else. There is no way to tell which
commit a published binary came from, which is exactly what you want when a user
reports a bug against "the latest release".

Build the package with -buildvcs=true instead. Same output, same flags, plus
vcs.revision and vcs.time in the binary.

* ci(release): give the Windows job the git it needs to stamp

-buildvcs=true fails the build when it cannot read VCS state, and the MSYS2
shell the Windows job runs in has no git on PATH. Install it there so the
Windows binary carries the same revision as the Linux ones instead of the flag
turning into a build break.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
2026-08-18 11:37:03 +02:00
Sanaei 8cec47a8a5 fix(ci): resync the bot prompts with the repo and close the gaps an audit found
The three prompts still enforced the comment ban CLAUDE.md replaced with
the 2-line cap on Aug 1 (1ff90c5b), so the review bot would flag every
legitimate short comment; frontend/CLAUDE.md and CONTRIBUTING.md carried
the same stale rule. The PR reviewer's recipe for reading a post-change
file (headRefOid + pr diff) was unfulfillable with its allowlist - it now
fetches refs/pull/N/head and reads blobs via git show, object-only, no
checkout. Conventions the reviewer checks now include the unchecked docs
openapi.json copy step, the docs/lib/xray third link implementation, the
both-ways route contract, and the i18n dead-key half of the rule.

Also: drop the SUBPROCESS_ENV_SCRUB=0 override on the two untrusted-input
jobs (the mention job proves gh works scrubbed); teach the triage prompt
the issue forms (pre-applied labels, required fields, no re-asking); add
a security-report exception plus SECURITY.md so vulnerabilities are not
confirmed publicly; add a clarification follow-up job so a reporter's
reply to "clarification needed" is actually processed; review PRs again
on ready_for_review and skip drafts; stamp the reviewed head SHA so
force-pushes visibly date a review; scope gh issue/pr edit to label and
title flags; per-job concurrency; comment guards now match the actual
bot login after the run started; artifact names survive re-runs; the
mention prompt's repo map and env-var facts corrected (XUI_PORT,
XUI_TUNNEL_HEALTH_*, distro env files, memory.high, encrypt-tokens).
The bug and feature forms also referenced a "needs triage" label that
does not exist in the repo and was silently never applied - dropped.
2026-08-17 02:41:21 +02:00
n0ctal 4b0e9f9b60 fix(nodes): log the inbound the node snapshot removes centrally (#6219)
The orphan sweep deletes a central inbound and the traffic history of every
client on it, but wrote nothing. An inbound that vanishes minutes after being
created is then indistinguishable from one that never arrived, and the only
way to tell them apart is reading the source.

Name the node, tag, id and port so the removal is visible in the panel log.

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-16 14:02:50 +02:00
Rouzbeh† 5d6d98d1f9 fix(warp): preserve WARP Plus license key when changing IP (#6218)
ChangeWarpIP rotated the WireGuard keypair by registering a brand-new
Cloudflare device via RegWarp, which overwrites the stored warp data with
the fresh registration's empty license_key. The old key was then re-applied
only best-effort: any SetWarpLicense failure was swallowed with a warning
log, permanently deleting the saved WARP Plus key, and even on success the
response returned to the UI carried the pre-reapply snapshot (empty key).

Fix: write the old license key back into the stored warp data immediately
after RegWarp (before the remote upgrade attempt), so storage never loses
it; keep the remote re-apply as best-effort but surface its failure as a
warning field in the response; and return the final stored data so the
modal shows the preserved key. The auto-update IP job shares this path and
is fixed too. warpAPIBase is now a var so integration tests can point at a
mock Cloudflare API.

Co-authored-by: rqzbeh <rqzbeh@users.noreply.github.com>
2026-08-16 14:00:16 +02:00
Sanaei b53a5515d6 fix(frontend): make the jalali expiry clear button actually clear
persian-calendar-suite seeds today's date and emits it whenever it mounts
without a value. Clearing the expiry remounts the picker with a null value,
so the library immediately fired onChange(today) and the date came straight
back — and it also painted that seeded date into its read-only input.

Swallow the mount-time emit (re-armed on every clear-remount) and hide the
seeded text while the value is empty, so a cleared expiry stays empty and a
fresh client/inbound form no longer silently adopts today as its expiry.
2026-08-15 23:35:00 +02:00
sonic 3fa88adbd7 fix(inbounds): surface form validation errors (#6084)
* inbounds: surface form validation errors

React Hook Form validation previously returned early without showing why an inbound save was blocked. Report the first field error and switch to the corresponding form tab so operators can correct it.

* Fix inbound form tab error navigation

Improve react-hook-form error traversal so validation stops on real `FieldError` leaves (detected by `type`) instead of any object with a `message`. This makes Save reliably jump to the tab containing the first invalid field and show the specific error, avoiding the previous generic/ambiguous invalid-state handling.

---------

Co-authored-by: sonic <sonic@linux.do>
2026-08-15 23:09:48 +02:00
Farhan Zare 930a0ed59d feat(inbound): DisableFlow — opt an inbound out of auto XTLS Vision (#5689) (#5698)
* feat(inbound): add DisableFlow to opt an inbound out of auto XTLS Vision

Adds an inbound-level DisableFlow flag so operators can suppress automatic
xtls-rprx-vision injection on a specific inbound even when its transport is
flow-capable — e.g. a tunneled/CDN-fronted XHTTP+vlessenc inbound where Vision
is not wanted, while keeping it on the same client's Reality inbounds.

When set, the inbound reports tlsFlowCapable=false, the write path clamps each
attached client's flow to empty (so flow_override stores ""), and share
links/subscriptions never carry the flow for it. The flag is panel-only
metadata and is never sent to xray.

Closes part of #5689.

* feat(inbound): DisableFlow toggle in the inbound form (frontend)

Wire the DisableFlow field through the form schema + adapters and add a
VLESS-gated switch in the inbound form, plus en-US strings. tsc --noEmit and
eslint pass.

* fix(inbound): honor DisableFlow in all emitters + on toggle; regen OpenAPI

Addresses review on #5690:
- Clash (clash_service.go) and JSON (json_service.go) subscription emitters now
  also skip the flow for a DisableFlow inbound — previously only the raw
  share-link path was gated, so those two still advertised it (blocking 1).
- UpdateInbound now strips any flow already stored on a DisableFlow inbound's
  clients (settings.clients[].flow + client_inbounds.flow_override) so xray and
  the subscription agree; otherwise toggling DisableFlow on an existing Vision
  client left xray expecting a flow the client no longer sends.
- Regenerated the OpenAPI + zod/types/examples artifacts for the new field and
  added an example tag (blocking 2; make gen-check is clean).
- Added Clash + JSON DisableFlow suppression tests alongside the raw-link one.

* fix(inbound): make DisableFlow durable, clamp on create, guard live config

Addresses the review + completeness audit on #5690:
- UpdateInbound now persists inbound.DisableFlow onto the saved row. It was
  only read to branch strip-vs-restore, so toggling the flag on an existing
  inbound never stuck and MigrationRestoreVisionFlow re-injected the flow — the
  exact #5689 path (editing a multi-inbound client's inbound) self-reverted.
- DBInbound (frontend) declares + initializes disableFlow so ObjectUtil
  .cloneProps carries the API value through; the edit Switch previously always
  read false and re-saving silently reverted the opt-out.
- AddInbound strips client flow (settings + parsed clients) when DisableFlow is
  set, so a created-disabled inbound never persists a flow xray would expect.
- GetXrayConfig forces flow="" for DisableFlow inbounds (VLESS + Trojan) as
  defense-in-depth, keeping the live config and the subscription in agreement.
- genTrojanLink share link honors DisableFlow too.
- Drop the dead explicit flow_override clear in UpdateInbound (SyncInbound
  rebuilds it from the stripped settings).
- Clear disableFlow in the inbound form when switching to a non-VLESS protocol.
- Add disableFlow/disableFlowHelp to the remaining 12 locales.

Tests: stripClientFlows unit cases; DB-backed AddInbound clamp; UpdateInbound
persist+strip+resist-restore regression (fails without the persist fix);
frontend DBInbound + adapter round-trip (fails without the model field).

* style(inbound): drop // line comments per repo CLAUDE.md

The DisableFlow work followed the surrounding code's commenting style; the repo
CLAUDE.md forbids // line comments in committed Go/TS. Remove the comments I
added (Go + frontend + tests) and regenerate OpenAPI/schemas, which drops the
generated field descriptions sourced from the Go doc comments. No behavior
change; full go test (service+sub, CGO) + frontend typecheck/vitest green;
golangci-lint clean on the changed files.

* fix(runtime): propagate disableFlow to nodes

Preserve the inbound DisableFlow flag when syncing inbounds across nodes and when recreating central records from remote traffic snapshots. This keeps multi-node deployments from reintroducing VLESS Vision flow in node configs and share links, and updates the related tests to cover the wired field and VLESS JSON generation.
2026-08-15 23:09:16 +02:00
Sanaei f22df49a71 fix(sub): restore the subscription info page for browser visits
Revert 43bc9153 and its follow-up 338822ab. The copy-only notice replaced the
themed sub page for every browser request, so mobile users got a bare "This is
a subscription link" screen instead of their traffic, expiry and links — and it
left serveSubPage plus the custom-theme renderer as dead code.
2026-08-15 22:11:37 +02:00
n0ctal b4e4478699 feat(inbounds): add a narrow endpoint for subscription sort order (#6179)
* feat(inbounds): add a narrow endpoint for subscription sort order

Changing an inbound's position in subscription output currently goes through
/update/:id, which takes a whole inbound: the caller has to send settings and
the entire client list back, and whatever it read before the edit is what gets
written. Two people reordering and editing clients in the same inbound race on
one blob, and the reorder wins by overwriting.

Mirror the existing /setEnable/:id shape. The handler takes only the index and
the service reads the stored inbound, so nothing in the request can reach the
settings JSON. Node-owned inbounds are marked dirty in the same transaction and
pushed through the existing runtime update.

* fix(nodes): scope sub sort index updates

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 21:48:24 +02:00
n0ctal bab39393f1 fix(nodes): validate every certificate in the node mTLS trust bundle (#6188)
* fix(nodes): validate every certificate in the node mTLS trust bundle

AppendCertsFromPEM reports success once a single certificate parses, so a
trust bundle whose later entries are damaged or truncated was accepted with
those entries silently absent from the pool. Parse and validate every PEM
block instead, and reject the bundle if any of them is malformed.

* fix(mtls): reject malformed certificate bundle layout

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 21:31:31 +02:00
Sanaei 338822ab07 fix(sub): keep copy page within mobile viewport
Constrain the copy-only subscription page to the dynamic viewport, wrap long localized text, and infer text direction so mobile browsers cannot render a horizontally shifted desktop-width page. Add regression coverage for the responsive layout contract.
2026-08-15 21:16:13 +02:00
n0ctal 43bc915397 fix(sub): serve a copy-only page when a subscription URL is opened in a browser (#6183)
* fix(sub): show copy-only page for browser subscription visits

Browser navigation to /sub previously rendered the normal subscription page, which exposed subscription material in page data or raw base64 depending on request headers. Keep VPN clients on the raw subscription body, but classify browser document requests and return a neutral static copy-only HTML page with no embedded share links or page data.

This preserves the C1 LimitIP parser fix in the same master candidate while avoiding a DE rollback of the browser subscription UX.

* fix(sub): keep the themed page for an explicit html request

Only implicit browser navigation is downgraded to the copy-only page. An
operator who appends html=1 or view=html already holds the URL, so the
themed subscription page keeps rendering for them and serveSubPage stays
in use.

* fix(sub): keep browser pages copy-only
2026-08-15 18:18:03 +02:00
n0ctal dafd3c0e64 feat(sub): warn when salamander settings cannot reach the client (#6177)
* feat(sub): warn when salamander settings cannot reach the client

A hysteria2 share link carries obfuscation as obfs=salamander plus
obfs-password, and nothing else. Xray's finalmask accepts more than that —
packetSize among them — and those extra settings change what the server expects
on the wire. The emitted URI then looks complete but describes a server the
client cannot reach: every standard client applies plain salamander, the server
drops the packets, and the failure is silent on both ends.

Log the unexpressible keys when building such a link, naming the inbound, so the
cause is visible instead of appearing as a client-side problem.

* fix(sub): deduplicate salamander warnings
2026-08-15 18:15:19 +02:00
Sanaei acbf09e710 fix(frontend): restore responsive table height
Remove viewport-capped vertical scrolling so page size controls the rendered table height and page scrolling remains responsive.
2026-08-15 18:13:10 +02:00
isultanov99 be70535b94 feat(inbounds): improve multi-node online attribution (#6164) 2026-08-15 17:40:35 +02:00
isultanov99 2d669fa4b7 feat(sub): add template variables to subscription metadata (#6163) 2026-08-15 17:38:29 +02:00
Lex Rivera 8c8556ab32 feat(frontend): multi-node cloning initial implementation (#6216)
* feat(frontend): multinode cloning initial implementation

* fix(frontend): harden live node detection in multinode cloning

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix(frontend): add aria label to clone inbound modal

* fix(frontend): shallow copy inbound settings during cloning

* fix(frontend): avoid potential port conflict during testing

* fix(frontend): selection buttons and websocket selection reset fix

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-15 17:36:25 +02:00
Sanaei 03950b1295 fix(frontend): disable table virtualization
Removes the `virtual` table option from Clients, Inbounds, and Nodes list pages. This aligns table behavior across key admin views and avoids virtualization-related rendering/interaction issues with the existing scroll and pagination setup.
2026-08-15 17:33:56 +02:00
Grigoriy d7698ec7aa feat(xray): browse geosite/geoip categories from routing rules (#6165)
* feat(xray): browse geosite/geoip categories from routing rules

Routing rules made you type category names from memory: nothing showed which
categories a database actually contains, what is inside one, or whether a
name resolves at all — a typo only surfaced when Xray refused the config.

The panel now reads Xray's .dat databases itself and exposes them over four
endpoints: databases in the asset folder, a database's categories, one page
of a category's rules, and validation of the tokens already in a rule. The
reader walks the protobuf wire format directly rather than decoding into Go
structs, because a 10 MB geosite.dat holds well over a million domains and
materialising them costs ~284 MB where streaming costs ~19 MB. Only the
category index is cached, entry pages are scanned on demand, and scans are
serialised, so twenty concurrent requests peak at 87 MB instead of 1 GB.
A database's type is decided by its contents, not its file name, since
custom .dat files are named freely.

In the rule form, the source-IP, IP and domain fields gain a database button
opening the browser: search over categories, a preview of what a category
holds, and a multi-select that merges into the field. Plain domains, CIDRs
and categories the panel does not know are left untouched; categories already
present come back ticked, and unticking one removes it from the rule.

* fix(xray): read geo databases through os.Root and match codes verbatim

CodeQL flagged the database read as a path built from a user-supplied value,
and it was right about the shape of it. The file name arrives in a request;
resolve() rejects traversal and stats the file through an os.Root, but the
read itself went through a joined path with os.ReadFile. That left the
symlink defence incomplete: the stat could pass while the read followed a
link planted — or swapped in — afterwards.

Reads now go through the same root, so a request-supplied name never becomes
a path this code resolves on its own, and the size limit is applied to the
opened file rather than to a separate stat of it.

Lookup no longer trims the category code either. It backs the routing-token
validator, and the core matches codes verbatim: "geosite: cn" will not start
Xray, so repairing that space here hid exactly the typo the validator exists
to report.

* fix(xray): address review findings on the geo category browser

Asset folder. The browser read config.GetBinFolderPath() unconditionally,
but the core honours a preset XRAY_LOCATION_ASSET and only falls back to the
bin folder (ensureXrayAssetLocation). On an install pointing at a shared
asset directory the panel listed an empty folder and reported perfectly
valid geosite:/geoip: tokens as missing — the validator warning about a
correct config. The directory is now resolved with the core's precedence.

Paging. Serving one page read and rescanned the whole database, so walking
category-ads-all re-read it per page. The index now records each category's
byte range and a page reads only that record through the os.Root handle,
with the current category's records held for the duration of a paging
session. Profiling that also showed the real cost was not the read but the
slice of payload pointers built per call — a category holds a hundred
thousand of them — so records are now walked with a callback instead.
Ten pages over category-ads-all: 239 MB allocated, now 4.3 MB.

Cached failures. Any error from reading a file was latched under the file's
size+mtime, so a transient ENOMEM or EMFILE marked a healthy database as
damaged until it changed on disk. Only deterministic failures are cached.

Wrong kind. A geoip: token typed into a domain field parsed as a plain
domain and was waved through, though the core cannot resolve it as one. It
is now reported, with its own reason and wording.

Frontend. The category filter fed the query key on every keystroke, so each
character triggered a request that re-scanned the database; it is debounced
now. GeoTokenInput accepts and forwards a ref, so React Hook Form can focus
these three fields on a validation error again. A failed validation shows
that it failed instead of rendering the same empty state as "no issues".

Also drops an unreachable branch in the token-count guard and corrects the
categories endpoint docs, where limit is unbounded by default.

---------

Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
2026-08-15 17:12:59 +02:00
Kobi Hikri 7c8a9a6909 ci: attach provenance and SBOM attestations to the published images (#6130) 2026-08-15 16:59:11 +02:00
Rouzbeh† 694ad6deae feat(sub): add per-client subscription HWID limits (#5802)
* feat(sub): add per-client subscription HWID limits

* fix(sub): address HWID review on shared subId and bulk create

* fix(sub): store HWID devices by sub_id and drop anchor client workaround

* fix(sub): restore UA auto-detect and HTML page routing in subs()

The cherry-pick of the HWID gate onto main's refactored SUBController
had dropped main's UA-based format auto-detection and sub-page handling
from subs(). Restore those branches, slotting enforceHwid after the
HTML page and before format detection so the gate only applies to
machine-readable subscription bodies.

Also adapt tests to main's options-struct constructor and to the
ClientService.Update signature extended with limitHwid.

* fix(frontend): drop axios from HttpUtil.delete

The bulk-delete rework's committed version still referenced axios,
which this file no longer imports, breaking typecheck in CI. Use the
httpRequest wrapper like the other verbs.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-15 16:50:20 +02:00
n0ctal 1793a9b8b4 feat(nodes): opt-in encryption at rest for the outbound node API token (#6186)
* node: encrypt outbound bearer token at rest

* fix(nodes): keep bearer tokens encrypted throughout

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 16:48:50 +02:00
PathGao 8e7fb144ee perf(frontend): replace blank Suspense fallbacks with Spin, switch to matchMedia hook, add virtual table scrolling (#6187)
- routes.tsx, LazyMount.tsx: replace Suspense fallback={null} with Spin
  loader so page transitions and lazy modals never show blank content
- useMediaQuery.ts: switch from resize event to matchMedia change event,
  eliminating state updates on every pixel drag; export MOBILE_BREAKPOINT_PX
- SubPage.tsx: drop duplicate inline isMobile logic (7 lines), use shared
  useMediaQuery(576) (2 lines)
- ClientsPage, InboundList, HostList, NodeList: add virtual + scroll.y to
  Table for viewport-only DOM rendering of large datasets
2026-08-15 16:44:08 +02:00
Dan Liutko 0f14ce7551 fix(web): fallback to default secret when database setting is empty (#6189)
* fix(web): fallback to default secret when database setting is empty

* style(web): format setting_security_test.go with gofumpt
2026-08-15 16:40:22 +02:00
n0ctal 7ecd88b9e3 fix(nodes): apply a rotated master mTLS certificate without restarting the panel (#6194)
* fix(mtls): invalidate pooled clients after credential rotation

* fix(mtls): make connection reload read-only

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 16:03:42 +02:00
n0ctal 1230559e69 feat(api): scoped, optionally expiring API tokens (#6201)
* security(api): add scoped expiring API tokens

* security(api): make scoped token lifecycle enforceable

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 15:31:49 +02:00
n0ctal aecbad3ab1 test(tgbot): detect open-coded keypad transitions (#6214)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-15 15:27:02 +02:00
Maxim Myalin 2217213e9f feat(sub): expose last subscription fetch time (#6217)
* feat(sub): expose last subscription fetch time

Record successful GET subscription fetches per client and surface the timestamp in the client API and UI.

* fix(frontend): include last subscription fetch in client traffic

* Update sub_fetch_test.go

---------

Co-authored-by: Hermes Agent <hermes-agent@localhost>
2026-08-15 15:22:11 +02:00
n0ctal ad32144c42 fix(sub): use a fullwidth percent in USAGE_PERCENTAGE (#6174)
* fix(sub): use a fullwidth percent in USAGE_PERCENTAGE

A remark is placed in the share link fragment, so an ASCII percent is
percent-encoded to %25. Happ treats such a fragment as malformed, discards the
whole remark and falls back to showing the server hostname, which defeats the
point of a remark template and leaks the host into the client's server list.

Emit U+FF05 FULLWIDTH PERCENT SIGN instead. It renders the same to a reader,
never produces %25, and round-trips through url.Parse unchanged.

* test(sub): exercise production fragment encoding

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:13:15 +02:00
n0ctal 34c248bb79 fix(cli): stop -getApiToken accumulating admin tokens (#6175)
* fix(cli): stop -getApiToken accumulating admin tokens

`x-ui setting -getApiToken` reads like a getter, but when tokens already exist
it minted a brand-new one named `cli-fallback-<unix>` on every invocation. The
plaintext is printed once and the row stays enabled forever, so an operator who
runs the command a few times while debugging silently leaves several
admin-equivalent credentials behind that nobody can tell apart or revoke
knowingly.

Keep the convenience the fallback was added for, but rotate a single
`cli-fallback` token instead: RecreateByName drops any existing row with that
name before issuing a new one, so at most one CLI-issued token exists at a time
and the previous plaintext stops working.

* fix(api-token): preserve token on failed replacement

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:12:43 +02:00
n0ctal 17fea2f656 fix(database): keep IP limits when the fail2ban probe is inconclusive (#6176)
* fix(database): keep IP limits when the fail2ban probe is inconclusive

ResetIpLimitNoFail2ban clears limitIp on every client — inbound settings JSON
and the clients table — whenever fail2banCanEnforce() returns false, then
records itself in the seeder history so it never re-evaluates. The probe was a
single `fail2ban-client -h` run, so it answered false both when fail2ban is
genuinely absent and when the command merely failed that once: a panel that
starts before fail2ban is up, or in a container where it is installed a moment
later, permanently loses every configured limit with no log line and no way
back.

Separate the two. A missing binary still means "absent" and the cleanup runs as
before; a binary that exists but will not run is reported as unknown, leaves the
configured values untouched, logs why, and does not record the seeder, so the
next start decides again.

* test(database): cover fail2ban reset safeguards

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:12:07 +02:00
n0ctal c5dec64d36 fix(clients): push bulk client changes to nodes only after the commit lands (#6181)
* fix(clients): apply bulk mutations after durable commit

* test(clients): guard bulk pushes behind commit

* fix(clients): fully delete remote bulk clients

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:11:19 +02:00
n0ctal b56b087254 fix(migration): stop a half-applied startup migration from committing silently (#6182)
* fix(traffic): check maintenance commits and IP-limit errors

* fix(migrations): propagate transactional failures

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:10:39 +02:00
n0ctal 3bb87e80aa fix(db): harden unrestricted freedom outbounds (#6184) 2026-08-14 20:07:30 +02:00
n0ctal 60453bf523 fix(nodes): persist the master mTLS credential atomically and stop silent reissue (#6195)
* fix: harden master mTLS credential persistence

* fix(mtls): validate and serialize credential persistence

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:03:54 +02:00
n0ctal bb29b6afec fix(node): adopt a matching deployed inbound instead of recreating it (#6197)
* fix(node): adopt compatible origin inbounds without mutation

* fix(nodes): preserve ambiguous and adopted aliases

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:01:35 +02:00
n0ctal 3b19091547 fix(sub): render the full remark once per subscription, not once per credential (#6198)
* fix(sub): scope full remarks to subscription identity

* fix(sub): preserve configured remark whitespace

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 20:00:51 +02:00
n0ctal 0496c23a26 fix(groups): report changed bulk moves without restarting xray (#6199) 2026-08-14 19:50:06 +02:00
n0ctal 1396005082 fix(traffic): apply maintenance side effects only after the commit lands (#6200)
* fix(traffic): apply maintenance after durable commit

* fix(traffic): apply all runtime maintenance after commit

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 19:42:09 +02:00
n0ctal b70c5abce8 fix(outbounds): propagate allocation query failures (#6208)
* fix(outbounds): propagate allocation query failures

* test(outbounds): cover update allocation failure

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 19:41:24 +02:00
n0ctal 20b3f84f77 fix(web): report unexpected HTTP serve failures (#6210)
* fix(web): report unexpected HTTP serve failures

* test(web): cover normal close and all HTTP servers

---------

Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-14 19:40:53 +02:00
Sanaei d291e1c5ee Bump Go toolchain and x dependencies
Refresh the Go toolchain from 1.26.5 to 1.26.6 and update the related x/* and protobuf dependency set in go.mod/go.sum. This keeps the project aligned with the current patch releases and ensures the module graph matches the expected transitive versions.
2026-08-14 17:02:17 +02:00
Mr. Nickson ecadfd0e60 fix(clients): stop recomputing the summary badges from the client_stats snapshot (#6169)
* fix(clients): stop recomputing the summary badges from the client_stats snapshot

pickClientsSummary's coverage guard (serverSummary.total >
allClientStats.length) only catches a net shortfall: an orphaned
client_traffics row and a client still missing one can cancel out, or an
orphan surplus alone can pass uncaught, and either way the guard fails to
fall back (#6116).

client_paging.go's q.summary() already derives the same bucket counts with
clients as the driving table (LEFT JOIN client_traffics), so it cannot
miscount either shape regardless of how the row got there, and listQuery
already polls it every 5s — the same cadence client_stats ticks on. The
client-side recompute bought no fresher a number than the server already
provides on its own poll, only a window to get one wrong, so this drops it:
the summary badges now always read serverSummary directly. allClientStats,
computeClientsSummary, pickClientsSummary and sameSummaryInputs are removed
as dead code along with it; the per-row live traffic patch in
applyClientStatsEvent is untouched, since it reads the same snapshot by
email match rather than by count and was never exposed to this class of bug.

* fix(clients): force a refetch on window focus and drop a stale comment

Review feedback on PR #6169:

listQuery combines staleTime: Infinity with refetchInterval: 5000, which
pauses while the tab is hidden. The WS-driven per-row traffic patch in
applyClientStatsEvent has no such visibility gating, so on a background tab
a row's live numbers keep moving while the summary badges above them freeze
at whatever they were before the tab was hidden, and staleTime: Infinity
blocks refetchOnWindowFocus from closing that gap on return. Before this
PR the client-side recompute this branch removed happened to paper over the
same underlying gap; now that it's gone, the gap is directly visible.
refetchOnWindowFocus: 'always' forces exactly one refetch on refocus,
ignoring staleTime, without touching the interval/staleTime pairing that
governs the rest of this query's behavior.

Separately, useInbounds.ts still referenced computeClientsSummary by name
in a comment explaining bucket priority; that function no longer exists
after this PR. Dropped the comment rather than repoint it, per the repo's
no-//-comment convention.
2026-08-14 16:45:31 +02:00
MMX d05e44e401 fix(outbound): import Hysteria2 salamander properly from standard obfs params (#6166)
* fix(outbound): import Hysteria2 salamander from standard obfs params

The outbound share-link importers only reconstructed salamander from the
private fm=<json> finalmask dump. Every standard Hysteria2 link — and this
panel's own generator (internal/sub) since it stopped emitting fm= — carries
the obfuscation as the standard obfs=salamander & obfs-password=<pw> pair,
which the importers ignored. As a result, importing a normal Hysteria2 link
(pasted into the outbound form or pulled from a subscription) silently dropped
the salamander config and produced an outbound that negotiates plain QUIC
against a server expecting obfuscation.

Parse the standard obfs/obfs-password pair in both the Go importer
(internal/util/link, used by subscription + JSON import) and the frontend
form parser (outbound-link-parser.ts), folding it into finalmask.udp. A
salamander mask already supplied via fm= still wins, so 3x-ui→3x-ui links
are unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(outbound): address review — mport hop, password-less fm mask, tests

Follow-up to the automated PR review on #6166:

- Import the Hysteria2 UDP port-hopping range from the standard `mport`
  param (finalmask.quicParams.udpHop.ports) in both importers — the same
  class of gap as salamander: the subscription generator emits `mport`
  standalone and no `fm=`, so port hopping was silently lost on import.
  An `fm=`-supplied udpHop still wins.
- When `fm=` carries a salamander mask without a usable password, fill it
  in from the obfs pair instead of treating the empty mask as authoritative
  (would otherwise enable obfuscation with an empty password).
- Trim the duplicated rationale comments to two lines each.
- Tests: collapse the four per-case Go functions into table-driven
  subtests; cover the obfs_password/obfsPassword aliases, case-insensitive
  obfs value, append-onto-non-salamander-udp, password-less-fm fill, and the
  mport paths; assert the fm-wins masks stay length 1 in both suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-14 16:43:29 +02:00
Kuzz007 9165ab67eb fix(install): preserve custom bin/ files (e.g. hand-added geoip) across updates (#6152)
* fix(install): preserve custom bin/ files (e.g. hand-added geoip) across updates

Every reinstall/update wipes /usr/local/x-ui/ wholesale and re-extracts
the release tarball, which only ships known assets (xray/mtg binaries,
the bundled geoip*/geosite*.dat sets). A user-reported real incident:
a hand-placed custom geoip file referenced from a routing rule via
"ext:<file>:<code>" got silently deleted on update, and Xray refused
to start at all afterward ("failed to open <file>: no such file or
directory"), taking down every inbound until the file was manually
restored from the user's own backup.

install_x-ui now backs up the old bin/ before the wipe and restores,
after extraction, only the files the fresh release doesn't provide --
bundled assets still get the newer per-release copy, nothing custom
silently disappears. Verified in isolation: standard files (geoip.dat,
the xray binary) end up as the fresh release's copy; a custom file
absent from the release survives untouched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: harden the bin/ snapshot-and-restore against the review round on #6152

- Replace the mktemp+cp snapshot with a same-filesystem mv of bin/ aside:
  an unchecked mktemp failure previously made the very next line copy
  bin/'s contents into "/" (empty custom_bin_backup + trailing slash),
  and a silently-ignored cp failure (stderr redirected, exit code never
  checked) could leave a truncated custom geo file that gets "restored"
  as if it were intact. A rename is atomic and needs no extra disk space,
  removing both failure modes at once; if it fails, back off cleanly and
  say so instead of proceeding as if a backup exists.
- Add a trap so an interrupted update (Ctrl-C, signal) between the
  backup and the restore doesn't leave the snapshot (which contains
  bin/config.json and every mtproto client's FakeTLS secret) sitting
  around indefinitely; the two exit-path cleanups this replaces are gone
  since the trap now covers those exits too.
- Move the restore below the arm arch-rename/chmod block instead of
  before it, so xray-linux-arm32/mtg-linux-arm already exist under their
  final names and don't get needlessly restored-then-overwritten and
  misreported as "custom".
- Exclude bin/config.json and bin/mtproto/*.toml from the restore: those
  are the panel's own generated runtime state (internal/xray/process.go,
  internal/mtproto/manager.go), not admin-placed files, and restoring a
  stale one only resurrects dead state or recreates bin/mtproto/ with the
  wrong (more permissive) directory mode.
- Match symlinks in the restore's find, not just plain files -- cp -a
  already preserves them in the snapshot, but the restore loop was
  silently dropping them, which is exactly the failure mode (a geo file
  symlinked in from elsewhere) this PR set out to fix.
- Quote the two new xui_folder expansions.
- Extend the non-interactive smoke test to reinstall over an existing
  install with a sentinel file in bin/, asserting it survives and that
  the bundled geoip.dat is still the release's own copy -- the update
  path this PR touches had no CI coverage at all before this.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 16:41:45 +02:00
n0ctal 0a30a03cb7 refactor(frontend): remove unused response envelope schema (#6204)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:46:00 +02:00
n0ctal 286a93474d refactor(frontend): remove unreachable barrel modules (#6205)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:45:26 +02:00
n0ctal 238e4bb314 refactor(tgbot): share numeric keypad transitions (#6211)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:41:47 +02:00
n0ctal 4a5f6771b3 fix(nodes): report probe heartbeat persistence failures (#6207)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:34:37 +02:00
n0ctal 64f4f0746c fix(warp): surface update-clock persistence failures (#6209)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:31:05 +02:00
n0ctal 79ef85b59f refactor(frontend): remove unused legacy utilities (#6206)
Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
2026-08-13 12:27:40 +02:00
Sanaei 5b80d4562d chore(docs): bump docs dependencies
Update fumadocs-core/mdx/ui to 16.14.3, lucide-react to 1.31.0, @types/node to 26.2.0, typescript-eslint to 8.67.0, esbuild to 0.28.2, shiki to 4.4.3, and various other transitive dependencies.
2026-08-12 19:59:41 +02:00
dependabot[bot] e2f75acad2 chore(deps): bump github.com/klauspost/compress from 1.19.1 to 1.19.2 (#6212)
Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.19.1 to 1.19.2.
- [Release notes](https://github.com/klauspost/compress/releases)
- [Commits](https://github.com/klauspost/compress/compare/v1.19.1...v1.19.2)

---
updated-dependencies:
- dependency-name: github.com/klauspost/compress
  dependency-version: 1.19.2
  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-08-12 16:57:37 +02:00
Chen, Ting-An 69a8237581 fix(i18n): localize Chinese Xray labels (#6202)
* fix(i18n): localize Traditional Chinese Xray labels

Several navigation, outbound, balancer, VPN, and DNS labels still displayed their English source text in the zh-TW interface. Translate the non-protocol labels while retaining established Xray terminology.

* fix(i18n): localize Simplified Chinese Xray labels

Mirror the reviewed Xray UI coverage in zh-CN so the same labels no longer fall back to English there.

Signed-off-by: 陳廷安 <73953029+nrps9909@users.noreply.github.com>

---------

Signed-off-by: 陳廷安 <73953029+nrps9909@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-12 16:56:11 +02:00
Sanaei f3f57e66f5 fix(frontend): wait out Collapse fade before a11y scan in ConfigBlock story
Collapse animates opacity in over motionDurationMid; the Collapsed story's
play function only waited for visibility, so the addon-a11y color-contrast
check could sample a mid-fade, lower-contrast frame and fail flakily in CI.
Wait for the panel's opacity to settle to 1 first.
2026-08-12 16:43:57 +02:00
Sanaei 8a8da88548 fix(frontend): isolate swagger deps from main vendor chunk
Keep swagger-ui-react and its transitive dependencies in the lazy swagger chunk so the initial panel bundle stays smaller. This avoids eager loading the OpenAPI UI on first paint while keeping the API docs route unchanged.
2026-08-12 16:11:47 +02:00
Sanaei 1f846c3cb2 fix(frontend): clean test validation output 2026-08-12 15:35:20 +02:00
Sanaei 1c255fc00c chore(frontend): bump npm dependencies
Refresh frontend package versions and regenerate the lockfile. This updates core UI and tooling packages including Ant Design, React Hook Form, Storybook, Vite, eslint/typescript-eslint, @noble/hashes, persian-calendar-suite, and swagger-ui-react to pick up the latest fixes and minor improvements.
2026-08-12 14:06:18 +02:00
dependabot[bot] 75032fd498 chore(deps): bump dompurify (#6193)
Bumps the npm_and_yarn group with 1 update in the /frontend directory: [dompurify](https://github.com/cure53/DOMPurify).


Updates `dompurify` from 3.4.12 to 3.4.13
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.4.12...3.4.13)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.4.13
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-12 13:40:13 +02:00
Sanaei ece1655939 fix(docs): prevent theme switch hydration mismatch 2026-08-06 20:29:00 +02:00
Sanaei cb902314db fix(docs): restore theme switch without runtime warnings
Move html/body shell and global css to root app layout to avoid hydration/script warnings from nested document nodes. Disable provider theme injection and add a custom script-free theme switch in shared layout slots.

Also migrate docs search static client initializer to ZBSearch (initDB), add zbsearch dependency, and align docs lint tooling with ESLint 9 compatibility so npm run lint passes.
2026-08-06 17:59:23 +02:00
n0ctal 7eacce6a46 chore(frontend): resolve the high-severity brace-expansion advisory (#6180)
npm audit --omit=dev --audit-level=high is a CI gate and it currently fails on
main: swagger-ui-react pulls @swagger-api/apidom-reference, which pins
minimatch, which resolves brace-expansion to 5.0.8 — the range covered by
GHSA-rgw5-rvv9-x895.

Pin the patched 5.0.9 through the existing swagger-ui-react overrides block
rather than globally: minimatch@3 under eslint-plugin-jsx-a11y still needs the
1.x line, and a blanket override would force v5 there too.
2026-08-06 16:29:03 +02:00
dependabot[bot] 199ddaf485 chore(deps-dev): bump brace-expansion (#6172)
Bumps the npm_and_yarn group with 1 update in the /frontend directory: [brace-expansion](https://github.com/juliangruber/brace-expansion).


Updates `brace-expansion` from 1.1.16 to 1.1.18
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.16...v1.1.18)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.18
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-06 16:27:30 +02:00
dependabot[bot] d142307366 chore(deps-dev): bump postcss (#6173)
Bumps the npm_and_yarn group with 1 update in the /docs directory: [postcss](https://github.com/postcss/postcss).


Updates `postcss` from 8.5.21 to 8.5.23
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.5.21...8.5.23)

---
updated-dependencies:
- dependency-name: postcss
  dependency-version: 8.5.23
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-06 16:27:13 +02:00
Sanaei 3883882726 chore: bump frontend and Go dependencies
Updates multiple frontend packages (antd, react-hook-form, storybook, vite, swagger-ui-react, playwright, typescript-eslint, etc.) and Go dependencies (gopsutil, gorm postgres driver, pion/transport, ugorji/codec, genproto, and others). Also replaces `__dirname` with `import.meta.dirname` in vite.config.js for ESM compatibility.
2026-08-04 11:52:45 +02:00
Sanaei 216d18b3c4 chore(vscode): fix Linux paths in the task and launch configs
The "go: build" task hardcoded bin/3x-ui.exe, so building on Linux
produced a binary carrying a Windows extension. It now emits bin/3x-ui
and keeps the .exe name behind a windows override.

The Postgres launch config prepended C:\Program Files\PostgreSQL\18\bin
to PATH on every platform. Linux separates entries with ':', not ';', so
that string fused into the first real PATH entry and clobbered it. Moved
it into a windows block, which is where the pg_dump/pg_restore lookups
in ServerService need it anyway.
2026-08-02 12:40:11 +02:00
Sanaei 2a8c3bc0db fix(clients): stop a stale IP row from blocking a client edit
Saving a client walks every inbound it is attached to and calls
UpdateInboundClient, which re-keys the client's email in inbound_client_ips
to the spelling in the edited settings. The email match is EqualFold, so when
an inbound's settings JSON drifted in case from the client record the panel
issues a case-only rename of the tracking row.

inbound_client_ips.client_email is unique and case-sensitive, and the
IP-limit job keys its rows on whatever casing Xray reports, so both spellings
can already be present. The rename then aborts the whole edit with
"duplicate key value violates unique constraint
uni_inbound_client_ips_client_email" — the client could not be saved at all,
including when only adding an inbound to it.

The caller only renames onto an identity no live client holds, so a row on
the target email is stale IP tracking: delete it before renaming. The blob is
rebuilt by the next scan anyway.
2026-08-02 12:32:45 +02:00
Sanaei e71b75e99e docs(claude): correct enforced-guard claims and add the runtime dispatch rule
Fact-checked every line of CLAUDE.md against the tree. Six claims were wrong,
and two told an agent the opposite of the truth.

The file said nothing checks endpoints.ts against the Go routes and nothing
fails the build on a missing i18n key. Both guards exist and both run in
make verify: TestRouteRegistryContract diffs the real router against the
registry in both directions, and i18n-dead-keys.test.ts rejects a locale that
misses an en-US key as well as an en-US key nothing references. An agent
trusting the old text either skips a step it thinks is unenforced or is
blindsided when a "silent" omission turns the suite red.

The rest: the Go locale returns an empty string for an unknown key, not the raw
key; mtg-multi is a prebuilt binary fetched at build time, not a Go dependency
built from source; commits are type(area): summary, not <area>: summary, and
perf is in active use; make verify is the fast gate, not a mirror of CI, which
also runs race, vulncheck, a live-Postgres job where a SKIP is a failure, and a
fuzz smoke.

Add the five facts most likely to burn an agent, all reproduced before writing
them down. A fresh clone has no internal/web/dist, so go build dies on the embed
pattern while thirty-odd packages pass — it reads as a broken repo rather than a
missing make dist-stub. Every state-changing inbound/client op must dispatch
through runtime.Runtime; a direct xray/api.go call passes all local tests and
silently breaks every multi-node install, which is exactly what a hard rule is
for. Node 24 is required because make gen imports .ts directly. Postgres, xray
e2e and scale tests skip themselves without their env vars. An endpoint change
has a fourth step nothing checks: syncing docs/public/openapi.json.

Definition of done loses its first step — verify's gen-check already runs gen
and fails on a dirty generated diff.
2026-08-01 16:06:55 +02:00
Sanaei 5bc81dfd1d fix(node): stop the node sync from deleting clients it never meant to
A client that hit its quota or expiry was disabled, then destroyed on both
panels a few seconds later. Five defects fed the same hard delete.

ReconcileNode pushed buildRuntimeInboundForAPI, which strips disabled
clients. Every other call site targets an in-memory Xray config, where
dropping a user is harmless; a node target is a peer panel's DATABASE, so
the node deleted the row, stopped reporting it, and the master mirrored that
deletion back. Split the builder in two: buildInboundForNodePush injects
fallbacks only, buildInboundForLocalRuntime adds the strip on top. The names
now say which targets they are safe for.

setRemoteTrafficLocked trusted a config_dirty the caller sampled before the
snapshot round-trip. A client added inside that window commits on the same
serialized writer and marks the node dirty, but the merge still treated the
older snapshot as authoritative and deleted it. Re-read the flag inside the
writer.

In "selected" sync mode, FilterNodeSnapshot strips a deselected tag, but the
sweep loaded every inbound with node_id set, so deselecting a tag read as
"the node deleted it" and wiped an inbound the node still serves. Skip tags
outside the node's managed set.

A failed SyncInbound was logged and swallowed; on SQLite the transaction
still commits, and the sweep then deleted the innocent clients whose links
that failure had left unbuilt. Skip the sweep for such an inbound, and close
the trigger: SyncInbound now stores the trimmed email it looks up by, and
email validation rejects every unicode space rather than only U+0020.

ClientService.Delete tombstones up front and deliberately keeps the record
when an inbound fails, so the next attempt can retry the leftovers. The
tombstone did not lift with it, so the next merge dropped the client from
the synced settings and finished the deletion this path had refused. Add
withdrawClientTombstones on every failure path, in BulkDelete too.

Finally, make the sweep itself recoverable. "Ended the merge unattached" is
true for a real remote deletion and equally true for a bad merge, so it now
stamps sync_orphaned_at instead of deleting; any later merge that sees the
client attached clears the mark, and a reaper removes only what stayed
orphaned past the grace period. The traffic row survives that window too, or
a reclaimed client would come back with its usage, quota and expiry reset.
The mark is written by this sweep alone, so orphans from any other cause
keep their existing manual-cleanup semantics.
2026-08-01 15:19:08 +02:00
Sanaei f4b7b08e08 fix(ldap): stop auto-delete from wiping every client on an empty directory
FetchVlessFlags returns (empty map, nil) whenever the bind succeeds but the
search yields nothing usable — a renamed OU, a service account that lost read
on the user attribute, a filter that stopped matching. The only guard on the
destructive half of the sync was `err != nil`, so that answer was read as
"every user is gone" and the job detached every client from the configured
inbounds, once a minute, for as long as the directory stayed broken.

Gate auto-delete behind autoDeleteSafeForFetch: refuse an empty fetch, and
refuse one that collapsed below half of the last successful sync, which is a
misconfigured directory far more often than real churn.

Also stop splitCsv from defaulting an empty string to DefaultTruthyValues.
That default belongs to the truthy-value setting, but splitCsv is also what
parses ldapInboundTags, so an unconfigured tag list silently resolved to
["true","1","yes","on"]. It only ever bounded the blast radius by accident.
2026-08-01 15:18:50 +02:00
Sanaei 1ff90c5b66 docs(claude): bound comment length, fix size, and test value
Three agent-facing rules, each written after the same mistake showed up in
review.

Comments were banned outright, which the codebase itself contradicts on
almost every file — the ban pushed real invariants out of the code entirely.
Allow them, but cap a block at 2 lines and spend those lines on the *why* a
name cannot carry.

Add a scope rule: the fix must be the smallest change that removes the root
cause. A small bug does not earn new columns, jobs, abstractions or config;
if it genuinely needs architecture, agree on that first instead of shipping
it alongside the fix.

Add two testing rules: a test must go red when its fix is reverted, and it
must cover something that can actually break. A test that passes either way
certifies nothing and is then cited as proof the fix works.
2026-08-01 15:18:35 +02:00
dependabot[bot] 138e1bd840 chore(deps): bump google.golang.org/grpc from 1.82.1 to 1.83.0 (#6162)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.82.1 to 1.83.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.82.1...v1.83.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-version: 1.83.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-31 18:30:43 +02:00
Isuru Sampath 31c1eed5dc fix dead code, typo, and minor bugs in main.go, process.go and index.go (#6167)
Fixes several small issues found during code review:
- fix(xray): return explicit nil instead of stale err in getLogPath
- fix(xray): remove duplicate doc comment on GetErrorLogPath
- refactor: remove unreachable return after log.Fatalf (×4)
- fix(cli): add missing newline to listen IP success message
- fix(cli): typo "form" → "from" in migrate help text
- refactor: simplify var+assign to short declaration for server/subServer
- fix(controller): return error from getTwoFactorEnable instead of swallowing it
2026-07-31 18:27:46 +02:00
PathGao 264f61eb90 Merge pull request #6161 from PathGao/feat-sidebar-pinning
feat(ui): let users pin the sidebar
2026-07-30 23:37:47 +08:00
PathGao ac584cfc90 fix(ui): reserve space for pinned sidebar
Keep page content accessible when the desktop sidebar remains expanded and cover the complete pin lifecycle.
2026-07-30 14:52:38 +08:00
PathGao 91c5d7b19f style(ui): preserve sidebar header spacing
Keep the original title alignment while fitting the pin with the existing header actions.
2026-07-30 14:48:03 +08:00
PathGao b2fe233108 fix(ui): align sidebar pin controls
Keep the pin with the expanded header actions and center the collapsed version link with the navigation rail.
2026-07-30 14:46:43 +08:00
PathGao 5373786faa feat(ui): let users pin the sidebar
Restore a persistent expanded-sidebar choice while preserving the compact hover rail as the default.
2026-07-30 14:39:55 +08:00
834 changed files with 75789 additions and 20740 deletions
+5 -2
View File
@@ -1,7 +1,7 @@
name: Bug report
description: Report something that is broken or behaving unexpectedly
title: "[Bug]: "
labels: ["bug", "needs triage"]
labels: ["bug"]
body:
- type: markdown
@@ -64,7 +64,10 @@ body:
id: screenshots
attributes:
label: Screenshots
description: Drag images directly into this field. Redact any sensitive data.
description: |
Drag images directly into this field. Redact any sensitive data.
Images cannot be searched or machine-read — always paste the exact
error text or log lines as text in the fields above as well.
validations:
required: false
+1 -1
View File
@@ -1,7 +1,7 @@
name: Feature request
description: Suggest an idea or improvement for 3x-ui
title: "[Feature]: "
labels: ["enhancement", "needs triage"]
labels: ["enhancement"]
body:
- type: markdown
+4 -1
View File
@@ -73,7 +73,10 @@ body:
id: screenshots
attributes:
label: Screenshots or config snippets
description: Drag images or paste relevant config. Redact tokens, real domains, client UUIDs.
description: |
Drag images or paste relevant config. Redact tokens, real domains,
client UUIDs. Prefer pasted text over screenshots — images cannot
be searched or machine-read.
validations:
required: false
+181
View File
@@ -0,0 +1,181 @@
# Repository context for the Claude bot
Shared briefing for the jobs in `.github/workflows/claude-bot.yml`. It exists so
these facts live in ONE place next to the code instead of being restated in each
prompt, where they went stale silently. (Pull-request review is separate: its
code-review skill is briefed with `CLAUDE.md` and `REVIEW.md`, not this.)
`CLAUDE.md`, `frontend/CLAUDE.md` and `docs/architecture.md` outrank this file.
Where they disagree with it, they win and this file is the thing to fix.
`docs/architecture.md` carries a "Symptom -> File" index and the cron-job table,
which answer "which file owns X" in one hop; grepping blind wastes turns on a
question it already answers.
## Stack
3x-ui is an open-source web control panel for managing Xray-core servers.
- Backend: Go 1.27, module `github.com/mhsanaei/3x-ui/v3`, Gin and GORM.
- It runs Xray-core as a managed child process (`internal/xray/process.go`) and
imports `github.com/xtls/xray-core` for config types and the gRPC
stats/handler/router API. The release the panel BUNDLES is pinned in
`DockerInit.sh`; the version it COMPILES against is pinned in `go.mod`, and
the two are not always the same.
- MTProto inbounds run a SECOND managed child, the `mtg-multi` binary (a
multi-secret mtg fork, panel-side code in `internal/mtproto/`), one process
per inbound. Client, ad-tag and quota/expiry edits are hot-applied through the
fork's management API (`PUT /secrets`) so connections survive, with a process
restart as the fallback on older binaries.
- Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux, the executable
directory on Windows) or PostgreSQL (`XUI_DB_TYPE` / `XUI_DB_DSN`). The SQLite
driver is CGo, so `CGO_ENABLED=0` builds fail.
- Frontend: React 19 + Ant Design 6 + Vite 8 + TypeScript in `frontend/`, built
into `internal/web/dist/` (gitignored) and embedded with `embed.FS`.
## Where things live
| area | path |
| --- | --- |
| entry point + `x-ui` CLI | `main.go` |
| env parsing | `internal/config/` |
| schema, migrations | `internal/database/`, `internal/database/model/` |
| Xray child process + config | `internal/xray/` |
| MTProto inbounds | `internal/mtproto/` |
| subscription server | `internal/sub/` |
| HTTP handlers | `internal/web/controller/` |
| business logic | `internal/web/service/` |
| cron jobs (schedules in `web.go startTask()`) | `internal/web/job/` |
| master/sub-node over mTLS | `internal/web/runtime/` |
| i18n | `internal/web/locale/`, `internal/web/translation/` |
| UI source | `frontend/src/` |
| install / upgrade | `install.sh`, `x-ui.sh`, `DockerInit.sh` |
## Hard rules a change must respect
- **Dispatch through `runtime.Runtime`.** Every state-changing inbound or client
operation goes through the interface in `internal/web/runtime/`, never
straight to `internal/xray/api.go`. A direct call passes every local test and
silently breaks every multi-node deployment; it is invisible in a single-box
reading of a diff.
- **Layering.** Controllers are thin — bind, validate, respond — with no GORM
queries, no Xray calls and no business rules. `internal/util/*` is leaf-only
and must not import service, controller or database. `internal/web/dist/` and
`frontend/src/generated/` are generated; a hand-edit is a violation.
- **Comments in committed Go/TS/TSX: 2 lines MAX per block**, spent on the *why*
a name cannot hold — an invariant, an issue number, a non-obvious constraint.
Exempt, never flag: `//go:build`, `//go:generate`, `//nolint:`,
`// Code generated ... DO NOT EDIT.`. HTML `<!-- -->` is fine.
- **The route contract chain**, which breaks in four distinct places:
1. a new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry
in `frontend/src/pages/api-docs/endpoints.ts` — pinned BOTH ways by
`TestRouteRegistryContract` in `internal/web/routes_contract_test.go`, so a
renamed or removed route that leaves a stale entry fails too;
2. generated artefacts must be regenerated with `make gen`, or CI's `codegen`
job fails on a dirty `frontend/src/generated` or
`frontend/public/openapi.json`;
3. a NEW struct crossing the API boundary must be added to the `StructAllow`
allowlist in `tools/openapigen/main.go`, or it is SILENTLY dropped from the
schemas and `frontend/scripts/build-openapi.mjs` then fails — a guaranteed
CI break, not a style nit;
4. the step NOTHING checks — `frontend/public/openapi.json` must be copied to
`docs/public/openapi.json` and the MDX regenerated with
`cd docs && pnpm gen:api`, because `docs-ci.yml` fires only on `docs/**`.
Step 4 is the one that reaches production wrong.
- **i18n.** A new English key goes in EVERY locale JSON in
`internal/web/translation/` (13 files) AND must be referenced from
`frontend/src` or Go in the SAME change.
`frontend/src/test/i18n-dead-keys.test.ts` fails on a missing locale file and
on an orphan key alike.
- **Migrations.** Schema changes are GORM `AutoMigrate` PLUS hand-written
migrations in `internal/database/db.go`. There are no migration files and no
down-migrations, and everything has to work on SQLite AND PostgreSQL.
- **Tests.** Stdlib `testing` only (no testify), table-driven with `t.Run`
subtests and `t.Helper()` on helpers. An assertion must pin the exact value,
typed error or emitted string — `err != nil` and `len(x) > 0` are findings,
not nits. Prefer real dependencies: a throwaway DB via
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` with `t.Cleanup`, and
`httptest` for HTTP. `internal/sub`'s `initSubDB(t)` is the template.
A test must FAIL without its fix; one that passes either way certifies
nothing and then gets cited as proof the fix works.
## The three link implementations
Link and subscription generation is implemented three times, independently:
| language | path | what it feeds |
| --- | --- | --- |
| Go | `internal/util/link/`, `internal/sub/` | what the panel serves |
| TS | `frontend/src/lib/xray/` | what the panel UI shows |
| TS | `docs/lib/xray/` | what the docs site shows |
A change to share-link or subscription output that touches one and not the
others is how they drift apart.
## Downstream programs that must accept what the panel emits
- **XTLS/Xray-core** — the Xray config the panel generates, and the VLESS/VMess
transport and security fields.
- **MetaCubeX/mihomo** — consumes the Clash YAML from `internal/sub/`.
- **SagerNet/sing-box** — parses the share links the panel emits.
- **mhsanaei/mtg-multi** — the MTProto sidecar whose TOML (`[secrets]`,
`[secret-ad-tags]`, `[secret-limits]`) and management API
(`PUT /secrets`, `POST /secrets/{name}/reset-quota`) `internal/mtproto/`
writes and calls.
## What CI runs
`.github/workflows/ci.yml`, on every pull request touching Go or frontend code.
It is paths-filtered, so a docs-only or workflow-only change produces no run.
| job | what it proves |
| --- | --- |
| `go-test` | `go test -shuffle=on -count=1` over every package except `frontend/node_modules` |
| `race` | the same set under `-race -shuffle=on` |
| `postgres-durable-first` | live PostgreSQL 16: the `PostgresCommitFailure` tests plus `TestHostAutoMigrateCreatesColumns_Postgres` and `TestMigrate_Postgres`. Both steps COUNT passes rather than assert on SKIP, so a renamed or deleted test fails the job |
| `govulncheck` | known vulnerabilities |
| `golangci` | `golangci-lint` |
| `fuzz-smoke` | 30s each on `FuzzParseLink` and `FuzzDecodeCertPin` |
| `codegen` | `npm run gen` then `git diff --exit-code` on the generated files |
| `frontend` | MSW worker drift, lint, format:check, typecheck, `npm test` (Vitest + headless-Chromium Storybook), build, build-storybook, `npm audit` |
**What CI does NOT prove.** These test families `t.Skip` unless an environment
variable is set, and CI sets only the PostgreSQL ones above:
| gate | covers |
| --- | --- |
| `XUI_TEST_PG_DSN` | PostgreSQL-specific paths |
| `XUI_DB_TYPE` + `XUI_DB_DSN` | dialect-dependent behaviour |
| `XRAY_E2E_BINARY` | the Xray gRPC end-to-end tests in `internal/xray/` |
| `XUI_SCALE_TEST` | scale tests in `internal/sub/`, `internal/web/job/`, `internal/web/service/` |
Mutation testing (`mutation.yml`) runs nightly and never on a pull request, so a
test that cannot fail is invisible to CI. `make verify` is the local gate.
## Support facts reporters get wrong
- Linux install: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
- Install generates a RANDOM username, password and web base path — never
admin/admin. The `x-ui` menu on the server shows or resets them.
- The installer service environment file is DISTRO-DEPENDENT:
`/etc/default/x-ui` (Debian/Ubuntu), `/etc/conf.d/x-ui` (Arch),
`/etc/sysconfig/x-ui` (RHEL/Fedora). Naming the wrong one means the reporter's
edit is silently never read by systemd — a common cause of "I set the variable
and nothing happened".
- Windows is supported. There the database sits next to the executable, not in
`/etc` — never quote the Linux path to a Windows user.
- SQLite to PostgreSQL: `x-ui migrate-db --dsn "postgres://..."`, then set
`XUI_DB_TYPE`/`XUI_DB_DSN` in that file and `systemctl restart x-ui`. The
source SQLite file is left in place.
- Docker image `ghcr.io/mhsanaei/3x-ui`; PostgreSQL profile
`docker compose --profile postgres up -d`. Fail2ban IP-limit enforcement needs
`NET_ADMIN` + `NET_RAW` (compose grants them; a bare `docker run` must add
`--cap-add=NET_ADMIN --cap-add=NET_RAW`).
- Never state that a `XUI_*` variable does not exist without grepping
`internal/config/` and `internal/tunnelmonitor/` first. The
`XUI_TUNNEL_HEALTH_*` family is the usual answer to "the panel restarts Xray
every few minutes".
- Security per inbound is none / tls / reality. XTLS is a VLESS *flow*
(`xtls-rprx-vision`), not a security setting — never tell anyone to pick XTLS
in the security dropdown.
- Never hardcode a version. For "is this already fixed" use
`gh release list -L 10`, `gh search commits`, and `git log -S`.
+31 -3
View File
@@ -8,6 +8,8 @@ on:
- "go.sum"
- "frontend/**"
- ".nvmrc"
- "Makefile"
- ".github/workflows/ci.yml"
push:
branches:
- main
@@ -17,6 +19,8 @@ on:
- "go.sum"
- "frontend/**"
- ".nvmrc"
- "Makefile"
- ".github/workflows/ci.yml"
permissions:
contents: read
@@ -53,6 +57,9 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
XUI_DB_TYPE: postgres
XUI_DB_DSN: "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=xui_durable sslmode=disable"
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
@@ -64,9 +71,24 @@ jobs:
- name: PostgreSQL durable-first tests
run: |
set -o pipefail
XUI_DB_TYPE=postgres XUI_DB_DSN="host=127.0.0.1 port=5432 user=postgres password=postgres dbname=xui_durable sslmode=disable" \
go test ./internal/web/service -run 'PostgresCommitFailure' -count=1 -v | tee /tmp/postgres-durable-first.log
if grep -q -- '--- SKIP' /tmp/postgres-durable-first.log; then
go test ./internal/web/service -run 'PostgresCommitFailure' -count=1 -v | tee /tmp/postgres-durable-first.log
# Count passes rather than assert no SKIP: a renamed or deleted test
# prints "no tests to run" and exits 0, leaving the step green for nothing.
passed=$(grep -c -- '--- PASS' /tmp/postgres-durable-first.log || true)
if [ "$passed" -lt 1 ]; then
echo "expected at least 1 passing durable-first test, got $passed" >&2
exit 1
fi
- name: PostgreSQL schema and migration tests
run: |
set -o pipefail
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log
# Both must pass. Counting, not SKIP-matching: renaming either test would
# otherwise leave this step green while testing nothing.
passed=$(grep -c -- '--- PASS' /tmp/postgres-schema.log || true)
if [ "$passed" -lt 2 ]; then
echo "expected 2 passing PostgreSQL schema tests, got $passed" >&2
exit 1
fi
@@ -162,9 +184,15 @@ jobs:
- name: Install
run: npm ci
working-directory: frontend
- name: Verify generated MSW worker is current
run: git diff --exit-code -- public/mockServiceWorker.js package-lock.json
working-directory: frontend
- name: Lint
run: npm run lint
working-directory: frontend
- name: Format check
run: npm run format:check
working-directory: frontend
- name: Typecheck
run: npm run typecheck
working-directory: frontend
File diff suppressed because it is too large Load Diff
+2
View File
@@ -55,6 +55,8 @@ jobs:
with:
context: .
push: true
provenance: mode=max
sbom: true
platforms: linux/amd64,linux/arm64/v8,linux/arm/v7,linux/arm/v6,linux/386
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+3
View File
@@ -42,6 +42,9 @@ jobs:
- name: Lint
run: pnpm lint
- name: Format check
run: pnpm format:check
- name: Test
run: pnpm test
+3 -2
View File
@@ -109,7 +109,7 @@ jobs:
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA::8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release -v main.go
go build -buildvcs=true -ldflags "$LDFLAGS" -o xui-release -v .
file xui-release
ldd xui-release || echo "Static binary confirmed"
@@ -247,6 +247,7 @@ jobs:
msystem: MINGW64
update: true
install: >-
git
mingw-w64-x86_64-gcc
mingw-w64-x86_64-sqlite3
mingw-w64-x86_64-pkg-config
@@ -270,7 +271,7 @@ jobs:
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA:0:8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release.exe -v main.go
go build -buildvcs=true -ldflags "$LDFLAGS" -o xui-release.exe -v .
- name: Copy and download resources
shell: pwsh
-3
View File
@@ -19,9 +19,6 @@ backup/
bin/
x-ui/
dist/
!internal/web/dist/
internal/web/dist/*
!internal/web/dist/.gitkeep
release/
node_modules/
+1 -1
View File
@@ -32,7 +32,7 @@ linters:
# golang.org/x/tools/go/packages is a generator change, out of scope here.
- linters:
- staticcheck
text: "SA1019: parser.ParseDir"
text: 'SA1019: (go/)?parser\.ParseDir'
# ST1005 (capitalized error strings) conflicts with intentional
# user-facing error copy that tests assert verbatim.
- linters:
+12 -3
View File
@@ -29,10 +29,19 @@
"XUI_LOG_FOLDER": "x-ui",
"XUI_BIN_FOLDER": "x-ui",
"XUI_DB_TYPE": "postgres",
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable",
"PATH": "C:\\Program Files\\PostgreSQL\\18\\bin;${env:PATH}"
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable"
},
"windows": {
"env": {
"XUI_DEBUG": "true",
"XUI_LOG_FOLDER": "x-ui",
"XUI_BIN_FOLDER": "x-ui",
"XUI_DB_TYPE": "postgres",
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable",
"PATH": "C:\\Program Files\\PostgreSQL\\18\\bin;${env:PATH}"
}
},
"console": "integratedTerminal"
},
}
]
}
+9 -1
View File
@@ -8,9 +8,17 @@
"args": [
"build",
"-o",
"bin/3x-ui.exe",
"bin/3x-ui",
"./main.go"
],
"windows": {
"args": [
"build",
"-o",
"bin/3x-ui.exe",
"./main.go"
]
},
"options": {
"cwd": "${workspaceFolder}"
},
+80 -23
View File
@@ -8,12 +8,14 @@ index, layering rules), read `docs/architecture.md` on demand — do not guess
file locations when it can answer in one hop.
## Stack
- Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
- Backend: Go 1.27 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
Runs Xray-core as a managed child process (`internal/xray/process.go`) and
imports `github.com/xtls/xray-core` for config types + gRPC stats/handler/router
API. MTProto inbounds run a second managed child — the `mtg-multi` binary
(`github.com/mhsanaei/mtg-multi`, a multi-secret fork built from source;
`internal/mtproto/`) — outside Xray, one process per inbound serving each
(a multi-secret mtg fork — NOT a Go dependency; its prebuilt release binary is
fetched at image/release build time by `DockerInit.sh` + `release.yml`,
panel-side code in `internal/mtproto/`) — outside Xray, one process per inbound
serving each
client's FakeTLS secret via the fork's `[secrets]` section (plus per-client
ad-tags via `[secret-ad-tags]` and per-client data quota / expiry via
`[secret-limits]`, mapped from the client's `totalGB`/`expiryTime`). Client,
@@ -32,11 +34,21 @@ file locations when it can answer in one hop.
- `main.go` — entry point + `x-ui` CLI (run, migrate, migrate-db, setting, cert).
- `internal/config/` — env parsing (XUI_DEBUG, XUI_LOG_LEVEL, XUI_LOG_FOLDER,
XUI_BIN_FOLDER, XUI_SKIP_HSTS, XUI_PORT, XUI_DB_*).
- `internal/database/` + `internal/database/model/` — GORM schema (Inbound,
Client, Setting, User), inbound Protocol enum, AutoMigrate + hand-written
migrations in `db.go`.
- `internal/database/` + `internal/database/model/` — GORM schema (~24 models;
Inbound, Client, Setting, User are the core), inbound Protocol enum,
AutoMigrate + hand-written migrations in `db.go`.
- `internal/xray/` — Xray child-process lifecycle, config generation, gRPC API.
- `internal/xray/geodata/` — streaming geosite/geoip `.dat` reader (cached
category index + paged entries) and `geosite:`/`geoip:`/`ext:` token parsing.
- `internal/mtproto/` — MTProto inbounds via the bundled `mtg-multi` binary.
- `internal/amneziawg/` — AmneziaWG protocol shape: instance/peer derivation
from an inbound, 3.1 obfuscation param generation + validation, port-forward
spec parsing.
- `internal/amneziawgnet/` — embedded AmneziaWG runtime: amneziawg-go device
over a gVisor userspace netstack, per-inbound reconcile manager, TCP/UDP
relay into a loopback per-peer-auth SOCKS5 Xray inbound, port-forward
listeners, per-peer IPv6 egress aliases.
- `internal/pia/` — PIA WireGuard protocol client (auth, signed server list, `/addKey`).
- `internal/sub/` — subscription server (raw / JSON / Clash).
- `internal/eventbus/` — in-process pub/sub (outbound/node health, xray.crash,
cpu.high, memory.high, login.attempt).
@@ -46,7 +58,8 @@ file locations when it can answer in one hop.
- `controller/` — panel + REST API handlers; OpenAPI at /panel/api/openapi.json.
- `service/` — business logic (InboundService, SettingService, XrayService,
node sync); subpackages tgbot/, email/, outbound/, panel/, integration/.
- `job/` — cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP).
- `job/` 18 cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP,
CPU/memory watchdogs, …); full table in `docs/architecture.md` §5.4.
- `middleware/`, `entity/`, `global/`, `session/` (CSRF), `network/`,
`runtime/` (master/sub-node over mTLS), `websocket/`.
- `locale/` + `translation/` — i18n, 13 embedded locale JSON files.
@@ -55,26 +68,49 @@ file locations when it can answer in one hop.
into `frontend/src/generated/` from Go structs. The OpenAPI doc itself
(`frontend/public/openapi.json`) is assembled from those + `endpoints.ts` by
`frontend/scripts/build-openapi.mjs`.
- `docs/` — separate Next.js/Fumadocs site (pnpm, own CI in `docs-ci.yml`,
outside `make verify`). Holds a THIRD independent implementation of
link/subscription generation in `docs/lib/xray/` — check it whenever
share-link or install-command output changes.
## Hard rules (non-negotiable)
- NO `//` line comments in committed Go/TS. Names carry meaning; rename instead
of annotating. Exempt: `//go:build`, `//go:generate`, and other directives.
- Fix size must match bug size. Find the root cause, then make the SMALLEST
change that removes it — a one-line guard beats a new subsystem. A small bug
does not earn new columns, jobs, abstractions, config knobs or helper layers.
If a fix genuinely needs new architecture, say so and get agreement first;
never ship it unasked next to the fix.
- Comments in committed Go/TS: 2 lines MAX per comment block. Make the name
carry the meaning first and rename rather than annotate; spend the 2 lines on
the *why* a name cannot hold — an invariant, an issue number, a non-obvious
constraint. Exempt: `//go:build`, `//go:generate`, and other directives.
HTML `<!-- -->` is fine. (A linter cannot enforce this — you must.)
- New `g.POST`/`g.GET` in `internal/web/controller/` REQUIRES a matching entry
in `frontend/src/pages/api-docs/endpoints.ts`, then `make gen` (or
`cd frontend && npm run gen`). It is a hand-maintained registry — nothing checks
it against the Go routes, so an omitted route silently vanishes from the docs.
`cd frontend && npm run gen`). Hand-maintained but pinned both ways by
`TestRouteRegistryContract` (`internal/web/routes_contract_test.go`): a missing
OR stale entry fails `make test-go`. Scope: `/panel/api/*` + a few session
routes; sub-server routes are exempt.
- Response examples come from Go struct `example:` tags via `tools/openapigen`
never hand-write them. A new struct must be added to openapigen's `StructAllow`
allowlist (`tools/openapigen/main.go`) or it is silently omitted from
schemas/examples (and `build-openapi.mjs` then fails on the missing schema).
- A new English i18n key must be added to EVERY locale JSON in
`internal/web/translation/` (13 files). Missing keys fall back to en-US (or
render the raw key if absent there too); nothing fails the build, so they are
easy to miss.
- A new or renamed endpoint has a FOURTH step nothing checks: copy
`frontend/public/openapi.json` `docs/public/openapi.json`, then
`cd docs && pnpm gen:api` to refresh the MDX under
`docs/content/docs/en/reference/api/`. `docs-ci.yml` fires only on `docs/**`.
- A new English i18n key goes in EVERY locale JSON in `internal/web/translation/`
(13 files) AND must be referenced from `frontend/src` or Go in the SAME commit —
`frontend/src/test/i18n-dead-keys.test.ts` fails both ways. It is a frontend
test, so run `npm test`, not just `make test-go`. At runtime the frontend falls
back to en-US; Go (`internal/web/locale/`) returns "" for an unknown key.
- DB / model changes require a migration in `internal/database/db.go`.
- Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `docs`,
`style`): `<area>: short imperative summary`, then a body explaining the why.
- Every state-changing inbound/client op dispatches through `runtime.Runtime`
(`internal/web/runtime/`) — never straight to `internal/xray/api.go`, never from
a controller or cron job. A direct call passes every local test and silently
breaks every multi-node deployment. Other layering rules: `docs/architecture.md` §8.
- Conventional commits: `type(area): short imperative summary`, then a body
explaining the why. Types in use: `fix`, `feat`, `chore`, `refactor`, `perf`,
`docs`, `style`.
## Go conventions
- Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests,
@@ -83,13 +119,26 @@ file locations when it can answer in one hop.
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` +
`t.Cleanup(func() { _ = database.CloseDB() })`; `httptest` for HTTP.
`internal/sub`'s `initSubDB(t)` is the template.
- A test must fail without its fix. Write it, revert the fix, watch it go red,
restore. A test that passes either way is worse than no test: it certifies
nothing and then gets cited as proof the fix works.
- Test what can actually break. No test for a getter, a constant, a rename, a
pure map lookup, or inputs the function can never receive. One real test that
drives the bug through the actual code path beats five that restate the code.
- Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`.
- Postgres, xray-gRPC-e2e and scale tests `t.Skip` unless `XUI_TEST_PG_DSN`,
`XUI_DB_TYPE`+`XUI_DB_DSN`, `XRAY_E2E_BINARY` or `XUI_SCALE_TEST` is set — a
green `go test ./...` does not mean those paths ran.
## Frontend conventions (summary; full version in frontend/CLAUDE.md)
- Ant Design 6 only — no Tailwind/shadcn. Targeted tweaks, not rewrites.
- TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in
`src/schemas/` are the source of truth; infer types with `z.infer`, never
hand-write. Do not edit `src/generated/`.
- Node 24 (`.nvmrc`) — `make gen` imports `.ts` directly and needs its type
stripping; Node 22 dies with `ERR_UNKNOWN_FILE_EXTENSION`. `npm test` includes
a headless-Chromium Storybook project, so run
`npx playwright install --with-deps chromium` once or `make verify` fails.
- Editing `frontend/src` does NOT change what users see until the Vite build is
regenerated into `internal/web/dist/`. In `XUI_DEBUG=true`, HTML is served from
the frozen embedded FS but JS/CSS off disk — after `npm run build` you MUST
@@ -99,15 +148,23 @@ file locations when it can answer in one hop.
output changes, never to make a red test green.
## Build, test, verify
Run `make help` for all targets. The full local gate that mirrors CI:
A fresh clone has no `internal/web/dist/`, so a bare `go build ./...` dies with
`pattern all:dist: no matching files found` while ~35 other packages pass — it
reads as a broken repo, not a missing step. Run `make dist-stub` once; every
`make` Go target already depends on it, which is why `make test-go` beats
`go test ./...`. Run `make help` for all targets. The local gate:
make verify
make verify # gen-check + lint + typecheck + test + build + build-storybook
That is the *fast* gate, not all of CI. `ci.yml` also runs `make race`,
`make vulncheck`, a live-Postgres job (where a SKIP counts as a failure) and a
30s fuzz smoke on `FuzzParseLink`/`FuzzDecodeCertPin` — run those locally when
you touch DB/dialect or parser code.
Common targets: `make gen` (regenerate Zod/OpenAPI), `make lint` (Go + frontend),
`make test` (Go `-shuffle=on` + frontend), `make race`, `make build`. See `Makefile`.
## Definition of done (before opening a PR)
1. `make gen` and confirm `git diff` on `frontend/src/generated` +
`frontend/public/openapi.json` is clean.
2. `make verify` passes.
3. Diff is focused; refactors are separate from feature work.
1. `make verify` passes — its `gen-check` already runs `make gen` and fails on a
dirty `frontend/src/generated` / `frontend/public/openapi.json`.
2. Diff is focused; refactors are separate from feature work.
+7 -6
View File
@@ -4,7 +4,7 @@ Thanks for taking the time to contribute to 3x-ui. This guide gets a development
## Prerequisites
- **Go 1.26+** (the version pinned in `go.mod`)
- **Go 1.27+** (the version pinned in `go.mod`)
- **Node.js 24 LTS** (the version pinned in `.nvmrc`) and npm 10+ (for the React frontend)
- **Git**
- **A C compiler** — required by the CGo SQLite driver (`github.com/mattn/go-sqlite3`). Linux and macOS already ship one; for Windows see below.
@@ -184,9 +184,9 @@ Only a genuinely **standalone bundle** (like `login` or `subpage`, reachable wit
- **TypeScript strict mode** — all new code in `.ts` / `.tsx`. Run `npm run typecheck` (`tsc --noEmit`) before pushing. The path alias `@/*` resolves to `src/*`.
- **Ant Design 6** is the only UI kit — no Tailwind, no shadcn. A previous attempt to migrate was rolled back. Small, targeted UX tweaks beat sweeping rewrites; raise broader visual changes for discussion before implementing.
- **Function components + hooks** everywhere. No class components.
- **No `//` line comments** in committed JS/TS/Vue/Go. HTML `<!-- ... -->` is fine for template structure. Names should carry the meaning; rename rather than annotate. Comments are reserved for the *why*, and only when the reason is surprising.
- **Comments in committed Go/TS/TSX: 2 lines MAX per comment block**, spent on the *why* a name cannot hold — an invariant, an issue number, a non-obvious constraint. Names should carry the meaning; rename rather than annotate. Compiler and tool directives (`//go:build`, `//go:generate`, `//nolint:`) are exempt, and HTML `<!-- ... -->` is fine for template structure.
- **Persian and Arabic users are first-class.** When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows. (Full RTL layout is not currently wired through AntD `ConfigProvider direction` — only the Jalali date picker is RTL-aware — so treat RTL as an open area, not a solved one.)
- **Schemas over `any`.** New config shapes go in `src/schemas/`; `@typescript-eslint/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
- **Schemas over `any`.** New config shapes go in `src/schemas/`; oxlint's `typescript/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
- **Document new endpoints.** Every new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry in `src/pages/api-docs/endpoints.ts` — it drives both the in-panel API docs and the generated OpenAPI/Zod (`npm run gen:api` / `gen:zod`).
- **Do not break link generation.** Share-link logic lives in `src/lib/xray/` (`inbound-link.ts`, `outbound-link-parser.ts`, …) and is round-tripped by the golden fixture suite — run `npm run test` after any change to URL generation, defaults, or TLS/Reality handling, and regenerate snapshots (`npx vitest run -u`) only for intentional changes. Two runtime paths consume it: the **inbounds page** and the **clients page** subscription links (`/panel/api/clients/subLinks/:subId` → backend `GetSubs`); exercise both.
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — read the live version there rather than trusting a number quoted here — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
@@ -200,7 +200,8 @@ frontend/
├── login.html — login + 2FA entry
├── subpage.html — public subscription viewer entry
├── tsconfig.json — strict, jsx: "react-jsx", paths "@/*" → "src/*"
├── eslint.config.jsESLint flat config (@eslint/js + typescript-eslint + react-hooks)
├── .oxlintrc.json oxlint config (typescript + react-hooks + jsx-a11y)
├── tools/oxlint/ — input-number-guard.mjs (#6121/#6127 guard as a JS plugin)
├── vite.config.js
├── vitest.config.ts
├── scripts/ — build-openapi.mjs (endpoints.ts → openapi.json)
@@ -279,7 +280,7 @@ CI runs this for you nightly (and on demand) via `.github/workflows/mutation.yml
### CI
`.github/workflows/ci.yml` runs per PR: `go-test` (with `-shuffle -count=1`), a `race` job (`-race -shuffle -count=1`), a `fuzz-smoke` job on the critical parsers, and the frontend `typecheck`/`lint`/`test`/`build`/`build-storybook`. Snapshots are regression guards — regenerate them (`npx vitest run -u`) only for intentional output changes, never to make a red test green.
`.github/workflows/ci.yml` runs per PR: `go-test` (with `-shuffle -count=1`), a `race` job (`-race -shuffle -count=1`), a `fuzz-smoke` job on the critical parsers, and the frontend `typecheck`/`lint`/`format:check`/`test`/`build`/`build-storybook`. Snapshots are regression guards — regenerate them (`npx vitest run -u`) only for intentional output changes, never to make a red test green.
## Sending a pull request
@@ -288,7 +289,7 @@ CI runs this for you nightly (and on demand) via `.github/workflows/mutation.yml
3. Run the relevant checks before pushing:
- `go build ./...`
- `go test ./...` (when Go code changed)
- `cd frontend && npm run typecheck && npm run lint && npm run test && npm run build && npm run build-storybook` (when the frontend changed; CI runs this same set on every PR via `.github/workflows/ci.yml`)
- `cd frontend && npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build && npm run build-storybook` (when the frontend changed; CI runs this same set on every PR via `.github/workflows/ci.yml`)
4. Commit messages follow the existing pattern in `git log` — `<area>: short imperative summary`, then a body explaining the *why*. Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `style`, `docs`) are encouraged.
5. Open the PR against `main` with a brief description of what changed and how to test it.
+1 -1
View File
@@ -12,7 +12,7 @@ RUN npm run build
# ========================================================
# Stage: Builder
# ========================================================
FROM golang:1.26-alpine AS builder
FROM golang:1.27-alpine AS builder
WORKDIR /app
ARG TARGETARCH
+12 -4
View File
@@ -31,16 +31,24 @@ lint-go: dist-stub ## golangci-lint on Go sources
golangci-lint run
.PHONY: lint-fe
lint-fe: ## ESLint on frontend sources
lint-fe: ## oxlint on frontend sources
cd $(FRONTEND) && npm run lint
.PHONY: lint
lint: lint-go lint-fe ## All linters
.PHONY: format-check
format-check: ## oxfmt in check mode on frontend sources
cd $(FRONTEND) && npm run format:check
.PHONY: typecheck
typecheck: ## tsc --noEmit
cd $(FRONTEND) && npm run typecheck
.PHONY: msw-worker-check
msw-worker-check: ## Verify the tracked worker matches the installed MSW runtime
cmp $(FRONTEND)/public/mockServiceWorker.js $(FRONTEND)/node_modules/msw/lib/mockServiceWorker.js
.PHONY: test-go
test-go: dist-stub ## Go tests (shuffle, no cache)
go test -shuffle=on -count=1 $(GO_PKGS)
@@ -72,8 +80,8 @@ build: build-fe ## Build the frontend then the Go binary
build-storybook: ## Build the static Storybook (compile-checks all stories)
cd $(FRONTEND) && npm run build-storybook
# The PR gate. Matches ci.yml: codegen freshness, both linters, typecheck,
# both test suites, a full build, and the Storybook compile-check.
# The PR gate. Matches ci.yml: codegen freshness, both linters, the formatter,
# typecheck, both test suites, a full build, and the Storybook compile-check.
.PHONY: verify
verify: gen-check lint typecheck test build build-storybook ## Full local gate (mirrors CI)
verify: gen-check lint format-check typecheck msw-worker-check test build build-storybook ## Full local gate (mirrors CI)
@echo "verify: OK"
+147
View File
@@ -0,0 +1,147 @@
# Review instructions
3x-ui is a Go (Gin + GORM) web panel that generates configuration, share links
and subscriptions for other programs — Xray-core, mihomo, sing-box, mtg-multi —
and is deployed by operators who upgrade in place. Judge findings by what
breaks for those consumers and operators, not by style.
## Severity
Mark every finding with exactly one of these, at the start of the finding:
| Marker | Severity | Use it for |
| --- | --- | --- |
| 🔴 | Important | A defect this pull request introduces or makes worse, in one of the classes under "What Important means here". Worth fixing before it merges. |
| 🟡 | Nit | Style, naming, refactoring, and an ordinary `CLAUDE.md` violation the change introduces — a source comment block over two lines, a fix larger than the bug it removes, a test `CLAUDE.md` rejects outright. |
| 🟣 | Pre-existing | A real bug you hit while reading that this pull request neither introduced nor made worse. |
Not every `CLAUDE.md` rule is a nit. The three listed below — the dispatch
rule, the migration rule, the endpoint chain — are Important, because each one
passes every local test and breaks a real deployment.
Severity follows what this pull request did, not how alarming the defect looks
on its own. One the change worsens is 🔴 for the regression it added, not for
the whole defect; one it merely brought into view is 🟣.
Checking what this panel emits means reading far more code than the diff
changes, so pre-existing bugs surface on every review. One already on the base
branch stays 🟣 however bad it is: this pull request did not cause it, so it
cannot be a reason to hold this pull request. Say in one clause that it
predates the change. The exception is a live security hole on an exposed
surface — still 🟣, but open the summary with it.
## What Important means here
- Security on the exposed surfaces: `internal/web/controller/`, session and
middleware code, the PUBLIC `internal/sub/` subscription server, and Xray
config generation in `internal/xray/`.
- A state-changing inbound or client operation that bypasses `runtime.Runtime`
(`internal/web/runtime/`) and calls `internal/xray/api.go` directly, or
dispatches from a controller or cron job. It passes every local test and
silently breaks every multi-node deployment.
- A schema or model change without a matching hand-written migration in
`internal/database/db.go`, one that behaves differently on SQLite and
PostgreSQL, or one that loses or overwrites operator data on upgrade or
rollback. There are no migration files and no down-migrations.
- A change to what the panel emits on the wire — Xray config JSON, share
links, subscription/Clash YAML, mtg-multi TOML — that a downstream client
would reject or read differently, or that makes the three independent link
implementations (Go `internal/util/link/` + `internal/sub/`, TS
`frontend/src/lib/xray/`, TS `docs/lib/xray/`) diverge from one another.
- Any edit to `.github/workflows/`: this repository runs workflows with
secrets against a public fork stream. Untrusted expression interpolation
into `run:` blocks, broadened permissions, weakened guards, or a job that
executes pull-request code.
## Always check
- A new `g.POST`/`g.GET` in `internal/web/controller/` needs the whole chain:
an entry in `frontend/src/pages/api-docs/endpoints.ts`, regenerated
artefacts (`make gen`), any new API-boundary struct added to `StructAllow`
in `tools/openapigen/main.go`, and `frontend/public/openapi.json` copied to
`docs/public/openapi.json` with the docs MDX regenerated
(`cd docs && pnpm gen:api`). CI checks the first three; the docs copy is
checked by nothing — a missed copy is Important, not a nit.
- A bug fix carries a test that would fail without the fix. A test that cannot
tell the broken behaviour from the fixed one passes before and after, so it
certifies nothing and is itself the finding — asserting only `err != nil` or
`len(x) > 0`, or going green by regenerating golden fixtures or Vitest
snapshots.
- No second way to do a thing already decided: Go tests are stdlib `testing`
(never testify), the panel is Ant Design (never Tailwind or shadcn). Neither
golangci-lint nor oxlint forbids the import, so it passes CI clean.
## Do not report
- Anything CI already enforces: golangci-lint and gofumpt, oxlint, format
and typecheck, govulncheck, and `npm audit --omit=dev --audit-level=high`.
A dev-dependency advisory is out of scope on purpose: it ships to nobody.
- The contents of generated files (`frontend/src/generated/`,
`frontend/public/openapi.json`, `docs/public/openapi.json`) or lock files.
Those files being STALE after a source change is reportable; their style
is not.
- Missing tests for getters, constants, renames or pure map lookups —
`CLAUDE.md` rejects such tests outright.
- A missing or unreferenced i18n key.
`frontend/src/test/i18n-dead-keys.test.ts` pins the 13 locale files in
`internal/web/translation/` in both directions, so the `frontend` job is
already red. Report the failing check, not the key.
## A higher bar, not silence
Everything named under "What Important means here" gets full scrutiny. Two
areas do not — they earn review, but report there only what you are
near-certain about and that actually breaks something:
- `docs/` — the standalone Fumadocs site, with its own CI and its own
dependency tree. `docs/lib/xray/` is the exception and gets full scrutiny:
it is the third link implementation.
- `internal/web/translation/` — the key set is CI's job and the wording of a
translation is nobody's here.
## Verification bar
- A claim about behaviour needs a `file:line` citation from this repository,
not an inference from a name.
- A claim that a downstream client rejects or requires a wire-format detail —
a config key, JSON tag, URI query parameter, YAML or TOML key, an encoding
or hash choice — must name the upstream symbol that decides it (repository,
file, identifier). If you cannot verify it, keep the finding but say
explicitly that it is unverified instead of asserting it.
- "CI passed" is a claim too, and needs the same evidence: say it only of a
run you actually read. A green one proves less here than it looks — only
`postgres-durable-first` runs against PostgreSQL, `go-test` and `race` are
SQLite, and `XRAY_E2E_BINARY` and `XUI_SCALE_TEST` are set by no job, so
those tests have never run in CI at all. Where a change touches dialect,
migration or Xray gRPC code that no job exercised, say it is unverified
rather than repeating a green tick as proof.
## Cap the volume
🔴 findings are never capped. Report every one.
Report at most five 🟡 nits and at most three 🟣 pre-existing bugs. Past that,
say "plus N similar" in the summary instead of posting them.
A cap decides WHICH ones survive, so choose rather than truncate: the same nit
repeated across files is ONE finding with a count, not five slots; a nit in
code this pull request wrote outranks one in code it only moved; and a nit
nobody would act on does not deserve a slot at all.
After the first review of a pull request, report 🔴 findings only: a one-line
fix must not reach round seven on style.
## What the comment must show
Open with a one-line tally — `2 🔴 / 4 🟡 / 1 🟣` — so the author sees the
shape of the review before the detail. When nothing is 🔴, lead with
`No blocking issues` and put the tally after it.
The posted comment is the only part of a review anyone sees, so a bare "no
issues found" is a receipt, not a review: nothing in it says whether the diff
was read or the run died early. Every comment therefore ends with a short
coverage list — one line per area actually checked, naming what was examined
and what it turned out to be, plus the head SHA and the size of the diff it
covers. Say which claims could not be verified and why, including a check
this environment blocked. Keep that coverage list under ten lines; it is
evidence, not a retelling of the pull request.
+22
View File
@@ -0,0 +1,22 @@
# Security Policy
## Reporting a vulnerability
Do not open a public issue for anything you believe is exploitable — an
authentication bypass, remote code execution, injection, secret or
credential exposure, privilege escalation. A public report gives attackers
a head start against every 3x-ui deployment.
Instead, use GitHub's private vulnerability reporting: open this
repository's **Security** tab and click **Report a vulnerability**. Include
the affected 3x-ui version, reproduction steps, and the impact you see.
You will receive replies in the advisory thread.
There is no bug-bounty program. Fixes ship in the next release, and the
advisory is published after a fixed version is available.
## Supported versions
Only the latest release receives security fixes. Update with the install
script or your package channel and confirm the problem still exists before
reporting.
+198
View File
@@ -0,0 +1,198 @@
package main
// The Claude bot prompts in .github/workflows/claude-bot.yml no longer restate
// repository facts; they read .github/claude/repo-context.md instead. A stale
// claim in that file is invisible until it produces a wrong review, so every
// claim a machine can check is pinned here.
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
const (
botContextPath = ".github/claude/repo-context.md"
reviewPath = "REVIEW.md"
ciWorkflowPath = ".github/workflows/ci.yml"
)
func readRepoFile(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(b)
}
// section returns the text between two markers, so a table is matched only
// inside the heading that owns it.
func section(t *testing.T, doc, from, to string) string {
t.Helper()
i := strings.Index(doc, from)
if i < 0 {
t.Fatalf("%s no longer contains the heading %q", botContextPath, from)
}
rest := doc[i+len(from):]
if before, _, ok := strings.Cut(rest, to); ok {
return before
}
return rest
}
func TestBotContextLocaleFileCount(t *testing.T) {
doc := readRepoFile(t, botContextPath)
m := regexp.MustCompile("`internal/web/translation/` \\((\\d+) files\\)").FindStringSubmatch(doc)
if m == nil {
t.Fatalf("%s no longer states the locale file count as \"`internal/web/translation/` (N files)\"", botContextPath)
}
files, err := filepath.Glob("internal/web/translation/*.json")
if err != nil {
t.Fatalf("glob locales: %v", err)
}
if got := len(files); m[1] != itoa(got) {
t.Errorf("%s claims %s locale files, internal/web/translation/ holds %d; update the claim and every prompt that relies on it", botContextPath, m[1], got)
}
}
func itoa(n int) string {
if n == 0 {
return "0"
}
var b []byte
for n > 0 {
b = append([]byte{byte('0' + n%10)}, b...)
n /= 10
}
return string(b)
}
func TestBotContextNamesRealCIJobs(t *testing.T) {
doc := readRepoFile(t, botContextPath)
ci := readRepoFile(t, ciWorkflowPath)
table := section(t, doc, "## What CI runs", "**What CI does NOT prove.**")
rows := regexp.MustCompile("(?m)^\\| `([a-z0-9-]+)` \\|").FindAllStringSubmatch(table, -1)
if len(rows) < 5 {
t.Fatalf("expected the CI table in %s to list at least 5 jobs, found %d", botContextPath, len(rows))
}
for _, r := range rows {
t.Run(r[1], func(t *testing.T) {
if !strings.Contains(ci, "\n "+r[1]+":\n") {
t.Errorf("%s describes a CI job %q that %s does not define", botContextPath, r[1], ciWorkflowPath)
}
})
}
}
func TestBotContextNamesRealPaths(t *testing.T) {
// REVIEW.md briefs the review job the way repo-context.md briefs the
// issue bot, so both get their paths pinned.
// internal/web/dist and frontend/node_modules are build output: absent from a
// fresh clone, created by `make dist-stub` and `npm ci`.
generated := map[string]bool{
"internal/web/dist/": true,
"frontend/node_modules": true,
"frontend/src/generated/": true,
}
seen := map[string]bool{}
counts := map[string]int{}
for _, src := range []string{botContextPath, reviewPath} {
for _, m := range regexp.MustCompile("`([^`]+)`").FindAllStringSubmatch(readRepoFile(t, src), -1) {
p := m[1]
if !regexp.MustCompile(`^(internal|frontend|docs|tools|\.github)/`).MatchString(p) ||
strings.ContainsAny(p, "*{ ") || generated[p] || seen[p] {
continue
}
seen[p] = true
counts[src]++
t.Run(p, func(t *testing.T) {
if _, err := os.Stat(strings.TrimSuffix(p, "/")); err != nil {
t.Errorf("%s names %q, which does not exist; the bot prompts trust this file", src, p)
}
})
}
}
if counts[botContextPath] < 20 {
t.Errorf("expected the bot context to name at least 20 repository paths, found %d - has the file been gutted?", counts[botContextPath])
}
}
func TestBotContextSkipGatesExist(t *testing.T) {
doc := readRepoFile(t, botContextPath)
table := section(t, doc, "**What CI does NOT prove.**", "Mutation testing")
// [A-Z0-9_] and not [A-Z_]: XRAY_E2E_BINARY carries a digit, and excluding it
// silently dropped that gate from the check instead of failing.
gates := regexp.MustCompile("`((?:XUI|XRAY)_[A-Z0-9_]+)`").FindAllStringSubmatch(table, -1)
if len(gates) < 5 {
t.Fatalf("expected at least 5 skip-gate variables in %s, found %d", botContextPath, len(gates))
}
var sources []string
err := filepath.WalkDir("internal", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && strings.HasSuffix(path, ".go") {
sources = append(sources, path)
}
return nil
})
if err != nil {
t.Fatalf("walk internal: %v", err)
}
for _, g := range gates {
t.Run(g[1], func(t *testing.T) {
for _, f := range sources {
if strings.Contains(readRepoFile(t, f), g[1]) {
return
}
}
t.Errorf("%s lists %s as a test skip gate, but no .go file under internal/ reads it", botContextPath, g[1])
})
}
}
// REVIEW.md tells the reviewer which CI job proves what, and which skip gates
// mean a green run proved nothing. Both go stale silently on a rename.
func TestReviewNamesRealCIJobsAndGates(t *testing.T) {
doc := readRepoFile(t, reviewPath)
ci := readRepoFile(t, ciWorkflowPath)
// Hyphenated only: a single-word job name is indistinguishable from prose.
jobs := regexp.MustCompile("`([a-z0-9]+(?:-[a-z0-9]+)+)`").FindAllStringSubmatch(doc, -1)
if len(jobs) < 2 {
t.Fatalf("expected %s to name at least 2 CI jobs in backticks, found %d", reviewPath, len(jobs))
}
for _, j := range jobs {
t.Run(j[1], func(t *testing.T) {
if !strings.Contains(ci, "\n "+j[1]+":\n") {
t.Errorf("%s names a CI job %q that %s does not define", reviewPath, j[1], ciWorkflowPath)
}
})
}
for _, g := range regexp.MustCompile("`((?:XUI|XRAY)_[A-Z0-9_]+)`").FindAllStringSubmatch(doc, -1) {
t.Run(g[1], func(t *testing.T) {
if strings.Contains(ci, g[1]) {
t.Errorf("%s claims %s is never set in CI, but %s sets it", reviewPath, g[1], ciWorkflowPath)
}
})
}
}
// The i18n rule is the one REVIEW.md states as a number, so it is the one that
// goes wrong silently when a locale is added.
func TestReviewLocaleFileCount(t *testing.T) {
doc := readRepoFile(t, reviewPath)
m := regexp.MustCompile(`(\d+) locale files`).FindStringSubmatch(doc)
if m == nil {
t.Fatalf("%s no longer states the i18n rule as \"N locale files\"", reviewPath)
}
files, err := filepath.Glob("internal/web/translation/*.json")
if err != nil {
t.Fatalf("glob locales: %v", err)
}
if got := len(files); m[1] != itoa(got) {
t.Errorf("%s tells the reviewer to expect %s locale files, internal/web/translation/ holds %d", reviewPath, m[1], got)
}
}
+18
View File
@@ -87,6 +87,24 @@ docker run --rm \
*) echo "FAIL: panel did not serve (status ${code:-none})"; tail -n 30 /tmp/xui.log; exit 1 ;;
esac
echo "--- verifying a second install preserves custom bin/ files ---"
echo "custom-sentinel" > /usr/local/x-ui/bin/geoip_custom.dat
geoip_sum_before=$(sha256sum /usr/local/x-ui/bin/geoip.dat | cut -d" " -f1)
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
cat /root/install.sh | bash -s -- "$XUI_SMOKE_VERSION"
else
cat /root/install.sh | bash
fi
test -f /usr/local/x-ui/bin/geoip_custom.dat \
|| { echo "FAIL: custom bin/ file did not survive a second install"; exit 1; }
[ "$(cat /usr/local/x-ui/bin/geoip_custom.dat)" = "custom-sentinel" ] \
|| { echo "FAIL: custom bin/ file content changed across a second install"; exit 1; }
geoip_sum_after=$(sha256sum /usr/local/x-ui/bin/geoip.dat | cut -d" " -f1)
[ "$geoip_sum_after" = "$geoip_sum_before" ] \
|| { echo "FAIL: bundled geoip.dat changed across a same-version reinstall"; exit 1; }
echo "SMOKE_PASS: user=$XUI_USERNAME port=$XUI_PANEL_PORT path=$XUI_WEB_BASE_PATH"
'
+4
View File
@@ -12,6 +12,10 @@ services:
# with iptables, which needs NET_ADMIN. Without these caps a ban is logged
# and shown in fail2ban status but never actually applied. NET_RAW covers
# ip6tables. If you disable Fail2ban, you can drop cap_add.
#
# AmneziaWG works in this image: it runs embedded in the panel process
# (amneziawg-go over a gVisor userspace netstack), so it needs no kernel
# module and no host tooling. Publish its UDP listen port to use it.
cap_add:
- NET_ADMIN
- NET_RAW
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"ignorePatterns": [
"node_modules",
".next",
".source",
"out",
"pnpm-lock.yaml",
"public/openapi.json",
// Reflowing MDX prose merges headings into paragraphs and collapses lists
// inside JSX components (Steps/Callout). Author MDX by hand.
"content/**/*.mdx",
// Generated API reference pages (fumadocs-openapi output).
"content/docs/**/reference/api"
]
}
+42
View File
@@ -0,0 +1,42 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
".next/**",
".source/**",
"out/**",
"node_modules/**",
"next-env.d.ts",
"content/docs/**/reference/api/**"
],
"plugins": ["typescript", "react", "nextjs", "jsx-a11y", "import"],
"categories": {
"correctness": "error"
},
"env": {
"browser": true,
"node": true,
"es2022": true
},
"rules": {
"no-var": "error",
"prefer-const": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"typescript/no-explicit-any": "error",
"typescript/no-unused-vars": "warn",
"typescript/ban-ts-comment": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-namespace": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-unused-expressions": "warn",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/triple-slash-reference": "error",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"import/no-anonymous-default-export": "warn",
"jsx-a11y/prefer-tag-over-role": "off"
}
}
-10
View File
@@ -1,10 +0,0 @@
node_modules
.next
.source
out
pnpm-lock.yaml
public/openapi.json
# Don't let Prettier reflow MDX prose — it merges headings into paragraphs and
# collapses lists inside JSX components (Steps/Callout). Author MDX by hand.
content/**/*.mdx
content/docs/**/reference/api
-7
View File
@@ -1,7 +0,0 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
+3 -3
View File
@@ -20,12 +20,12 @@ pnpm dev # http://localhost:3000
| `pnpm build` | Production build |
| `pnpm start` | Serve the production build |
| `pnpm typecheck` | Generate MDX/route types and run `tsc --noEmit` |
| `pnpm lint` | ESLint (flat config) |
| `pnpm format` | Format with Prettier |
| `pnpm lint` | oxlint (`.oxlintrc.json`) |
| `pnpm format` | Format with oxfmt (`.oxfmtrc.json`) |
| `pnpm test` | Run unit tests (Vitest) for `lib/xray/*` pure logic |
| `pnpm gen:api` | Generate the API reference from `public/openapi.json` |
Before opening a pull request, please run `pnpm typecheck`, `pnpm lint`, and
Before opening a pull request, please run `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, and
`pnpm test` — these are the same checks that CI runs on every PR.
## License
+16 -16
View File
@@ -63,15 +63,15 @@ ever leaves your browser**:
## Tech stack
| Layer | Technology |
| ---------- | ---------------------------------------------------------- |
| Framework | [Next.js 16](https://nextjs.org) (App Router) · React 19 |
| Docs | [Fumadocs](https://fumadocs.dev) (`-ui` / `-core` / `-mdx`) |
| Styling | [Tailwind CSS v4](https://tailwindcss.com) |
| Search | [Orama](https://orama.com) static index |
| Language | TypeScript (strict) |
| Tests | [Vitest](https://vitest.dev) for the pure `lib/xray` logic |
| Tooling | pnpm · ESLint 9 · Prettier |
| Layer | Technology |
| --------- | ----------------------------------------------------------- |
| Framework | [Next.js 16](https://nextjs.org) (App Router) · React 19 |
| Docs | [Fumadocs](https://fumadocs.dev) (`-ui` / `-core` / `-mdx`) |
| Styling | [Tailwind CSS v4](https://tailwindcss.com) |
| Search | [Orama](https://orama.com) static index |
| Language | TypeScript (strict) |
| Tests | [Vitest](https://vitest.dev) for the pure `lib/xray` logic |
| Tooling | pnpm · oxlint · oxfmt |
## Quick start
@@ -86,13 +86,13 @@ pnpm dev # http://localhost:3000
Useful scripts:
| Script | Description |
| ---------------- | -------------------------------------------- |
| `pnpm dev` | Start the dev server |
| `pnpm build` | Production build (also typechecks) |
| `pnpm typecheck` | Generate MDX/route types and `tsc --noEmit` |
| `pnpm lint` | Run ESLint |
| `pnpm test` | Run unit tests (Vitest) |
| Script | Description |
| ---------------- | ------------------------------------------- |
| `pnpm dev` | Start the dev server |
| `pnpm build` | Production build (also typechecks) |
| `pnpm typecheck` | Generate MDX/route types and `tsc --noEmit` |
| `pnpm lint` | Run oxlint (`.oxlintrc.json`) |
| `pnpm test` | Run unit tests (Vitest) |
See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full list and project conventions.
+4 -16
View File
@@ -1,30 +1,18 @@
import '../global.css';
import { RootProvider } from 'fumadocs-ui/provider/next';
import { Inter, Vazirmatn } from 'next/font/google';
import { i18n, localeDirection } from '@/lib/i18n';
import { i18n } from '@/lib/i18n';
import { provider } from '@/lib/i18n-ui';
import SearchDialog from '@/components/search-dialog';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
// Persian UI font; covers Arabic + Latin glyphs so mixed content renders well.
const vazirmatn = Vazirmatn({ subsets: ['arabic'], display: 'swap' });
export function generateStaticParams() {
return i18n.languages.map((lang) => ({ lang }));
}
export default async function LangLayout({ params, children }: LayoutProps<'/[lang]'>) {
const { lang } = await params;
const dir = localeDirection(lang);
const fontClassName = lang === 'fa' ? vazirmatn.className : inter.className;
return (
<html lang={lang} dir={dir} className={fontClassName} suppressHydrationWarning>
<body className="flex min-h-screen flex-col" suppressHydrationWarning>
<RootProvider i18n={provider(lang)} search={{ SearchDialog }}>
{children}
</RootProvider>
</body>
</html>
<RootProvider i18n={provider(lang)} search={{ SearchDialog }} theme={{ enabled: false }}>
{children}
</RootProvider>
);
}
+2 -7
View File
@@ -5,13 +5,8 @@ import { createFromSource } from 'fumadocs-core/search/server';
export const revalidate = false;
export const dynamic = 'force-static';
// Static search index: works under both SSR/Vercel and static export
// (`output: 'export'`). The client loads this prebuilt index and searches
// in-browser (see the `type: 'static'` search option in app/[lang]/layout.tsx).
// All locales currently hold English (fallback) content, and Orama has no
// Persian tokenizer, so map every locale to the English tokenizer. When real
// translations land, switch ru -> 'russian', zh -> 'mandarin' (with
// @orama/tokenizers), etc. See https://docs.orama.com/open-source/supported-languages
// Every locale still serves English fallback content, so all map to zbsearch's
// English tokenizer (its SUPPORTED_LANGUAGES has no Persian or Chinese anyway).
export const { staticGET: GET } = createFromSource(source, {
localeMap: {
en: 'english',
+30 -5
View File
@@ -1,10 +1,16 @@
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { Inter, Vazirmatn } from 'next/font/google';
import './global.css';
import { appName, appTagline, siteUrl } from '@/lib/shared';
import { i18n, localeDirection } from '@/lib/i18n';
// Global SEO defaults. The real <html>/<body> live in `app/[lang]/layout.tsx`
// so we can set `lang`/`dir` per locale (RTL for fa); this root layout is a
// pass-through that only carries site-wide metadata.
const inter = Inter({ subsets: ['latin'], display: 'swap' });
// Persian UI font; covers Arabic + Latin glyphs so mixed content renders well.
const vazirmatn = Vazirmatn({ subsets: ['arabic'], display: 'swap' });
// Global SEO defaults and document shell. Locale-aware html attributes are
// computed from route params so RTL locales get a correct base direction.
export const metadata: Metadata = {
metadataBase: new URL(siteUrl),
title: {
@@ -26,6 +32,25 @@ export const metadata: Metadata = {
},
};
export default function RootLayout({ children }: { children: ReactNode }) {
return children;
export default async function RootLayout({
children,
params,
}: {
children: ReactNode;
params: Promise<{ lang?: string }>;
}) {
const { lang: rawLang } = await params;
const lang = i18n.languages.includes(rawLang as (typeof i18n.languages)[number])
? (rawLang as (typeof i18n.languages)[number])
: i18n.defaultLanguage;
const dir = localeDirection(lang);
const fontClassName = lang === 'fa' ? vazirmatn.className : inter.className;
return (
<html lang={lang} dir={dir} className={fontClassName} suppressHydrationWarning>
<body className="flex min-h-screen flex-col" suppressHydrationWarning>
{children}
</body>
</html>
);
}
+111 -98
View File
@@ -29,17 +29,17 @@ token), with a process restart as the fallback on older binaries.
Servers and processes, all launched from `main.go`:
| Server / process | Package | Purpose | Default port |
|---|---|---|---|
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
| **mtg-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | per inbound |
| Server / process | Package | Purpose | Default port |
| ---------------- | --------------------------------- | ------------------------------------------------------------------ | ----------------- |
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
| **mtg-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | per inbound |
Two key ideas that explain most of the complexity:
1. **The DB → Xray config pipeline.** Inbounds/clients live in the DB. On every change the
backend regenerates the Xray config and applies it — preferring a *hot diff* (live gRPC
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
@@ -51,7 +51,8 @@ Two key ideas that explain most of the complexity:
## 2. Tech stack
**Backend (Go 1.26):**
**Backend (Go 1.27):**
- 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.
@@ -61,6 +62,7 @@ Two key ideas that explain most of the complexity:
- Misc: gorilla/websocket, gopsutil (system stats), go-qrcode, gotp (2FA TOTP).
**Frontend (`frontend/`):**
- **React 19** + **Ant Design 6** + **Vite 8** + **TypeScript**.
- Data layer: **TanStack Query** (`@tanstack/react-query`) over the native **Fetch API**; **Zod 4** schemas.
- Router: **react-router 8**. Charts: **uPlot** (`frontend/src/components/viz/Sparkline.tsx`). Editor: **CodeMirror 6**.
@@ -95,7 +97,7 @@ Browser (React, fetch)
```
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.
with _behavior_, the bug is almost always in a service file, not a controller.
### 3.2 Subscription request (end-user fetching their config)
@@ -134,6 +136,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ └── 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.
│ ├── pia/ # PIA WireGuard protocol client (auth, signed server list, /addKey)
│ ├── 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):
@@ -147,7 +150,9 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ ├── 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
│ │ ── log_writer.go # Pipe Xray stdout/stderr into the panel logger
│ │ └── geodata/ # Browse geosite/geoip .dat: streaming protowire reader,
│ │ # cached category index, routing-token parsing (token.go)
│ │
│ ├── web/ # The panel server
│ │ ├── web.go # ⭐ Server bootstrap: initRouter (all routes) + startTask (all cron jobs)
@@ -159,7 +164,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── 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)
│ │ │ ├── xray_setting.go # /panel/api/xray (raw Xray config editor, WARP/Nord/PIA, geodata)
│ │ │ ├── api.go # /panel/api gateway (token auth, envelope + CSRF wiring)
│ │ │ ├── index.go # login/logout/csrf/2FA
│ │ │ ├── spa.go # SPA fallback for /panel UI routes
@@ -189,6 +194,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── 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
│ │ │ ├── geodata.go # Geo database browsing + routing-token validation
│ │ │ ├── xray_metrics.go # Xray observability metrics
│ │ │ ├── metric_history.go # Historical system/xray metrics
│ │ │ ├── reality_scan.go # REALITY target scanner
@@ -197,7 +203,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── 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)
│ │ │ ├── integration/ # External providers: warp.go, nord.go, pia.go
│ │ │ ├── outbound/ # Outbound config service
│ │ │ ├── panel/ # Cross-cutting panel services:
│ │ │ │ ├── panel.go # panel-level helpers
@@ -265,7 +271,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ └── 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/)
│ ├── components/ # Reusable UI (clients/ form/ geodata/ 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)
@@ -309,8 +315,8 @@ Restart is debounced via an atomic "need restart" flag (`SetToNeedRestart` /
### 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.
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`,
@@ -326,7 +332,7 @@ code* works whether the target is the local Xray or a remote node.
- **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
**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,
@@ -335,6 +341,7 @@ tracking). Node "dirty" flags drive an **anti-entropy reconciliation** so an off
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`).
@@ -357,28 +364,29 @@ Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.Traffic
All registered in `web.go``startTask()`. Each is a struct with a `Run()` method in `internal/web/job/`:
| Schedule | Job | Purpose / condition |
|---|---|---|
| `@every 1s` | `check_xray_running_job` | Restart Xray if it died (2 consecutive down checks) |
| `@every 30s` | (inline func in `startTask`) | Debounced Xray restart — consumes the "need restart" flag (§5.1) |
| `@every 5s` | `xray_traffic_job` | Pull traffic stats from Xray (5s start delay) |
| `@every 5s` | `node_heartbeat_job` | Probe child nodes (online/offline) |
| `@every 5s` | `node_traffic_sync_job` | Pull + merge node traffic; push reconciliation |
| `@every 10s` | `check_client_ip_job` | Enforce per-client IP limits |
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets |
| `@weekly` | `periodic_traffic_reset_job("weekly")` | Weekly 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 |
| 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 10s` | `amneziawg_job` | Reconcile embedded AmneziaWG interfaces against enabled local inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets |
| `@weekly` | `periodic_traffic_reset_job("weekly")` | Weekly 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.
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
@@ -397,8 +405,9 @@ frontend types (`cd frontend && npm run gen`) instead of editing `src/generated/
### 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`.
- `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/
@@ -435,68 +444,70 @@ Xray restart.
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 |
| 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 |
| 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` |
| **Geo category browser** empty / won't open | `xray/geodata/` (`Store`, `reader.go`), `service/geodata.go` | `controller/xray_setting.go` (`/panel/api/xray/geodata/*`), asset dir = `config.GetBinFolderPath()` |
| **`geosite:`/`geoip:` token** reported unknown in a routing rule | `xray/geodata/token.go`, `service/geodata.go` (`Validate`) | `frontend/src/lib/xray/geoTokens.ts`, `frontend/src/components/geodata/` |
| **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 / PIA** outbound integration | `service/integration/warp.go` / `nord.go` / `pia.go` | `internal/pia/`, `frontend/src/pages/xray/overrides/` |
| **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 |
---
@@ -517,7 +528,7 @@ for AutoMigrate in `internal/database/db.go`.
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*
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.
@@ -531,6 +542,7 @@ The canonical gate is the **Makefile** (mirrors CI): `make verify`. Also: `make
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)
@@ -542,12 +554,13 @@ 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):**
**Frontend (`cd frontend`, Node 24 — see `.nvmrc`):**
```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 lint # oxlint 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)
+6 -10
View File
@@ -1,8 +1,8 @@
'use client';
import { create } from '@orama/orama';
import { create } from 'zbsearch';
import { useDocsSearch } from 'fumadocs-core/search/client';
import { oramaStaticClient } from 'fumadocs-core/search/client/orama-static';
import { staticClient } from 'fumadocs-core/search/client/orama-static';
import {
SearchDialog,
SearchDialogClose,
@@ -21,20 +21,16 @@ interface SharedProps {
onOpenChange: (open: boolean) => void;
}
// The static search index is keyed by locale code (en/fa/ru/zh). Fumadocs'
// default static dialog feeds those codes to Orama as a tokenizer language, but
// Orama only accepts full names ("english") and throws on "en" — which silently
// breaks search entirely. All docs content is English (other locales fall back
// to it), so re-create the dialog — the documented escape hatch for custom Orama
// setups — with an initOrama that always builds an English index.
// Fumadocs' default dialog passes the index's locale code as a tokenizer language,
// and zbsearch throws on anything but a full name — so force "english" everywhere.
export default function SearchDialogClient(props: SharedProps) {
const { locale } = useI18n();
const client = useMemo(
() =>
oramaStaticClient({
staticClient({
from: '/api/search',
locale,
initOrama: () => create({ schema: { _: 'string' }, language: 'english' }),
initDB: () => create({ schema: { _: 'string' }, language: 'english' }),
}),
[locale],
);
+104
View File
@@ -0,0 +1,104 @@
'use client';
import { Moon, Sun } from 'lucide-react';
import { useEffect, useState, useSyncExternalStore } from 'react';
import type { ComponentProps } from 'react';
import { cn } from '@/lib/cn';
type ThemeMode = 'light-dark' | 'light-dark-system';
type ThemePref = 'light' | 'dark' | 'system';
const STORAGE_KEY = 'docs-theme';
// `useSyncExternalStore` supplies the same value for SSR and hydration, then
// switches to the browser value after React has attached to the markup.
const subscribeToHydration = () => () => {};
const getHydrationClientSnapshot = () => true;
const getHydrationServerSnapshot = () => false;
function getStoredTheme(): ThemePref {
if (typeof window === 'undefined') return 'system';
const raw = window.localStorage.getItem(STORAGE_KEY);
return raw === 'light' || raw === 'dark' || raw === 'system' ? raw : 'system';
}
function getResolvedTheme(theme: ThemePref): 'light' | 'dark' {
if (theme !== 'system') return theme;
if (typeof window === 'undefined') return 'light';
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(theme: ThemePref): void {
if (typeof document === 'undefined') return;
const resolved = getResolvedTheme(theme);
const root = document.documentElement;
root.classList.toggle('dark', resolved === 'dark');
root.style.colorScheme = resolved;
}
export function DocsThemeSwitch({
className,
mode = 'light-dark-system',
...props
}: {
className?: string;
mode?: ThemeMode;
} & Omit<ComponentProps<'div'>, 'children'>) {
// Keep the server and first client render identical. Reading localStorage or
// matchMedia here would make a persisted/system preference change the client
// markup before React has finished hydrating it.
const [selectedTheme, setSelectedTheme] = useState<ThemePref>('system');
const hydrated = useSyncExternalStore(
subscribeToHydration,
getHydrationClientSnapshot,
getHydrationServerSnapshot,
);
const theme = hydrated ? getStoredTheme() : selectedTheme;
useEffect(() => {
if (hydrated) applyTheme(theme);
}, [hydrated, theme]);
useEffect(() => {
if (!hydrated) return;
if (theme !== 'system') return;
const media = window.matchMedia('(prefers-color-scheme: dark)');
const update = () => applyTheme('system');
media.addEventListener('change', update);
return () => media.removeEventListener('change', update);
}, [hydrated, theme]);
const resolved = hydrated ? getResolvedTheme(theme) : 'light';
const setTheme = (nextTheme: ThemePref) => {
window.localStorage.setItem(STORAGE_KEY, nextTheme);
applyTheme(nextTheme);
setSelectedTheme(nextTheme);
};
const nextTheme = () => {
if (mode === 'light-dark') return resolved === 'dark' ? 'light' : 'dark';
if (theme === 'light') return 'dark';
if (theme === 'dark') return 'system';
return resolved === 'dark' ? 'light' : 'dark';
};
const label =
mode === 'light-dark-system'
? `Switch theme (current: ${theme})`
: `Switch to ${resolved === 'dark' ? 'light' : 'dark'} mode`;
return (
<div className={cn('inline-flex', className)} {...props}>
<button
type="button"
aria-label={label}
title={label}
onClick={() => setTheme(nextTheme())}
className="inline-flex size-8 items-center justify-center rounded-lg text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
>
{resolved === 'dark' ? <Moon className="size-4" /> : <Sun className="size-4" />}
</button>
</div>
);
}
@@ -1,7 +1,12 @@
'use client';
import { useId, useState } from 'react';
import { buildCurl, buildFetchSnippet, type ApiRequestInput, type HttpMethod } from '@/lib/xray/api-client';
import {
buildCurl,
buildFetchSnippet,
type ApiRequestInput,
type HttpMethod,
} from '@/lib/xray/api-client';
import { ToolFrame } from './tool-frame';
import { TextField, SelectField } from './shared/fields';
import { OutputBlock } from './shared/output-block';
+72 -11
View File
@@ -38,8 +38,24 @@ const DEFAULT_BALANCERS: BalancerRow[] = [
{ tag: 'balancer', selector: 'proxy', strategy: 'leastPing', fallbackTag: '' },
];
const DEFAULT_RULES: RuleRow[] = [
{ domain: 'geosite:category-ads-all', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'block' },
{ domain: '', ip: 'geoip:private', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'direct' },
{
domain: 'geosite:category-ads-all',
ip: '',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: 'block',
},
{
domain: '',
ip: 'geoip:private',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: 'direct',
},
];
function list(s: string): string[] {
@@ -113,7 +129,10 @@ export function RoutingBuilder() {
type="button"
className={addBtn}
onClick={() =>
setBalancers((p) => [...p, { tag: '', selector: '', strategy: 'random', fallbackTag: '' }])
setBalancers((p) => [
...p,
{ tag: '', selector: '', strategy: 'random', fallbackTag: '' },
])
}
>
Add balancer
@@ -163,7 +182,15 @@ export function RoutingBuilder() {
onClick={() =>
setRules((p) => [
...p,
{ domain: '', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: '' },
{
domain: '',
ip: '',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: '',
},
])
}
>
@@ -174,13 +201,47 @@ export function RoutingBuilder() {
{rules.map((r, i) => (
<div key={i} className="rounded-xl border p-3">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<TextField label="Domain (comma)" value={r.domain} onChange={(v) => patchRule(i, { domain: v })} placeholder="geosite:google, example.com" />
<TextField label="IP (comma)" value={r.ip} onChange={(v) => patchRule(i, { ip: v })} placeholder="geoip:cn, 1.1.1.1" />
<TextField label="Port" value={r.port} onChange={(v) => patchRule(i, { port: v })} placeholder="443 or 1000-2000" />
<SelectField label="Network" value={r.network} onChange={(v) => patchRule(i, { network: v })} options={NETWORKS} />
<TextField label="Inbound tag (comma)" value={r.inboundTag} onChange={(v) => patchRule(i, { inboundTag: v })} placeholder="optional" />
<SelectField label="Target kind" value={r.targetKind} onChange={(v) => patchRule(i, { targetKind: v as 'outbound' | 'balancer' })} options={TARGET_KINDS} />
<TextField label="Target tag" value={r.targetTag} onChange={(v) => patchRule(i, { targetTag: v })} />
<TextField
label="Domain (comma)"
value={r.domain}
onChange={(v) => patchRule(i, { domain: v })}
placeholder="geosite:google, example.com"
/>
<TextField
label="IP (comma)"
value={r.ip}
onChange={(v) => patchRule(i, { ip: v })}
placeholder="geoip:cn, 1.1.1.1"
/>
<TextField
label="Port"
value={r.port}
onChange={(v) => patchRule(i, { port: v })}
placeholder="443 or 1000-2000"
/>
<SelectField
label="Network"
value={r.network}
onChange={(v) => patchRule(i, { network: v })}
options={NETWORKS}
/>
<TextField
label="Inbound tag (comma)"
value={r.inboundTag}
onChange={(v) => patchRule(i, { inboundTag: v })}
placeholder="optional"
/>
<SelectField
label="Target kind"
value={r.targetKind}
onChange={(v) => patchRule(i, { targetKind: v as 'outbound' | 'balancer' })}
options={TARGET_KINDS}
/>
<TextField
label="Target tag"
value={r.targetTag}
onChange={(v) => patchRule(i, { targetTag: v })}
/>
</div>
<div className="mt-2 flex justify-end">
<button
+38 -7
View File
@@ -79,7 +79,15 @@ export function SubscriptionBuilder() {
setClients((prev) => prev.map((c, j) => (i === j ? { ...c, ...p } : c)));
}
const urlInput: SubUrlInput = { scheme, host, port: Number(port), subPath, jsonPath, subId, behindProxy };
const urlInput: SubUrlInput = {
scheme,
host,
port: Number(port),
subPath,
jsonPath,
subId,
behindProxy,
};
const urls = buildSubscriptionUrls(urlInput);
const subClients = clients.filter((c) => c.address.trim()).map(toClient);
@@ -159,16 +167,33 @@ export function SubscriptionBuilder() {
onChange={(v) => patch(i, { protocol: v as ClientProtocol })}
options={PROTOCOLS}
/>
<TextField label="Remark" value={c.remark} onChange={(v) => patch(i, { remark: v })} />
<TextField label="Address" value={c.address} onChange={(v) => patch(i, { address: v })} />
<TextField label="Port" value={c.port} onChange={(v) => patch(i, { port: v })} inputMode="numeric" />
<TextField
label="Remark"
value={c.remark}
onChange={(v) => patch(i, { remark: v })}
/>
<TextField
label="Address"
value={c.address}
onChange={(v) => patch(i, { address: v })}
/>
<TextField
label="Port"
value={c.port}
onChange={(v) => patch(i, { port: v })}
inputMode="numeric"
/>
<TextField
label={c.protocol === 'vless' || c.protocol === 'vmess' ? 'UUID (id)' : 'Password'}
value={c.credential}
onChange={(v) => patch(i, { credential: v })}
/>
{c.protocol === 'ss' ? (
<TextField label="Method" value={c.method} onChange={(v) => patch(i, { method: v })} />
<TextField
label="Method"
value={c.method}
onChange={(v) => patch(i, { method: v })}
/>
) : null}
<SelectField
label="Transport"
@@ -200,9 +225,15 @@ export function SubscriptionBuilder() {
</div>
<div className="mt-4 grid grid-cols-1 gap-4">
<OutputBlock label="Subscription links (decoded body)" value={buildShareLinks(subClients).join('\n')} />
<OutputBlock
label="Subscription links (decoded body)"
value={buildShareLinks(subClients).join('\n')}
/>
<OutputBlock label="Base64 body" value={buildBase64Subscription(subClients)} />
<OutputBlock label="JSON subscription (preview)" value={buildJsonSubscription(subClients)} />
<OutputBlock
label="JSON subscription (preview)"
value={buildJsonSubscription(subClients)}
/>
</div>
</ToolFrame>
);
+177
View File
@@ -0,0 +1,177 @@
---
title: AmneziaWG
description: Set up an AmneziaWG inbound in 3x-ui — obfuscation parameters, native IPv6, per-client port-forwarding, and routing client traffic through Xray.
icon: Lock
---
**AmneziaWG** is a WireGuard fork that adds traffic obfuscation (junk packets,
randomized padding, and rewritten protocol magic values) so the tunnel doesn't
look like WireGuard to deep-packet inspection. It's a popular choice where
plain WireGuard is blocked but a WireGuard-shaped tunnel with a different
fingerprint gets through.
<Callout type="info">
AmneziaWG runs **embedded in the panel process** — `amneziawg-go` over a
userspace (gVisor) network stack, not a kernel module. There is no DKMS
build, no Secure Boot conflict, and no host network/kernel access
requirement, so it works the same way inside a container as on bare
metal. Each peer's decapsulated traffic relays into its own loopback Xray
SOCKS5 inbound, so a peer's routing, sniffing, and per-client stats all
come from Xray's own machinery — the same as any other protocol's
inbound, not a separate code path.
</Callout>
## Key settings
### Server / interface
| Field | What it is |
| ------------------------ | ------------------------------------------------------------------------ |
| **Subnet** | The tunnel's IPv4 subnet (e.g. `10.8.1.0/24`); each client gets an address from it. |
| **MTU** | Interface MTU. Leave at the default unless you have a reason to change it. |
| **DNS (primary/secondary)** | Seeded into downloadable client configs; the server's own interface doesn't need one. |
| **External interface** | The host NIC a peer's IPv6 address gets aliased onto when IPv6 is enabled (see below). Leave blank to auto-detect. |
### Obfuscation (AmneziaWG 3.1)
The same values must match on both ends of the tunnel, so the server stores
them once and every client config inherits them. The panel generates a
randomized set for you (with a **regenerate** button) — a static, reused
value defeats the point, since DPI can fingerprint it over time.
| Field | What it is |
| ------------ | ---------------------------------------------------------------------------- |
| **Jc** | Number of junk packets sent before the handshake. |
| **Jmin/Jmax** | Size range (bytes) for those junk packets. `Jmin` must not exceed `Jmax`. |
| **S1/S2** | Padding added to the handshake init/response packets. `S1 + 56` must not equal `S2` — amneziawg-go rejects a value that would make both packets the same size. |
| **S3** | Cookie-reply padding, `0`-`64`. |
| **S4** | Transport (data) packet padding, `0`-`32`. |
| **H1-H4** | Magic header values that replace WireGuard's standard message-type bytes. Each is a single integer or a `low-high` range; `1`-`4` are reserved (real WireGuard message types) and must not be used. |
| **I1-I5** | Optional signature packets — random bytes prepended before the handshake, e.g. `<r 148>`. Generated sets fill `I1` only, matching Amnezia's own generator. |
| **HeaderProtectionKey** | A base64 32-byte key for the 3.0 header-protection mechanism. Must match on every client config; blank disables it. |
| **ContentPaddingAddition** | A single integer or `low-high` byte range of extra padding on content packets. Kept `<= 64` by the generator so a 1420-MTU tunnel doesn't fragment. |
| **RekeyAfterTime / RekeyTimeout / RejectAfterTime / KeepaliveTimeout / MaxHandshakeAttempts** | Handshake-timing randomization: each is a `low-high` range (seconds; attempts for the last one) the peer samples from, so session timing stops being a WireGuard fingerprint. Every `RekeyAfterTime` value must stay below every `RejectAfterTime` value. Blank keeps the WireGuard default. |
| **RandomTrailers** | Appends a random number of bytes to the end of every packet. |
| **DisableCookies** | Never send cookie replies — removes a DPI-visible WireGuard message type, at the cost of WireGuard's handshake-flood mitigation. |
<Callout type="info">
If you enter obfuscation values by hand instead of using the generated
defaults, keep `H1`-`H4` **non-overlapping** and above `4`, and double-check
`S1 + 56 != S2` — a bad value here keeps the embedded interface from
coming up at all.
</Callout>
<Callout type="warn">
The 3.1 parameters need a **3.1-capable client**. Clients must run a
3.1-capable Amnezia app; blanking the 3.1 fields renders a config older
clients still understand. There is no host-side version requirement —
the panel ships its own pinned `amneziawg-go`, not whatever happens to be
installed on the system.
</Callout>
## Set it up in the panel
<Steps>
<Step>
### Add an inbound
Add a new inbound, choose protocol **AmneziaWG**, and set the port and tunnel
subnet.
</Step>
<Step>
### Leave obfuscation on defaults (or regenerate)
The panel fills in a randomized, kernel-valid obfuscation set automatically.
Use **Regenerate** if you want a fresh one; there's no need to hand-edit these
unless you have a specific reason to.
</Step>
<Step>
### Add a client
Each client gets its own keypair and tunnel address. Download the client's
`.conf` or copy its share link (`vpn://…`, importable by the official
AmneziaWG/AmneziaVPN apps) from the client list.
</Step>
<Step>
### Optional: enable IPv6
Turning on IPv6 allocates an IPv6 address alongside each client's IPv4 one
from the configured IPv6 subnet. The panel aliases that address onto the
external interface's host NIC so outbound connections carry the peer's own
distinct public IPv6 identity — no NAT66 needed.
</Step>
<Step>
### Optional: forward ports to a client
Set a client's forwarded ports (e.g. `80, 443, 8000-8100`) to open a real
listener on the host that relays that traffic straight to the client's
tunnel address — useful for a client that needs to expose a service through
the server.
</Step>
</Steps>
Every AmneziaWG inbound's traffic already goes through Xray — each peer
relays into its own loopback SOCKS5 inbound, tagged with the AmneziaWG
inbound's own tag, so it shows up as a normal source on the
[Routing](/docs/operations/outbounds-routing) page like any other protocol's
inbound. There is no separate toggle for this: unlike a kernel tunnel,
there's no other way for a peer's traffic to reach the internet once it's
decapsulated.
## What the configuration looks like
A client's downloadable `.conf` (also what the `vpn://` share link encodes,
base64url'd) looks like this:
```ini title="client .conf"
[Interface]
PrivateKey = <client private key>
Address = 10.8.1.2/32
DNS = 8.8.8.8, 8.8.4.4
Jc = 4
Jmin = 65
Jmax = 220
S1 = 87
S2 = 44
S3 = 21
S4 = 9
H1 = 462980921-463150218
H2 = 1177681572-1177787900
H3 = 1907413509-1907903969
H4 = 2029908558-2030313135
I1 = <r 148>
HeaderProtectionKey = 8Iu83eHDA3fMKKSGaEsVW9Ycd2lYYzc0MYlk1jJTvE4=
ContentPaddingAddition = 17-49
RekeyAfterTime = 111-139
RekeyTimeout = 4-7
RejectAfterTime = 187-251
KeepaliveTimeout = 9-14
MaxHandshakeAttempts = 19-36
RandomTrailers = on
DisableCookies = on
# my-client
[Peer]
PublicKey = <server public key>
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = your-server:443
PersistentKeepalive = 25
```
## Not yet covered
<Callout type="info">
- **Multi-node (sub-nodes)** and **Telegram bot** — AmneziaWG inbounds haven't
been exercised through those paths yet. They likely work (the reconciler
runs the same way regardless of how the panel itself is deployed), but
that's not the same as a confirmed, tested claim — treat it as unverified
rather than assume it either way until someone reports back.
</Callout>
+1
View File
@@ -58,6 +58,7 @@ The inbound editor accepts these protocols:
| **Trojan** | TLS-based; supports XTLS and fallbacks. |
| **Shadowsocks** | Includes Shadowsocks-2022 (`2022-blake3-*`) ciphers. |
| **WireGuard** | Modern tunnel. |
| **AmneziaWG** | Obfuscated WireGuard fork, embedded in the panel process. See [AmneziaWG](/docs/config/amneziawg). |
| **Hysteria2** | Selected as `hysteria`; the panel emits `hysteria2://` links. |
| **HTTP** | HTTP proxy. |
| **Mixed (SOCKS/HTTP)** | A combined SOCKS + HTTP listener. |
+1
View File
@@ -6,6 +6,7 @@
"ssl-certificates",
"inbounds",
"reality",
"amneziawg",
"transports",
"clients",
"subscription",
@@ -1,13 +1,13 @@
---
title: Outbounds & Routing
description: Shape egress in 3x-ui — WARP and NordVPN outbounds, outbound subscriptions (server pools), routing rules, and load balancers.
description: Shape egress in 3x-ui — WARP, NordVPN, PIA WireGuard, outbound subscriptions, routing rules, and load balancers.
icon: Route
---
Inbounds accept clients; **outbounds** decide where their traffic goes next.
3x-ui can route traffic through Cloudflare WARP, NordVPN, or arbitrary outbound
pools imported from a subscription, and select between them with routing rules
and balancers.
3x-ui can route traffic through Cloudflare WARP, NordVPN, Private Internet Access
(WireGuard), or arbitrary outbound pools imported from a subscription,
and select between them with routing rules and balancers.
## Editing outbounds & routing
@@ -86,6 +86,23 @@ with a routing rule.
accept a private key directly) and list countries/servers, so you can build a
NordVPN outbound.
## PIA WireGuard
3x-ui can sign in with a PIA username and password, list countries/regions/servers
from the signed PIA server list, and build a WireGuard outbound. Open
**Xray → Outbounds → More → PIA**, sign in, pick a server, and add the outbound.
You can add several servers (one outbound per hostname). The tag is
`pia-<region>-<server>` (for example `pia-us-east-useast1`). Adding or using
**Reset** on a row registers a WireGuard key with PIA `/addKey` for that server.
The same hostname cannot be added twice. Logout clears the stored token only;
delete unused PIA outbounds from the Outbounds list. Reset and delete do not
revoke the WireGuard peer on the PIA account.
The password is not stored. The PIA API token is stored with the same
`NODE_TOKEN_ENCRYPTION` setting as node API tokens. If you retire an old
`XUI_NODE_TOKEN_KEY` without signing into PIA again, Add/Reset fail until you
re-login. Peer `allowedIPs` is IPv4-only (`0.0.0.0/0`).
## Outbound subscriptions (server pools)
An **outbound subscription** imports a remote share-link subscription and injects
@@ -1,66 +1,43 @@
---
title: API Tokens
description: >-
Manage Bearer tokens used for programmatic auth (bots, central panels acting
on this node, CI). Each token has a unique name and an enabled flag — disable
to revoke without deleting, delete to revoke permanently. Tokens are stored as
SHA-256 hashes and the plaintext is returned only once, in the create response
— it cannot be retrieved afterwards, so copy it then. Send one as
<code>Authorization: Bearer &lt;token&gt;</code> on any /panel/api/* request —
the token is a full-admin credential.
description: Manage scoped Bearer tokens for programmatic auth. Tokens grant
admin, monitor, or node-sync access, may expire, and are stored as SHA-256
hashes. The plaintext is returned only once at creation.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every API token, enabled or not. The token value is never returned
only metadata.
url: >-
#list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
title: List every API token, enabled or not. The token value is never returned —
only metadata.
url: '#list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata'
- depth: 2
title: >-
Mint a new API token. Name must be unique and 1-64 characters; the token
string is server-generated and returned only in this response — it is
stored hashed and cannot be retrieved later.
url: >-
#mint-a-new-api-token-name-must-be-unique-and-1-64-characters-the-token-string-is-server-generated-and-returned-only-in-this-response--it-is-stored-hashed-and-cannot-be-retrieved-later
title: Mint a scoped API token. The server-generated plaintext is returned only
once and stored as a hash.
url: '#mint-a-scoped-api-token-the-server-generated-plaintext-is-returned-only-once-and-stored-as-a-hash'
- depth: 2
title: >-
Permanently delete a token. Any caller using it stops authenticating
title: Permanently delete a token. Any caller using it stops authenticating
immediately.
url: >-
#permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
url: '#permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately'
- depth: 2
title: >-
Toggle a token enabled/disabled without deleting it. Disabled tokens are
title: Toggle a token enabled/disabled without deleting it. Disabled tokens are
rejected by checkAPIAuth on the next request.
url: >-
#toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
url: '#toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request'
structuredData:
headings:
- content: >-
List every API token, enabled or not. The token value is never
returnedonly metadata.
id: >-
list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
- content: >-
Mint a new API token. Name must be unique and 1-64 characters; the
token string is server-generated and returned only in this response —
it is stored hashed and cannot be retrieved later.
id: >-
mint-a-new-api-token-name-must-be-unique-and-1-64-characters-the-token-string-is-server-generated-and-returned-only-in-this-response--it-is-stored-hashed-and-cannot-be-retrieved-later
- content: >-
Permanently delete a token. Any caller using it stops authenticating
- content: List every API token, enabled or not. The token value is never returned
— only metadata.
id: list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
- content: Mint a scoped API token. The server-generated plaintext is returned
only once and stored as a hash.
id: mint-a-scoped-api-token-the-server-generated-plaintext-is-returned-only-once-and-stored-as-a-hash
- content: Permanently delete a token. Any caller using it stops authenticating
immediately.
id: >-
permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
- content: >-
Toggle a token enabled/disabled without deleting it. Disabled tokens
id: permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
- content: Toggle a token enabled/disabled without deleting it. Disabled tokens
are rejected by checkAPIAuth on the next request.
id: >-
toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
id: toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
contents: []
---
@@ -1,8 +1,7 @@
---
title: Authentication
description: >-
Two authentication modes are supported. UI sessions use a cookie set by the
login endpoint. Programmatic clients (bots, scripts, remote panels)
description: Two authentication modes are supported. UI sessions use a cookie
set by the login endpoint. Programmatic clients (bots, scripts, remote panels)
authenticate with a Bearer token taken from Settings → Security → API Token.
Both work for every endpoint under /panel/api/*.
full: true
@@ -11,51 +10,38 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Authenticate with username + password and receive a session cookie.
title: Authenticate with username + password and receive a session cookie.
Required before any cookie-based API call.
url: >-
#authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
url: '#authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call'
- depth: 2
title: Clear the session cookie. Requires the CSRF header for browser sessions.
url: '#clear-the-session-cookie-requires-the-csrf-header-for-browser-sessions'
- depth: 2
title: >-
Mint a CSRF token for the current session. The SPA replays it in the
title: Mint a CSRF token for the current session. The SPA replays it in the
X-CSRF-Token header on unsafe requests. Bearer-token callers can skip
this — the middleware short-circuits CSRF for authenticated API
requests.
url: >-
#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
url: '#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests'
- depth: 2
title: >-
Returns whether 2FA is enabled on the panel — used by the login page to
title: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field.
url: >-
#returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
url: '#returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field'
structuredData:
headings:
- content: >-
Authenticate with username + password and receive a session cookie.
- content: Authenticate with username + password and receive a session cookie.
Required before any cookie-based API call.
id: >-
authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
- content: >-
Clear the session cookie. Requires the CSRF header for browser
id: authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
- content: Clear the session cookie. Requires the CSRF header for browser
sessions.
id: clear-the-session-cookie-requires-the-csrf-header-for-browser-sessions
- content: >-
Mint a CSRF token for the current session. The SPA replays it in the
- content: Mint a CSRF token for the current session. The SPA replays it in the
X-CSRF-Token header on unsafe requests. Bearer-token callers can skip
this — the middleware short-circuits CSRF for authenticated API
requests.
id: >-
mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
- content: >-
Returns whether 2FA is enabled on the panelused by the login page
to decide whether to show the OTP field.
id: >-
returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
id: mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
- content: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field.
id: returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
contents: []
---
@@ -7,18 +7,14 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Send a fresh DB backup to every Telegram chat configured as an admin
title: Send a fresh DB backup to every Telegram chat configured as an admin
recipient. No body, no params.
url: >-
#send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
url: '#send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params'
structuredData:
headings:
- content: >-
Send a fresh DB backup to every Telegram chat configured as an admin
- content: Send a fresh DB backup to every Telegram chat configured as an admin
recipient. No body, no params.
id: >-
send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
id: send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
contents: []
---
+308 -360
View File
@@ -1,195 +1,159 @@
---
title: Clients
description: >-
Manage clients as first-class entities that can be attached to one or more
inbounds. A single client row drives the settings.clients entry in every
inbound it belongs to. Endpoints live under /panel/api/clients.
description: Manage clients as first-class entities that can be attached to one
or more inbounds. A single client row drives the settings.clients entry in
every inbound it belongs to. Endpoints live under /panel/api/clients.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every client with its attached inbound IDs and traffic record. The
title: List every client with its attached inbound IDs and traffic record. The
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
url: >-
#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
url: '#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write'
- depth: 2
title: >-
Filter, sort, and paginate clients on the server. Each item is a slim
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
response also includes a summary computed across the full DB row set so
dashboard counters stay stable as the user paginates or filters. Page
size capped at 200; fetch /get/:email to obtain the full per-client
payload for an edit/info modal.
url: >-
#filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal
dashboard counters stay stable as the user paginates or filters: the
*Count fields are exact, while the email arrays beside them stop at 200
entries so the payload does not grow with the panel. Page size capped at
200; fetch /get/:email to obtain the full per-client payload for an
edit/info modal.'
url: '#filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-the-count-fields-are-exact-while-the-email-arrays-beside-them-stop-at-200-entries-so-the-payload-does-not-grow-with-the-panel-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal'
- depth: 2
title: >-
Fetch one client by email, including the inbound IDs and external config
title: Fetch one client by email, including the inbound IDs and external config
IDs it is attached to.
url: >-
#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to'
- depth: 2
title: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess, password
for Trojan/Shadowsocks, auth for Hysteria) are generated server-side
when omitted, so callers can send only the universal fields.
url: >-
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
title: Fetch clients by Telegram user ID. Returns an array since multiple
clients can share the same Telegram ID.
url: '#fetch-clients-by-telegram-user-id-returns-an-array-since-multiple-clients-can-share-the-same-telegram-id'
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
title: Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets are generated server-side when
omitted, so callers can send only the universal fields.
url: '#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields'
- depth: 2
title: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields
you want to keep (the server replaces the row, it does not patch).
url: >-
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch'
- depth: 2
title: >-
Delete a client by email. Removes it from every attached inbound and
title: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
url: >-
#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed'
- depth: 2
title: >-
Attach an existing client to one or more additional inbounds. Body is
title: Attach an existing client to one or more additional inbounds. Body is
JSON.
url: >-
#attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
url: '#attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json'
- depth: 2
title: Detach a client from one or more inbounds without deleting the client.
url: '#detach-a-client-from-one-or-more-inbounds-without-deleting-the-client'
- depth: 2
title: >-
Replace a client's external links (per-client share links and remote
subscription URLs surfaced in their subscription). Sends the full set;
the server replaces all rows.
url: >-
#replace-a-clients-external-links-per-client-share-links-and-remote-subscription-urls-surfaced-in-their-subscription-sends-the-full-set-the-server-replaces-all-rows
title: Replace a client's external links and external subscriptions. Sends the
full set; the server replaces all rows. Disabled rows stay saved for
editing but are not emitted in generated subscriptions.
url: '#replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions'
- depth: 2
title: >-
Reset the up/down counters for every client globally. Quotas and expiry
title: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
moved.
url: >-
#reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
url: '#reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved'
- depth: 2
title: >-
Delete every client whose traffic quota is exhausted (used >= total,
when reset is disabled) or whose expiry has passed. Returns the deleted
count and triggers an Xray restart when any client was on a running
inbound.
url: >-
#delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
title: Delete every client whose traffic quota is exhausted (used >= total, when
reset is disabled) or whose expiry has passed. Returns the deleted count
and triggers an Xray restart when any client was on a running inbound.
url: '#delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound'
- depth: 2
title: >-
Delete every client that is not attached to any inbound, along with its
traffic record, IP log, and external links. Useful for clearing clients
left unattached after their inbounds were removed. Returns the deleted
count. Cannot be undone.
url: >-
#delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
title: Delete every client that is not attached to any inbound, along with its
traffic record, IP log, HWID devices, and external links. Useful for
clearing clients left unattached after their inbounds were removed.
Returns the deleted count. Cannot be undone.
url: '#delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone'
- depth: 2
title: >-
Return every client as a {client, inboundIds} array — the same shape
title: Return every client as a {client, inboundIds} array — the same shape
/bulkCreate and /import accept — so the payload round-trips straight
back through /import. Clients with no inbound attachment are included
with an empty inboundIds list. The UI shows this in a CodeMirror viewer
(copy / download); programmatic callers get the array in obj.
url: >-
#return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
url: '#return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj'
- depth: 2
title: >-
Import clients from a JSON body { "data": "<json>" }, where data is a
title: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]). Items
with inboundIds are created and attached to those inbounds; items with
an empty inboundIds list are restored as unattached client records.
Existing emails are never overwritten — they are returned in skipped.
Triggers a single Xray restart at the end if any target inbound was
running.
url: >-
#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
running.'
url: '#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running'
- depth: 2
title: >-
Shift expiry and/or traffic quota for many clients in one call.
title: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry
(expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the
corresponding field — bulk extend never converts unlimited to limited.
The optional flow directive sets the XTLS flow on every client: "none"
clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the
inbound supports it (omit or "" to leave it unchanged). Returns the
adjusted count and per-email skip reasons.
url: >-
#shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
corresponding field — bulk extend never converts unlimited to limited. A
client that was auto-disabled solely because it was depleted (expired or
over quota) is automatically re-enabled — locally and on its node — when
the adjustment lifts it out of depletion; a manually-disabled or
still-depleted client is left disabled. The optional flow directive sets
the XTLS flow on every client: "none" clears it,
"xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound
supports it (omit or "" to leave it unchanged). Returns the adjusted
count and per-email skip reasons.'
url: '#shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons'
- depth: 2
title: >-
Enable many clients in one call. Emails are grouped by inbound and
title: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to add each user. Note that enabling a
client whose quota is exhausted or whose expiry has passed only flips
the flag — the traffic loop will disable it again on the next tick.
Returns the changed count and per-email skip reasons.
url: >-
#enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
url: '#enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons'
- depth: 2
title: >-
Disable many clients in one call. Emails are grouped by inbound and
title: Disable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to remove each user. Returns the
changed count and per-email skip reasons.
url: >-
#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
url: '#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons'
- depth: 2
title: >-
Delete many clients in one call. The server processes the list
title: Delete many clients in one call. The server processes the list
sequentially so each delete sees the committed state of the previous one
— avoids the race the per-email fan-out had on the panel side. Pass
keepTraffic=true to retain the xray_client_traffic rows after deletion.
url: >-
#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
url: '#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion'
- depth: 2
title: >-
Create many clients in one call. Body is a JSON array of {client,
title: Create many clients in one call. Body is a JSON array of {client,
inboundIds} payloads — the same shape /add accepts. Items are processed
sequentially; per-email skip reasons are returned for items that fail
(e.g., duplicate email). Triggers a single Xray restart at the end if
any inbound was running.
url: >-
#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
url: '#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running'
- depth: 2
title: >-
Add many clients to a group in one call. Updates clients.group_name and
title: Add many clients to a group in one call. Updates clients.group_name and
patches the matching client entry inside every owning inbound's settings
JSON in a single transaction. If the group name does not yet exist (in
client_groups or as a derived label), it is auto-created as a persistent
group. To clear the group label, use /groups/bulkRemove instead.
url: >-
#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
url: '#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead'
- depth: 2
title: >-
Clear the group label on many clients in one call. Inverse of
title: Clear the group label on many clients in one call. Inverse of
/groups/bulkAdd. Clients themselves are kept — only the group label is
cleared from clients.group_name and from each owning inbound's settings
JSON. Groups become empty if all their members are removed.
url: >-
#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
url: '#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed'
- depth: 2
title: >-
Attach many existing clients to many inbounds in one call. Each client
title: Attach many existing clients to many inbounds in one call. Each client
keeps its identity (email/UUID/password/subId) and a shared traffic row;
all clients are added to a target inbound in a single AddInboundClient
call. Clients already present on a target are reported under skipped.
Returns per-email attached/skipped/errors lists and triggers a single
Xray restart if any target inbound was running.
url: >-
#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: >-
Mirror of bulkAttach: detach many existing clients from many inbounds in
title: "Mirror of bulkAttach: detach many existing clients from many inbounds in
one call. For each email, intersects the client's current inbounds with
the requested set and detaches from those only; (email, inbound) pairs
where the client is not currently attached are silently no-ops. Emails
@@ -197,110 +161,100 @@ _openapi:
skipped. Client records are kept even if they become orphaned — use
bulkDel for full removal. Returns per-email detached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
url: >-
#mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
running."
url: '#mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: >-
Zero up/down counters for many clients in one call. Loops the
title: Zero up/down counters for many clients in one call. Loops the
single-reset path so each client is re-enabled across its attached
inbounds and pushed to Xray/remote nodes. Returns the count of
successfully reset clients.
url: >-
#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
url: '#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients'
- depth: 2
title: >-
List all client groups with their member counts. Merges persisted groups
title: List all client groups with their member counts. Merges persisted groups
(rows in client_groups, including empty placeholders) with the distinct
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
url: '#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
title: Return just the email list of clients that currently belong to the given
group. Useful for fanning a single bulk action over an entire group
without round-tripping the full client list.
url: >-
#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
url: '#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list'
- depth: 2
title: >-
Create a new empty (placeholder) group. The group becomes selectable in
title: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
url: '#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists'
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
title: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
url: '#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated'
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
title: Remove a group. Deletes the client_groups row and clears the group label
from every matching client (both clients.group_name and the inbound
settings JSON). The clients themselves are NOT deleted — use /bulkDel
after filtering by group for that. Returns the count of clients whose
label was cleared.
url: >-
#remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
url: '#remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared'
- depth: 2
title: >-
Zero out a single clients up/down counters. Re-enables the client
across every attached inbound and pushes the change to Xray (or the
remote node) so depleted users can connect again immediately.
url: >-
#zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
title: Reset only the group-level traffic counter shown on the groups page.
Snapshots the current up/down sum of the group's members as a baseline
so the group total reads zero, while leaving each client's own counters
(and their quotas) untouched. No Xray restart is triggered. Creates the
client_groups row if the group exists only as a derived label.
url: '#reset-only-the-group-level-traffic-counter-shown-on-the-groups-page-snapshots-the-current-updown-sum-of-the-groups-members-as-a-baseline-so-the-group-total-reads-zero-while-leaving-each-clients-own-counters-and-their-quotas-untouched-no-xray-restart-is-triggered-creates-the-client_groups-row-if-the-group-exists-only-as-a-derived-label'
- depth: 2
title: >-
Manually adjust a clients upload + download counters. Useful for
title: Zero out a single clients up/down counters. Re-enables the client across
every attached inbound and pushes the change to Xray (or the remote
node) so depleted users can connect again immediately.
url: '#zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately'
- depth: 2
title: Manually adjust a clients upload + download counters. Useful for
migrations from external accounting systems.
url: >-
#manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
url: '#manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems'
- depth: 2
title: >-
List source IPs that have connected with the given clients credentials.
title: List source IPs that have connected with the given clients credentials.
Returns an array of "ip (timestamp)" strings.
url: >-
#list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
url: '#list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings'
- depth: 2
title: Reset the recorded IP list for a client.
url: '#reset-the-recorded-ip-list-for-a-client'
- depth: 2
title: >-
List the emails of currently connected clients (last seen within the
title: List registered HWID devices for a client. Hashes are not exposed.
url: '#list-registered-hwid-devices-for-a-client-hashes-are-not-exposed'
- depth: 2
title: Clear all registered HWID devices for a client so new devices can
register again.
url: '#clear-all-registered-hwid-devices-for-a-client-so-new-devices-can-register-again'
- depth: 2
title: Remove a single registered HWID device by its id, freeing one slot under
the HWID limit.
url: '#remove-a-single-registered-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit'
- depth: 2
title: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
url: >-
#list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
url: '#list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node'
- depth: 2
title: >-
Online client emails grouped by the panelGuid of the node that
physically hosts each client. The local panel uses its own GUID; each
node (at any depth in a chain) uses its GUID. Lets the inbounds page
attribute online status to the real node instead of the intermediate one
it syncs through.
url: >-
#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
title: Online client emails grouped by the panelGuid of the node that physically
hosts each client. The local panel uses its own GUID; each node (at any
depth in a chain) uses its GUID. Lets the inbounds page attribute online
status to the real node instead of the intermediate one it syncs
through.
url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through'
- depth: 2
title: >-
Per-client source IPs grouped by the panelGuid of the node that observed
title: Per-client source IPs grouped by the panelGuid of the node that observed
them. Lets the central panel attribute and enforce per-client IP limits
using the real visitor IPs each node sees, instead of the address of the
intermediate panel it syncs through.
url: >-
#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
url: '#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through'
- depth: 2
title: >-
Inbound tags that carried traffic within the heartbeat window, grouped
by the hosting node's panelGuid. Pairs with onlinesByGuid so the
inbounds page only marks a multi-inbound client online on the inbounds
it actually used. Nodes that do not report per-inbound activity are
absent.
url: >-
#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
title: Inbound tags that carried traffic within the heartbeat window, grouped by
the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds
page only marks a multi-inbound client online on the inbounds it
actually used. Nodes that do not report per-inbound activity are absent.
url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent'
- depth: 2
title: Map of client email → last-seen unix timestamp.
url: '#map-of-client-email--last-seen-unix-timestamp'
@@ -308,189 +262,149 @@ _openapi:
title: Traffic counters for a client identified by email.
url: '#traffic-counters-for-a-client-identified-by-email'
- depth: 2
title: >-
Return every protocol URL (vless://, vmess://, trojan://, ss://,
title: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
result set as /sub/<subId>, but as a JSON array — no base64. When an
inbound has streamSettings.externalProxy set, one URL is emitted per
external proxy. Empty array when the subId has no enabled clients.
url: >-
#return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
url: '#return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients'
- depth: 2
title: >-
Return every URL for one client across all attached inbounds — the same
title: 'Return every URL for one client across all attached inbounds — the same
strings the Copy URL button copies in the panel UI. Supported protocols:
vmess, vless, trojan, shadowsocks, hysteria. If
streamSettings.externalProxy is set, returns one URL per external proxy.
Protocols without a URL form (socks, http, mixed, wireguard, dokodemo,
tunnel) contribute nothing.
url: >-
#return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
tunnel) contribute nothing.'
url: '#return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing'
structuredData:
headings:
- content: >-
List every client with its attached inbound IDs and traffic record.
The reverse field, if set, is returned as a nested JSON object (legacy
- content: List every client with its attached inbound IDs and traffic record. The
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
id: >-
list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: >-
Filter, sort, and paginate clients on the server. Each item is a slim
id: list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
response also includes a summary computed across the full DB row set
so dashboard counters stay stable as the user paginates or filters.
Page size capped at 200; fetch /get/:email to obtain the full
per-client payload for an edit/info modal.
id: >-
filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal
- content: >-
Fetch one client by email, including the inbound IDs and external
so dashboard counters stay stable as the user paginates or filters:
the *Count fields are exact, while the email arrays beside them stop
at 200 entries so the payload does not grow with the panel. Page size
capped at 200; fetch /get/:email to obtain the full per-client payload
for an edit/info modal.'
id: filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-the-count-fields-are-exact-while-the-email-arrays-beside-them-stop-at-200-entries-so-the-payload-does-not-grow-with-the-panel-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal
- content: Fetch one client by email, including the inbound IDs and external
config IDs it is attached to.
id: >-
fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess,
password for Trojan/Shadowsocks, auth for Hysteria) are generated
server-side when omitted, so callers can send only the universal
fields.
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payloadsupply the full
set of fields you want to keep (the server replaces the row, it does
not patch).
id: >-
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
- content: >-
Delete a client by email. Removes it from every attached inbound and
id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: Fetch clients by Telegram user ID. Returns an array since multiple
clients can share the same Telegram ID.
id: fetch-clients-by-telegram-user-id-returns-an-array-since-multiple-clients-can-share-the-same-telegram-id
- content: Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets are generated server-side
when omitted, so callers can send only the universal fields.
id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of
fields you want to keep (the server replaces the row, it does not
patch).
id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
- content: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
id: >-
delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: >-
Attach an existing client to one or more additional inbounds. Body is
id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: Attach an existing client to one or more additional inbounds. Body is
JSON.
id: >-
attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
id: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
- content: Detach a client from one or more inbounds without deleting the client.
id: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client
- content: >-
Replace a client's external links (per-client share links and remote
subscription URLs surfaced in their subscription). Sends the full set;
the server replaces all rows.
id: >-
replace-a-clients-external-links-per-client-share-links-and-remote-subscription-urls-surfaced-in-their-subscription-sends-the-full-set-the-server-replaces-all-rows
- content: >-
Reset the up/down counters for every client globally. Quotas and
expiry are not affected. Triggers an Xray restart if any counter
actually moved.
id: >-
reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
- content: >-
Delete every client whose traffic quota is exhausted (used >= total,
- content: Replace a client's external links and external subscriptions. Sends the
full set; the server replaces all rows. Disabled rows stay saved for
editing but are not emitted in generated subscriptions.
id: replace-a-clients-external-links-and-external-subscriptions-sends-the-full-set-the-server-replaces-all-rows-disabled-rows-stay-saved-for-editing-but-are-not-emitted-in-generated-subscriptions
- content: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
moved.
id: reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
- content: Delete every client whose traffic quota is exhausted (used >= total,
when reset is disabled) or whose expiry has passed. Returns the
deleted count and triggers an Xray restart when any client was on a
running inbound.
id: >-
delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
- content: >-
Delete every client that is not attached to any inbound, along with
its traffic record, IP log, and external links. Useful for clearing
clients left unattached after their inbounds were removed. Returns the
deleted count. Cannot be undone.
id: >-
delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
- content: >-
Return every client as a {client, inboundIds} array — the same shape
id: delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
- content: Delete every client that is not attached to any inbound, along with its
traffic record, IP log, HWID devices, and external links. Useful for
clearing clients left unattached after their inbounds were removed.
Returns the deleted count. Cannot be undone.
id: delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-hwid-devices-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
- content: Return every client as a {client, inboundIds} array — the same shape
/bulkCreate and /import accept — so the payload round-trips straight
back through /import. Clients with no inbound attachment are included
with an empty inboundIds list. The UI shows this in a CodeMirror
viewer (copy / download); programmatic callers get the array in obj.
id: >-
return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
- content: >-
Import clients from a JSON body { "data": "<json>" }, where data is a
id: return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
- content: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]).
Items with inboundIds are created and attached to those inbounds;
items with an empty inboundIds list are restored as unattached client
records. Existing emails are never overwritten — they are returned in
skipped. Triggers a single Xray restart at the end if any target
inbound was running.
id: >-
import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
- content: >-
Shift expiry and/or traffic quota for many clients in one call.
inbound was running.'
id: import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
- content: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry
(expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the
corresponding field — bulk extend never converts unlimited to limited.
The optional flow directive sets the XTLS flow on every client: "none"
A client that was auto-disabled solely because it was depleted
(expired or over quota) is automatically re-enabled — locally and on
its node — when the adjustment lifts it out of depletion; a
manually-disabled or still-depleted client is left disabled. The
optional flow directive sets the XTLS flow on every client: "none"
clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where
the inbound supports it (omit or "" to leave it unchanged). Returns
the adjusted count and per-email skip reasons.
id: >-
shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
- content: >-
Enable many clients in one call. Emails are grouped by inbound and
the adjusted count and per-email skip reasons.'
id: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
- content: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to add each user. Note that enabling
a client whose quota is exhausted or whose expiry has passed only
flips the flag — the traffic loop will disable it again on the next
tick. Returns the changed count and per-email skip reasons.
id: >-
enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
- content: >-
Disable many clients in one call. Emails are grouped by inbound and
id: enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
- content: Disable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to remove each user. Returns the
changed count and per-email skip reasons.
id: >-
disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
- content: >-
Delete many clients in one call. The server processes the list
id: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
- content: Delete many clients in one call. The server processes the list
sequentially so each delete sees the committed state of the previous
one — avoids the race the per-email fan-out had on the panel side.
Pass keepTraffic=true to retain the xray_client_traffic rows after
deletion.
id: >-
delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
- content: >-
Create many clients in one call. Body is a JSON array of {client,
id: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
- content: Create many clients in one call. Body is a JSON array of {client,
inboundIds} payloads — the same shape /add accepts. Items are
processed sequentially; per-email skip reasons are returned for items
that fail (e.g., duplicate email). Triggers a single Xray restart at
the end if any inbound was running.
id: >-
create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
- content: >-
Add many clients to a group in one call. Updates clients.group_name
and patches the matching client entry inside every owning inbound's
id: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
- content: Add many clients to a group in one call. Updates clients.group_name and
patches the matching client entry inside every owning inbound's
settings JSON in a single transaction. If the group name does not yet
exist (in client_groups or as a derived label), it is auto-created as
a persistent group. To clear the group label, use /groups/bulkRemove
instead.
id: >-
add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
- content: >-
Clear the group label on many clients in one call. Inverse of
id: add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
- content: Clear the group label on many clients in one call. Inverse of
/groups/bulkAdd. Clients themselves are kept — only the group label is
cleared from clients.group_name and from each owning inbound's
settings JSON. Groups become empty if all their members are removed.
id: >-
clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
- content: >-
Attach many existing clients to many inbounds in one call. Each client
id: clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
- content: Attach many existing clients to many inbounds in one call. Each client
keeps its identity (email/UUID/password/subId) and a shared traffic
row; all clients are added to a target inbound in a single
AddInboundClient call. Clients already present on a target are
reported under skipped. Returns per-email attached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
id: >-
attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: >-
Mirror of bulkAttach: detach many existing clients from many inbounds
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: "Mirror of bulkAttach: detach many existing clients from many inbounds
in one call. For each email, intersects the client's current inbounds
with the requested set and detaches from those only; (email, inbound)
pairs where the client is not currently attached are silently no-ops.
@@ -498,118 +412,152 @@ _openapi:
under skipped. Client records are kept even if they become orphaned —
use bulkDel for full removal. Returns per-email
detached/skipped/errors lists and triggers a single Xray restart if
any target inbound was running.
id: >-
mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: >-
Zero up/down counters for many clients in one call. Loops the
any target inbound was running."
id: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: Zero up/down counters for many clients in one call. Loops the
single-reset path so each client is re-enabled across its attached
inbounds and pushed to Xray/remote nodes. Returns the count of
successfully reset clients.
id: >-
zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
- content: >-
List all client groups with their member counts. Merges persisted
id: zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
- content: List all client groups with their member counts. Merges persisted
groups (rows in client_groups, including empty placeholders) with the
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
id: list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
group without round-tripping the full client list.
id: >-
return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: >-
Create a new empty (placeholder) group. The group becomes selectable
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
id: return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
id: create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
id: rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
- content: Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
inbound settings JSON). The clients themselves are NOT deleted — use
/bulkDel after filtering by group for that. Returns the count of
clients whose label was cleared.
id: >-
remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
- content: >-
Zero out a single clients up/down counters. Re-enables the client
id: remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
- content: Reset only the group-level traffic counter shown on the groups page.
Snapshots the current up/down sum of the group's members as a baseline
so the group total reads zero, while leaving each client's own
counters (and their quotas) untouched. No Xray restart is triggered.
Creates the client_groups row if the group exists only as a derived
label.
id: reset-only-the-group-level-traffic-counter-shown-on-the-groups-page-snapshots-the-current-updown-sum-of-the-groups-members-as-a-baseline-so-the-group-total-reads-zero-while-leaving-each-clients-own-counters-and-their-quotas-untouched-no-xray-restart-is-triggered-creates-the-client_groups-row-if-the-group-exists-only-as-a-derived-label
- content: Zero out a single clients up/down counters. Re-enables the client
across every attached inbound and pushes the change to Xray (or the
remote node) so depleted users can connect again immediately.
id: >-
zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
- content: >-
Manually adjust a clients upload + download counters. Useful for
id: zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
- content: Manually adjust a clients upload + download counters. Useful for
migrations from external accounting systems.
id: >-
manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
- content: >-
List source IPs that have connected with the given clients
id: manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
- content: List source IPs that have connected with the given clients
credentials. Returns an array of "ip (timestamp)" strings.
id: >-
list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
id: list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
- content: Reset the recorded IP list for a client.
id: reset-the-recorded-ip-list-for-a-client
- content: >-
List the emails of currently connected clients (last seen within the
- content: List registered HWID devices for a client. Hashes are not exposed.
id: list-registered-hwid-devices-for-a-client-hashes-are-not-exposed
- content: Clear all registered HWID devices for a client so new devices can
register again.
id: clear-all-registered-hwid-devices-for-a-client-so-new-devices-can-register-again
- content: Remove a single registered HWID device by its id, freeing one slot
under the HWID limit.
id: remove-a-single-registered-hwid-device-by-its-id-freeing-one-slot-under-the-hwid-limit
- content: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
id: >-
list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
- content: >-
Online client emails grouped by the panelGuid of the node that
id: list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
- content: Online client emails grouped by the panelGuid of the node that
physically hosts each client. The local panel uses its own GUID; each
node (at any depth in a chain) uses its GUID. Lets the inbounds page
attribute online status to the real node instead of the intermediate
one it syncs through.
id: >-
online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
- content: >-
Per-client source IPs grouped by the panelGuid of the node that
id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
- content: Per-client source IPs grouped by the panelGuid of the node that
observed them. Lets the central panel attribute and enforce per-client
IP limits using the real visitor IPs each node sees, instead of the
address of the intermediate panel it syncs through.
id: >-
per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
- content: >-
Inbound tags that carried traffic within the heartbeat window, grouped
id: per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
- content: Inbound tags that carried traffic within the heartbeat window, grouped
by the hosting node's panelGuid. Pairs with onlinesByGuid so the
inbounds page only marks a multi-inbound client online on the inbounds
it actually used. Nodes that do not report per-inbound activity are
absent.
id: >-
inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
- content: Map of client email → last-seen unix timestamp.
id: map-of-client-email--last-seen-unix-timestamp
- content: Traffic counters for a client identified by email.
id: traffic-counters-for-a-client-identified-by-email
- content: >-
Return every protocol URL (vless://, vmess://, trojan://, ss://,
- content: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
result set as /sub/<subId>, but as a JSON array — no base64. When an
inbound has streamSettings.externalProxy set, one URL is emitted per
external proxy. Empty array when the subId has no enabled clients.
id: >-
return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
- content: >-
Return every URL for one client across all attached inbounds — the
id: return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
- content: 'Return every URL for one client across all attached inbounds — the
same strings the Copy URL button copies in the panel UI. Supported
protocols: vmess, vless, trojan, shadowsocks, hysteria. If
streamSettings.externalProxy is set, returns one URL per external
proxy. Protocols without a URL form (socks, http, mixed, wireguard,
dokodemo, tunnel) contribute nothing.
id: >-
return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents: []
dokodemo, tunnel) contribute nothing.'
id: return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents:
- content: >-
Fields the server fills in when they are omitted — a valid value sent
by the caller is never overwritten. Re-adding an email that already
exists, with its stored `subId`, reuses the stored `id`, `password`,
`auth` and `secret` instead of minting new ones, so the identity stays
in sync across its inbounds.
- **VLESS / VMess** — `id`, a fresh UUID
- **Trojan** — `password`
- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a
supplied password that does not base64-decode to the key length of the
cipher (16 or 32 bytes) is replaced by a generated key and the call
still succeeds, so read the client back if you did not let the server
pick. Legacy ciphers keep any non-empty password
- **Hysteria** — `auth`
- **mtproto** — `secret`, a FakeTLS secret derived from the fronting
domain of the inbound, or from `www.cloudflare.com` when it has none
- **WireGuard** — `privateKey` and `publicKey` when both are blank, or
`publicKey` alone when only a `privateKey` was sent, plus
`allowedIPs`: one free `/32` taken from the /24 the existing peers of
that inbound already sit in, or from `10.0.0.0/24` when it has none
Accepted on the same body but never generated: `preSharedKey` and
`keepAlive` (WireGuard), `adTag` (mtproto).
WireGuard is the only one of these that can fail. Allocation widens
the search to the containing /16 before giving up with `wireguard: no
free address available in <scope>`, and an `allowedIPs` supplied by
the caller is validated instead of allocated: `wireguard: allowedIPs
entry already used by another client: <address>` when a different
client of that same inbound already holds it. The check is per
inbound, so the same address on two different inbounds is accepted.
The same validation runs on POST /panel/api/clients/{email}/attach,
where a client that already carries an address brings it along.
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound
instead of being given a fresh address, so the call fails with
`wireguard: allowedIPs entry already used by another client:
<address>` when a different client of the target inbound already holds
it. Free the address on that inbound first — see POST
/panel/api/clients/add for the full rule.'
heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
@@ -621,7 +569,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
</>
);
}
+48 -66
View File
@@ -1,7 +1,6 @@
---
title: Hosts
description: >-
Per-inbound override endpoints. Each enabled host renders one extra
description: Per-inbound override endpoints. Each enabled host renders one extra
subscription link/proxy with its own address/port/TLS, superseding the legacy
externalProxy array. All endpoints under /panel/api/hosts.
full: true
@@ -10,86 +9,69 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every host across all inbounds, grouped by inbound then ordered by
title: List every host across all inbounds, grouped by inbound then ordered by
sort order.
url: >-
#list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order
url: '#list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order'
- depth: 2
title: Fetch a single host by ID.
url: '#fetch-a-single-host-by-id'
title: Fetch a single host group by Group ID.
url: '#fetch-a-single-host-group-by-group-id'
- depth: 2
title: Fetch one inbound's hosts, ordered by sort order then id.
url: '#fetch-one-inbounds-hosts-ordered-by-sort-order-then-id'
title: Fetch one inbound's hosts, grouped by host group.
url: '#fetch-one-inbounds-hosts-grouped-by-host-group'
- depth: 2
title: Distinct, sorted set of tags used across all hosts.
url: '#distinct-sorted-set-of-tags-used-across-all-hosts'
- depth: 2
title: >-
Create a host on an inbound. inboundId and remark are required; security
defaults to "same" (inherit the inbound).
url: >-
#create-a-host-on-an-inbound-inboundid-and-remark-are-required-security-defaults-to-same-inherit-the-inbound
title: Create a host group on inbounds.
url: '#create-a-host-group-on-inbounds'
- depth: 2
title: >-
Replace a hosts content. The inbound and sort order are immutable here
(use /reorder for ordering).
url: >-
#replace-a-hosts-content-the-inbound-and-sort-order-are-immutable-here-use-reorder-for-ordering
title: Replace a host groups content.
url: '#replace-a-host-groups-content'
- depth: 2
title: Delete a host.
url: '#delete-a-host'
title: Delete a host group.
url: '#delete-a-host-group'
- depth: 2
title: >-
Enable or disable a single host (disabled hosts are skipped in
subscriptions).
url: >-
#enable-or-disable-a-single-host-disabled-hosts-are-skipped-in-subscriptions
title: Enable or disable a host group.
url: '#enable-or-disable-a-host-group'
- depth: 2
title: Set host sort order by the position of each id in the array.
url: '#set-host-sort-order-by-the-position-of-each-id-in-the-array'
title: Set host group sort order by the position of each groupId in the array.
url: '#set-host-group-sort-order-by-the-position-of-each-groupid-in-the-array'
- depth: 2
title: Enable or disable many hosts in one call.
url: '#enable-or-disable-many-hosts-in-one-call'
title: Add a host group to inbounds (same as /add).
url: '#add-a-host-group-to-inbounds-same-as-add'
- depth: 2
title: Delete many hosts in one call.
url: '#delete-many-hosts-in-one-call'
title: Enable or disable many host groups in one call.
url: '#enable-or-disable-many-host-groups-in-one-call'
- depth: 2
title: Delete many host groups in one call.
url: '#delete-many-host-groups-in-one-call'
structuredData:
headings:
- content: >-
List every host across all inbounds, grouped by inbound then ordered
by sort order.
id: >-
list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order
- content: Fetch a single host by ID.
id: fetch-a-single-host-by-id
- content: Fetch one inbound's hosts, ordered by sort order then id.
id: fetch-one-inbounds-hosts-ordered-by-sort-order-then-id
- content: List every host across all inbounds, grouped by inbound then ordered by
sort order.
id: list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order
- content: Fetch a single host group by Group ID.
id: fetch-a-single-host-group-by-group-id
- content: Fetch one inbound's hosts, grouped by host group.
id: fetch-one-inbounds-hosts-grouped-by-host-group
- content: Distinct, sorted set of tags used across all hosts.
id: distinct-sorted-set-of-tags-used-across-all-hosts
- content: >-
Create a host on an inbound. inboundId and remark are required;
security defaults to "same" (inherit the inbound).
id: >-
create-a-host-on-an-inbound-inboundid-and-remark-are-required-security-defaults-to-same-inherit-the-inbound
- content: >-
Replace a hosts content. The inbound and sort order are immutable
here (use /reorder for ordering).
id: >-
replace-a-hosts-content-the-inbound-and-sort-order-are-immutable-here-use-reorder-for-ordering
- content: Delete a host.
id: delete-a-host
- content: >-
Enable or disable a single host (disabled hosts are skipped in
subscriptions).
id: >-
enable-or-disable-a-single-host-disabled-hosts-are-skipped-in-subscriptions
- content: Set host sort order by the position of each id in the array.
id: set-host-sort-order-by-the-position-of-each-id-in-the-array
- content: Enable or disable many hosts in one call.
id: enable-or-disable-many-hosts-in-one-call
- content: Delete many hosts in one call.
id: delete-many-hosts-in-one-call
- content: Create a host group on inbounds.
id: create-a-host-group-on-inbounds
- content: Replace a host groups content.
id: replace-a-host-groups-content
- content: Delete a host group.
id: delete-a-host-group
- content: Enable or disable a host group.
id: enable-or-disable-a-host-group
- content: Set host group sort order by the position of each groupId in the array.
id: set-host-group-sort-order-by-the-position-of-each-groupid-in-the-array
- content: Add a host group to inbounds (same as /add).
id: add-a-host-group-to-inbounds-same-as-add
- content: Enable or disable many host groups in one call.
id: enable-or-disable-many-host-groups-in-one-call
- content: Delete many host groups in one call.
id: delete-many-host-groups-in-one-call
contents: []
---
@@ -102,7 +84,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{id}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{id}","method":"post"},{"path":"/panel/api/hosts/del/{id}","method":"post"},{"path":"/panel/api/hosts/setEnable/{id}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{groupId}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{groupId}","method":"post"},{"path":"/panel/api/hosts/del/{groupId}","method":"post"},{"path":"/panel/api/hosts/setEnable/{groupId}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/add","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
</>
);
}
+85 -120
View File
@@ -1,8 +1,7 @@
---
title: Inbounds
description: >-
Manage inbound configurations and their clients. All endpoints live under
/panel/api/inbounds and require a logged-in session or Bearer token.
description: Manage inbound configurations and their clients. All endpoints live
under /panel/api/inbounds and require a logged-in session or Bearer token.
Link-generating endpoints honour forwarded headers only when the request comes
from a configured trusted proxy.
full: true
@@ -11,25 +10,20 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every inbound owned by the authenticated user, including each
title: List every inbound owned by the authenticated user, including each
inbounds clientStats traffic counters. settings, streamSettings, and
sniffing are returned as nested JSON objects (no escaped strings);
legacy callers that send them back as JSON-encoded strings are still
accepted on write.
url: >-
#list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
url: '#list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write'
- depth: 2
title: >-
Same shape as /list but with settings.clients[] stripped down to {email,
title: Same shape as /list but with settings.clients[] stripped down to {email,
enable, comment} and ClientStats not enriched with UUID/SubId. Use this
for list pages; fetch /get/:id when you need the full per-client payload
(uuid, password, flow, ...).
url: >-
#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-'
- depth: 2
title: >-
Lightweight picker projection of the authenticated users inbounds.
title: Lightweight picker projection of the authenticated users inbounds.
Returns id, remark, tag, protocol, port, a server-computed
tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on
XHTTP with VLESS encryption / vlessenc enabled), and ssMethod (the
@@ -38,110 +32,95 @@ _openapi:
dropdowns and attach pickers — it skips settings, streamSettings, and
clientStats so the payload stays small even on panels with thousands of
clients.
url: >-
#lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
url: '#lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients'
- depth: 2
title: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, mtproto) across all inbounds and all of their clients.
Links are rendered through the subscription engine, so the configured
remark template (name-only display part) is applied per client — the
same output the client info/QR pages use. Protocols without a URL form
(socks, http, mixed, wireguard, dokodemo, tunnel) contribute nothing.
Used by the panels "Export all inbound links" action.
url: '#return-every-protocol-url-vless-vmess-trojan-ss-hysteria-mtproto-across-all-inbounds-and-all-of-their-clients-links-are-rendered-through-the-subscription-engine-so-the-configured-remark-template-name-only-display-part-is-applied-per-client--the-same-output-the-client-infoqr-pages-use-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing-used-by-the-panels-export-all-inbound-links-action'
- depth: 2
title: Fetch a single inbound by numeric ID.
url: '#fetch-a-single-inbound-by-numeric-id'
- depth: 2
title: >-
Create a new inbound. Send the full inbound payload (protocol, port,
title: Create a new inbound. Send the full inbound payload (protocol, port,
settings, streamSettings, sniffing, remark, expiryTime, total, enable).
settings, streamSettings, and sniffing may be sent as nested JSON
objects (preferred) or as JSON-encoded strings (legacy).
url: >-
#create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
url: '#create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy'
- depth: 2
title: Delete an inbound by ID. Also removes its associated client stats rows.
url: '#delete-an-inbound-by-id-also-removes-its-associated-client-stats-rows'
- depth: 2
title: >-
Delete many inbounds in one call. Processes the list sequentially;
title: Delete many inbounds in one call. Processes the list sequentially;
failures are reported per id and the rest still proceed. Restarts xray
at most once.
url: >-
#delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
url: '#delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once'
- depth: 2
title: >-
Replace an inbounds configuration. Body shape mirrors /add. Heavy on
title: Replace an inbounds configuration. Body shape mirrors /add. Heavy on
inbounds with thousands of clients — prefer /setEnable for enable-only
flips.
url: >-
#replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
url: '#replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips'
- depth: 2
title: >-
Toggle only the enable flag without serialising the whole settings JSON.
title: Toggle only the enable flag without serialising the whole settings JSON.
Recommended for UI switches on large inbounds.
url: >-
#toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
url: '#toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds'
- depth: 2
title: >-
Zero out upload + download counters for a single inbound. Does not touch
title: Set only the subscription sort order. Reads the stored inbound, so a
reorder cannot carry a stale client list over a concurrent edit.
url: '#set-only-the-subscription-sort-order-reads-the-stored-inbound-so-a-reorder-cannot-carry-a-stale-client-list-over-a-concurrent-edit'
- depth: 2
title: Zero out upload + download counters for a single inbound. Does not touch
per-client counters.
url: >-
#zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
url: '#zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters'
- depth: 2
title: >-
Remove every client attached to a single inbound while keeping the
title: Remove every client attached to a single inbound while keeping the
inbound itself. Collects emails from settings.clients[] and feeds them
into the optimized bulk-delete path (runtime user removal + traffic-row
cleanup + SyncInbound). Destructive and cannot be undone.
url: >-
#remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
url: '#remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone'
- depth: 2
title: >-
Reset upload + download counters on every inbound. Destructive —
title: Reset upload + download counters on every inbound. Destructive —
accounting history is lost.
url: >-
#reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
url: '#reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost'
- depth: 2
title: >-
Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
title: Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
The body uses form encoding with a single "data" field.
url: >-
#bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
url: '#bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field'
- depth: 2
title: >-
Receive a master panel's aggregated per-client usage, keyed by the
title: Receive a master panel's aggregated per-client usage, keyed by the
master's GUID. Stored in a side table used only for the UI display
overlay and local quota enforcement — never folded into the local
counters that masters poll, so delta accounting stays intact. Called
panel-to-panel by the node traffic sync job.
url: >-
#receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
url: '#receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job'
- depth: 2
title: >-
List the fallback rules attached to a master VLESS/Trojan TCP-TLS
title: List the fallback rules attached to a master VLESS/Trojan TCP-TLS
inbound. Each rule links one child inbound (the dest) to optional
SNI/ALPN/path/dest/xver match criteria. When dest is empty the child
inbound's listen+port is used.
url: >-
#list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
url: '#list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used'
- depth: 2
title: >-
Replace the entire fallback list for a master inbound. Body is JSON.
title: Replace the entire fallback list for a master inbound. Body is JSON.
Triggers an Xray restart.
url: >-
#replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
url: '#replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart'
structuredData:
headings:
- content: >-
List every inbound owned by the authenticated user, including each
- content: List every inbound owned by the authenticated user, including each
inbounds clientStats traffic counters. settings, streamSettings, and
sniffing are returned as nested JSON objects (no escaped strings);
legacy callers that send them back as JSON-encoded strings are still
accepted on write.
id: >-
list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
- content: >-
Same shape as /list but with settings.clients[] stripped down to
id: list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
- content: Same shape as /list but with settings.clients[] stripped down to
{email, enable, comment} and ClientStats not enriched with UUID/SubId.
Use this for list pages; fetch /get/:id when you need the full
per-client payload (uuid, password, flow, ...).
id: >-
same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
- content: >-
Lightweight picker projection of the authenticated users inbounds.
id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
- content: Lightweight picker projection of the authenticated users inbounds.
Returns id, remark, tag, protocol, port, a server-computed
tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on
XHTTP with VLESS encryption / vlessenc enabled), and ssMethod (the
@@ -150,80 +129,66 @@ _openapi:
dropdowns and attach pickers — it skips settings, streamSettings, and
clientStats so the payload stays small even on panels with thousands
of clients.
id: >-
lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
id: lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
- content: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, mtproto) across all inbounds and all of their clients.
Links are rendered through the subscription engine, so the configured
remark template (name-only display part) is applied per client — the
same output the client info/QR pages use. Protocols without a URL form
(socks, http, mixed, wireguard, dokodemo, tunnel) contribute nothing.
Used by the panels "Export all inbound links" action.
id: return-every-protocol-url-vless-vmess-trojan-ss-hysteria-mtproto-across-all-inbounds-and-all-of-their-clients-links-are-rendered-through-the-subscription-engine-so-the-configured-remark-template-name-only-display-part-is-applied-per-client--the-same-output-the-client-infoqr-pages-use-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing-used-by-the-panels-export-all-inbound-links-action
- content: Fetch a single inbound by numeric ID.
id: fetch-a-single-inbound-by-numeric-id
- content: >-
Create a new inbound. Send the full inbound payload (protocol, port,
- content: Create a new inbound. Send the full inbound payload (protocol, port,
settings, streamSettings, sniffing, remark, expiryTime, total,
enable). settings, streamSettings, and sniffing may be sent as nested
JSON objects (preferred) or as JSON-encoded strings (legacy).
id: >-
create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
- content: >-
Delete an inbound by ID. Also removes its associated client stats
rows.
id: create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
- content: Delete an inbound by ID. Also removes its associated client stats rows.
id: delete-an-inbound-by-id-also-removes-its-associated-client-stats-rows
- content: >-
Delete many inbounds in one call. Processes the list sequentially;
- content: Delete many inbounds in one call. Processes the list sequentially;
failures are reported per id and the rest still proceed. Restarts xray
at most once.
id: >-
delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
- content: >-
Replace an inbounds configuration. Body shape mirrors /add. Heavy on
id: delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
- content: Replace an inbounds configuration. Body shape mirrors /add. Heavy on
inbounds with thousands of clients — prefer /setEnable for enable-only
flips.
id: >-
replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
- content: >-
Toggle only the enable flag without serialising the whole settings
id: replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
- content: Toggle only the enable flag without serialising the whole settings
JSON. Recommended for UI switches on large inbounds.
id: >-
toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
- content: >-
Zero out upload + download counters for a single inbound. Does not
id: toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
- content: Set only the subscription sort order. Reads the stored inbound, so a
reorder cannot carry a stale client list over a concurrent edit.
id: set-only-the-subscription-sort-order-reads-the-stored-inbound-so-a-reorder-cannot-carry-a-stale-client-list-over-a-concurrent-edit
- content: Zero out upload + download counters for a single inbound. Does not
touch per-client counters.
id: >-
zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
- content: >-
Remove every client attached to a single inbound while keeping the
id: zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
- content: Remove every client attached to a single inbound while keeping the
inbound itself. Collects emails from settings.clients[] and feeds them
into the optimized bulk-delete path (runtime user removal +
traffic-row cleanup + SyncInbound). Destructive and cannot be undone.
id: >-
remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
- content: >-
Reset upload + download counters on every inbound. Destructive —
id: remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
- content: Reset upload + download counters on every inbound. Destructive
accounting history is lost.
id: >-
reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
- content: >-
Bulk-import an inbound from a JSON blob (e.g. one exported via the
UI). The body uses form encoding with a single "data" field.
id: >-
bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
- content: >-
Receive a master panel's aggregated per-client usage, keyed by the
id: reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
- content: Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
The body uses form encoding with a single "data" field.
id: bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
- content: Receive a master panel's aggregated per-client usage, keyed by the
master's GUID. Stored in a side table used only for the UI display
overlay and local quota enforcement — never folded into the local
counters that masters poll, so delta accounting stays intact. Called
panel-to-panel by the node traffic sync job.
id: >-
receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
- content: >-
List the fallback rules attached to a master VLESS/Trojan TCP-TLS
id: receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
- content: List the fallback rules attached to a master VLESS/Trojan TCP-TLS
inbound. Each rule links one child inbound (the dest) to optional
SNI/ALPN/path/dest/xver match criteria. When dest is empty the child
inbound's listen+port is used.
id: >-
list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
- content: >-
Replace the entire fallback list for a master inbound. Body is JSON.
id: list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
- content: Replace the entire fallback list for a master inbound. Body is JSON.
Triggers an Xray restart.
id: >-
replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
contents: []
---
@@ -236,7 +201,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/allLinks","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/subSortIndex","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
</>
);
}
@@ -11,6 +11,7 @@
"settings",
"xray-settings",
"subscription-server",
"subscription-balancers",
"hosts",
"nodes",
"backup",
+68 -94
View File
@@ -1,54 +1,51 @@
---
title: Nodes
description: >-
Manage remote 3x-ui panels acting as nodes for a central panel. All endpoints
under /panel/api/nodes.
description: Manage remote 3x-ui panels acting as nodes for a central panel. All
endpoints under /panel/api/nodes.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every configured node with its connection details, health, and last
title: List every configured node with its connection details, health, and last
heartbeat patch.
url: >-
#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch'
- depth: 2
title: >-
This panel's node-auth CA certificate (public, PEM) to paste into a
title: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
url: >-
#this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
url: '#this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node'
- depth: 2
title: >-
Set the CA certificate this panel trusts for incoming node-API client
title: Set the CA certificate this panel trusts for incoming node-API client
certificates (this panel acting as a node). Paste the managing panel's
CA (from nodes/mtls/ca). An empty caCert disables it. A non-empty value
must be a PEM certificate. Applied on the next panel restart.
url: >-
#set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
url: '#set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart'
- depth: 2
title: Validate the stored master mTLS client credential and invalidate cached
transports. Each transport closes its old idle pool and rebuilds with
the rotated certificate before its next request.
url: '#validate-the-stored-master-mtls-client-credential-and-invalidate-cached-transports-each-transport-closes-its-old-idle-pool-and-rebuilds-with-the-rotated-certificate-before-its-next-request'
- depth: 2
title: Fetch a single node by ID.
url: '#fetch-a-single-node-by-id'
- depth: 2
title: >-
Fetch a node's own web TLS certificate/key file paths (proxied to the
title: Fetch a node's own web TLS certificate/key file paths (proxied to the
node). Used by the inbound form's "Set Cert from Panel" so a
node-assigned inbound gets paths that exist on the node, not the central
panel.
url: >-
#fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel
url: '#fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel'
- depth: 2
title: >-
Register a new remote node. Provide its URL, apiToken, and optional
remark / allowPrivateAddress flag.
url: >-
#register-a-new-remote-node-provide-its-url-apitoken-and-optional-remark--allowprivateaddress-flag
title: Register a new remote node. Provide its URL, write-only apiToken, and
optional remark / allowPrivateAddress flag. Responses expose hasApiToken
only.
url: '#register-a-new-remote-node-provide-its-url-write-only-apitoken-and-optional-remark--allowprivateaddress-flag-responses-expose-hasapitoken-only'
- depth: 2
title: Replace a nodes connection details. Same body shape as /add.
url: '#replace-a-nodes-connection-details-same-body-shape-as-add'
title: 'Replace a nodes connection details. apiToken is write-only: omit it or
send an empty string to keep the stored token; set clearApiToken=true to
clear it.'
url: '#replace-a-nodes-connection-details-apitoken-is-write-only-omit-it-or-send-an-empty-string-to-keep-the-stored-token-set-clearapitokentrue-to-clear-it'
- depth: 2
title: Delete a node. Inbounds bound to it are not auto-migrated.
url: '#delete-a-node-inbounds-bound-to-it-are-not-auto-migrated'
@@ -56,115 +53,92 @@ _openapi:
title: Pause or resume traffic sync with this node.
url: '#pause-or-resume-traffic-sync-with-this-node'
- depth: 2
title: >-
Probe a node without saving it. Uses the body as connection details and
title: Probe a node without saving it. Uses the body as connection details and
returns the same heartbeat snapshot a registered node would have.
url: >-
#probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
url: '#probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have'
- depth: 2
title: >-
Connect to the node over HTTPS without verifying its certificate and
title: Connect to the node over HTTPS without verifying its certificate and
return the leaf certificate's SHA-256 (base64). Used by the Add/Edit
Node dialog to fetch and pin a self-signed certificate. Uses the same
body as /test.
url: >-
#connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
url: '#connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test'
- depth: 2
title: >-
Use unsaved node connection details to list the remote inbounds
available for selective import.
url: >-
#use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
title: Use unsaved node connection details to list the remote inbounds available
for selective import.
url: '#use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import'
- depth: 2
title: Probe an existing node, updating its cached health state.
url: '#probe-an-existing-node-updating-its-cached-health-state'
- depth: 2
title: >-
Trigger the official panel self-updater on each given node (downloads
title: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
updated; offline/disabled ones are reported as skipped. Set "dev": true
to move the nodes to the rolling per-commit dev channel instead of the
latest stable release. Returns a per-node result list.
url: >-
#trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
latest stable release. Returns a per-node result list.'
url: '#trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list'
- depth: 2
title: >-
Aggregated metric history for a node — same shape as /server/history,
title: Aggregated metric history for a node — same shape as /server/history,
scoped to one node.
url: >-
#aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
url: '#aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node'
structuredData:
headings:
- content: >-
List every configured node with its connection details, health, and
- content: List every configured node with its connection details, health, and
last heartbeat patch.
id: >-
list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
- content: >-
This panel's node-auth CA certificate (public, PEM) to paste into a
id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
- content: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
id: >-
this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
- content: >-
Set the CA certificate this panel trusts for incoming node-API client
id: this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
- content: Set the CA certificate this panel trusts for incoming node-API client
certificates (this panel acting as a node). Paste the managing panel's
CA (from nodes/mtls/ca). An empty caCert disables it. A non-empty
value must be a PEM certificate. Applied on the next panel restart.
id: >-
set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
id: set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
- content: Validate the stored master mTLS client credential and invalidate cached
transports. Each transport closes its old idle pool and rebuilds with
the rotated certificate before its next request.
id: validate-the-stored-master-mtls-client-credential-and-invalidate-cached-transports-each-transport-closes-its-old-idle-pool-and-rebuilds-with-the-rotated-certificate-before-its-next-request
- content: Fetch a single node by ID.
id: fetch-a-single-node-by-id
- content: >-
Fetch a node's own web TLS certificate/key file paths (proxied to the
- content: Fetch a node's own web TLS certificate/key file paths (proxied to the
node). Used by the inbound form's "Set Cert from Panel" so a
node-assigned inbound gets paths that exist on the node, not the
central panel.
id: >-
fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel
- content: >-
Register a new remote node. Provide its URL, apiToken, and optional
remark / allowPrivateAddress flag.
id: >-
register-a-new-remote-node-provide-its-url-apitoken-and-optional-remark--allowprivateaddress-flag
- content: Replace a nodes connection details. Same body shape as /add.
id: replace-a-nodes-connection-details-same-body-shape-as-add
id: fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel
- content: Register a new remote node. Provide its URL, write-only apiToken, and
optional remark / allowPrivateAddress flag. Responses expose
hasApiToken only.
id: register-a-new-remote-node-provide-its-url-write-only-apitoken-and-optional-remark--allowprivateaddress-flag-responses-expose-hasapitoken-only
- content: 'Replace a nodes connection details. apiToken is write-only: omit it
or send an empty string to keep the stored token; set
clearApiToken=true to clear it.'
id: replace-a-nodes-connection-details-apitoken-is-write-only-omit-it-or-send-an-empty-string-to-keep-the-stored-token-set-clearapitokentrue-to-clear-it
- content: Delete a node. Inbounds bound to it are not auto-migrated.
id: delete-a-node-inbounds-bound-to-it-are-not-auto-migrated
- content: Pause or resume traffic sync with this node.
id: pause-or-resume-traffic-sync-with-this-node
- content: >-
Probe a node without saving it. Uses the body as connection details
and returns the same heartbeat snapshot a registered node would have.
id: >-
probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
- content: >-
Connect to the node over HTTPS without verifying its certificate and
- content: Probe a node without saving it. Uses the body as connection details and
returns the same heartbeat snapshot a registered node would have.
id: probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
- content: Connect to the node over HTTPS without verifying its certificate and
return the leaf certificate's SHA-256 (base64). Used by the Add/Edit
Node dialog to fetch and pin a self-signed certificate. Uses the same
body as /test.
id: >-
connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
- content: >-
Use unsaved node connection details to list the remote inbounds
id: connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
- content: Use unsaved node connection details to list the remote inbounds
available for selective import.
id: >-
use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
id: use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
- content: Probe an existing node, updating its cached health state.
id: probe-an-existing-node-updating-its-cached-health-state
- content: >-
Trigger the official panel self-updater on each given node (downloads
- content: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
updated; offline/disabled ones are reported as skipped. Set "dev":
true to move the nodes to the rolling per-commit dev channel instead
of the latest stable release. Returns a per-node result list.
id: >-
trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
- content: >-
Aggregated metric history for a node — same shape as /server/history,
of the latest stable release. Returns a per-node result list.'
id: trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
- content: Aggregated metric history for a node — same shape as /server/history,
scoped to one node.
id: >-
aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
id: aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
contents: []
---
@@ -177,7 +151,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
</>
);
}
+189 -235
View File
@@ -1,159 +1,131 @@
---
title: Server
description: >-
System status, log retrieval, certificate generators, Xray binary management,
and backup/restore. All under /panel/api/server.
description: System status, log retrieval, certificate generators, Xray binary
management, and backup/restore. All under /panel/api/server.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
seconds in the background.
url: >-
#real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
title: Serve this API description as an OpenAPI 3 document — the same file that
powers the API Docs page. Requires a session or Bearer token like the
rest of /panel/api. Useful for generating clients or importing into API
tooling.
url: '#serve-this-api-description-as-an-openapi-3-document--the-same-file-that-powers-the-api-docs-page-requires-a-session-or-bearer-token-like-the-rest-of-panelapi-useful-for-generating-clients-or-importing-into-api-tooling'
- depth: 2
title: >-
Reports whether per-client IP limits can be enforced on this host. The
title: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
seconds in the background.'
url: '#real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background'
- depth: 2
title: Reports whether per-client IP limits can be enforced on this host. The
panel uses it to gate the "IP Limit" field, since enforcement depends on
Fail2ban being installed.
url: >-
#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
url: '#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed'
- depth: 2
title: >-
Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.
url: >-
#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
title: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.'
url: '#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape'
- depth: 2
title: >-
Aggregated time-series for one metric. Returns an array of {t, v}
samples covering the last ~6 hours.
url: >-
#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
title: Aggregated time-series for one metric. Returns an array of {t, v} samples
covering the last ~6 hours.
url: '#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours'
- depth: 2
title: >-
Xray runtime metrics state — whether the xray config has a `metrics`
title: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
url: >-
#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
url: '#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured'
- depth: 2
title: >-
Time-series history for one Xray runtime metric over the last ~6 hours.
title: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
url: >-
#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
url: '#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket'
- depth: 2
title: >-
Latest snapshot from the Xray observatory — per-outbound latency, health
title: Latest snapshot from the Xray observatory — per-outbound latency, health
status, and last-probe time. Only populated when the Xray config has an
observatory configured.
url: >-
#latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
url: '#latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured'
- depth: 2
title: >-
Time-series of observatory probe results for one outbound tag. Same {t,
title: Time-series of observatory probe results for one outbound tag. Same {t,
v} shape as the other history endpoints.
url: >-
#time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
url: '#time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints'
- depth: 2
title: List Xray binary versions available for install on this host.
url: '#list-xray-binary-versions-available-for-install-on-this-host'
- depth: 2
title: Check whether a newer 3x-ui release is available on GitHub.
url: '#check-whether-a-newer-3x-ui-release-is-available-on-github'
- depth: 2
title: 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.
url: '#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'
- depth: 2
title: Return the assembled Xray config thats currently running on this host.
url: '#return-the-assembled-xray-config-thats-currently-running-on-this-host'
- depth: 2
title: >-
Stream the SQLite database file as an attachment. Use as a manual
backup.
url: '#stream-the-sqlite-database-file-as-an-attachment-use-as-a-manual-backup'
title: 'Stream a full database backup as an attachment: the SQLite .db file on
SQLite panels, or a pg_dump custom-format archive (.dump) on PostgreSQL
panels. Use as a manual backup.'
url: '#stream-a-full-database-backup-as-an-attachment-the-sqlite-db-file-on-sqlite-panels-or-a-pg_dump-custom-format-archive-dump-on-postgresql-panels-use-as-a-manual-backup'
- depth: 2
title: >-
Stream a cross-engine migration file as an attachment: a .dump (SQL
title: 'Stream a cross-engine migration file as an attachment: a .dump (SQL
text) on SQLite, or a .db SQLite database built from the live data on
PostgreSQL.
url: >-
#stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
PostgreSQL.'
url: '#stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql'
- depth: 2
title: Generate a fresh UUID v4. Convenience helper for client IDs.
url: '#generate-a-fresh-uuid-v4-convenience-helper-for-client-ids'
- depth: 2
title: >-
Return this panel's own web TLS certificate and key file paths. The
title: Return this panel's own web TLS certificate and key file paths. The
central panel calls it on a node (via the node API token) so "Set Cert
from Panel" fills a node-assigned inbound with paths that exist on the
node.
url: >-
#return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
url: '#return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node'
- depth: 2
title: >-
Read-only summaries (guid, parentGuid, name, address, status, versions)
title: Read-only summaries (guid, parentGuid, name, address, status, versions)
of the nodes this panel manages. A parent panel calls it on a node (via
the node API token) to surface transitive sub-nodes in a chained
topology. Counts are computed by the parent, not returned here.
url: >-
#read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
url: '#read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here'
- depth: 2
title: Generate a new X25519 keypair for Reality.
url: '#generate-a-new-x25519-keypair-for-reality'
- depth: 2
title: >-
Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
title: Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
{privateKey, publicKey, seed}.
url: >-
#generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
url: '#generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed'
- depth: 2
title: >-
Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
{clientKey, serverKey}.
url: >-
#generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
title: Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns {clientKey,
serverKey}.
url: '#generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey'
- depth: 2
title: >-
Generate VLESS encryption auth options. Returns an auths array each with
title: Generate VLESS encryption auth options. Returns an auths array each with
id, label, encryption, and decryption fields.
url: >-
#generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
url: '#generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields'
- depth: 2
title: Stop the Xray binary. All proxies go offline immediately.
url: '#stop-the-xray-binary-all-proxies-go-offline-immediately'
- depth: 2
title: >-
Reload Xray with the current config. Typically required after structural
title: Reload Xray with the current config. Typically required after structural
inbound or routing changes.
url: >-
#reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
url: '#reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes'
- depth: 2
title: >-
Download and install the specified Xray version. Pass "latest" for the
title: Download and install the specified Xray version. Pass "latest" for the
newest release.
url: >-
#download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
url: '#download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release'
- depth: 2
title: >-
Self-update the panel to the latest version. The server restarts on
title: Self-update the panel to the latest version. The server restarts on
success.
url: >-
#self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
url: '#self-update-the-panel-to-the-latest-version-the-server-restarts-on-success'
- depth: 2
title: >-
Toggle the panel update channel between stable and the rolling
per-commit dev release. Only effective on dev builds.
url: >-
#toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
title: Toggle the panel update channel between stable and the rolling per-commit
dev release. Only effective on dev builds.
url: '#toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds'
- depth: 2
title: >-
Refresh the default GeoIP / GeoSite data files. Body can include a
title: Refresh the default GeoIP / GeoSite data files. Body can include a
fileName, or use the /:fileName variant.
url: >-
#refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
url: '#refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant'
- depth: 2
title: Refresh a single Geo file by filename (e.g. geoip.dat, geosite.dat).
url: '#refresh-a-single-geo-file-by-filename-eg-geoipdat-geositedat'
@@ -164,205 +136,187 @@ _openapi:
title: Return the last N lines of the Xray process log.
url: '#return-the-last-n-lines-of-the-xray-process-log'
- depth: 2
title: >-
Restore the panel DB from an uploaded SQLite file (multipart form, field
name "db"). The panel restarts after restore. Destructive.
url: >-
#restore-the-panel-db-from-an-uploaded-sqlite-file-multipart-form-field-name-db-the-panel-restarts-after-restore-destructive
title: Return live AmneziaWG peer activity (handshake, endpoint, transfer) plus
the panels own AmneziaWG event lines.
url: '#return-live-amneziawg-peer-activity-handshake-endpoint-transfer-plus-the-panels-own-amneziawg-event-lines'
- depth: 2
title: >-
Generate a new ECH (Encrypted Client Hello) keypair and config list for
title: Restore the panel DB from an uploaded backup (multipart form, field name
"db"). SQLite panels accept a SQLite database (.db) or a SQLite
migration dump (.dump); PostgreSQL panels accept a pg_dump archive
(.dump), a SQLite database (.db), or a SQLite migration dump. The panel
restarts after restore. Destructive.
url: '#restore-the-panel-db-from-an-uploaded-backup-multipart-form-field-name-db-sqlite-panels-accept-a-sqlite-database-db-or-a-sqlite-migration-dump-dump-postgresql-panels-accept-a-pg_dump-archive-dump-a-sqlite-database-db-or-a-sqlite-migration-dump-the-panel-restarts-after-restore-destructive'
- depth: 2
title: Generate a new ECH (Encrypted Client Hello) keypair and config list for
the given SNI.
url: >-
#generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
url: '#generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni'
- depth: 2
title: >-
Compute the hex SHA-256 of a certificate (DER) for pinning
title: Compute the hex SHA-256 of a certificate (DER) for pinning
(pinnedPeerCertSha256). Provide either a server file path or inline
PEM/DER content.
url: >-
#compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
url: '#compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content'
- depth: 2
title: >-
Run `xray tls ping` against a remote server and return its live
title: Run `xray tls ping` against a remote server and return its live
leaf-certificate SHA-256 hash(es) for pinning (pinnedPeerCertSha256).
url: >-
#run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
url: '#run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256'
- depth: 2
title: >-
Fetch the fully aggregated inbound_client_ips database table. Used by
title: Run a live TLS 1.3 probe against a candidate REALITY target and return a
feasibility verdict (TLS 1.3 + h2 + X25519 + trusted certificate) plus
the certificate SAN DNS names. A target on a private/loopback address is
reported with privateTarget=true and probed only when allowPrivate is
set.
url: '#run-a-live-tls-13-probe-against-a-candidate-reality-target-and-return-a-feasibility-verdict-tls-13--h2--x25519--trusted-certificate-plus-the-certificate-san-dns-names-a-target-on-a-privateloopback-address-is-reported-with-privatetargettrue-and-probed-only-when-allowprivate-is-set'
- depth: 2
title: Probe/discover REALITY targets and return each verdict ranked by
feasibility then latency. Each comma-separated token may be a domain
(validated with SNI), a bare IP, or a CIDR range (discovered without SNI
by reading the certificate domain). When empty, a built-in seed list is
probed.
url: '#probediscover-reality-targets-and-return-each-verdict-ranked-by-feasibility-then-latency-each-comma-separated-token-may-be-a-domain-validated-with-sni-a-bare-ip-or-a-cidr-range-discovered-without-sni-by-reading-the-certificate-domain-when-empty-a-built-in-seed-list-is-probed'
- depth: 2
title: Fetch the fully aggregated inbound_client_ips database table. Used by
nodes to sync recently active IPs across the cluster.
url: >-
#fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
url: '#fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster'
- depth: 2
title: >-
Submit a list of recently active IP timestamps. The panel merges them
title: Submit a list of recently active IP timestamps. The panel merges them
with the existing database to maintain a unified global IP-limit view.
url: >-
#submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
url: '#submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view'
structuredData:
headings:
- content: >-
Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
- content: Serve this API description as an OpenAPI 3 document — the same file
that powers the API Docs page. Requires a session or Bearer token like
the rest of /panel/api. Useful for generating clients or importing
into API tooling.
id: serve-this-api-description-as-an-openapi-3-document--the-same-file-that-powers-the-api-docs-page-requires-a-session-or-bearer-token-like-the-rest-of-panelapi-useful-for-generating-clients-or-importing-into-api-tooling
- content: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
seconds in the background.
id: >-
real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
- content: >-
Reports whether per-client IP limits can be enforced on this host. The
seconds in the background.'
id: real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
- content: Reports whether per-client IP limits can be enforced on this host. The
panel uses it to gate the "IP Limit" field, since enforcement depends
on Fail2ban being installed.
id: >-
reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: >-
Legacy: aggregated CPU history. Use /history/cpu/:bucket instead
same data with a uniform {t, v} shape.
id: >-
legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
- content: >-
Aggregated time-series for one metric. Returns an array of {t, v}
id: reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead —
same data with a uniform {t, v} shape.'
id: legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
- content: Aggregated time-series for one metric. Returns an array of {t, v}
samples covering the last ~6 hours.
id: >-
aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
- content: >-
Xray runtime metrics state — whether the xray config has a `metrics`
id: aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
- content: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
id: >-
xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
- content: >-
Time-series history for one Xray runtime metric over the last ~6
hours. Same {t, v} shape as /history/:metric/:bucket.
id: >-
time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
- content: >-
Latest snapshot from the Xray observatory — per-outbound latency,
id: xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
- content: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
id: time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
- content: Latest snapshot from the Xray observatory — per-outbound latency,
health status, and last-probe time. Only populated when the Xray
config has an observatory configured.
id: >-
latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
- content: >-
Time-series of observatory probe results for one outbound tag. Same
{t, v} shape as the other history endpoints.
id: >-
time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
id: latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
- content: Time-series of observatory probe results for one outbound tag. Same {t,
v} shape as the other history endpoints.
id: time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
- content: List Xray binary versions available for install on this host.
id: list-xray-binary-versions-available-for-install-on-this-host
- content: Check whether a newer 3x-ui release is available on GitHub.
id: check-whether-a-newer-3x-ui-release-is-available-on-github
- content: >-
Return the assembled Xray config thats currently running on this
host.
- content: 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.
id: 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
- content: Return the assembled Xray config thats currently running on this host.
id: return-the-assembled-xray-config-thats-currently-running-on-this-host
- content: >-
Stream the SQLite database file as an attachment. Use as a manual
backup.
id: >-
stream-the-sqlite-database-file-as-an-attachment-use-as-a-manual-backup
- content: >-
Stream a cross-engine migration file as an attachment: a .dump (SQL
- content: 'Stream a full database backup as an attachment: the SQLite .db file on
SQLite panels, or a pg_dump custom-format archive (.dump) on
PostgreSQL panels. Use as a manual backup.'
id: stream-a-full-database-backup-as-an-attachment-the-sqlite-db-file-on-sqlite-panels-or-a-pg_dump-custom-format-archive-dump-on-postgresql-panels-use-as-a-manual-backup
- content: 'Stream a cross-engine migration file as an attachment: a .dump (SQL
text) on SQLite, or a .db SQLite database built from the live data on
PostgreSQL.
id: >-
stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
PostgreSQL.'
id: stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
- content: Generate a fresh UUID v4. Convenience helper for client IDs.
id: generate-a-fresh-uuid-v4-convenience-helper-for-client-ids
- content: >-
Return this panel's own web TLS certificate and key file paths. The
- content: Return this panel's own web TLS certificate and key file paths. The
central panel calls it on a node (via the node API token) so "Set Cert
from Panel" fills a node-assigned inbound with paths that exist on the
node.
id: >-
return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
- content: >-
Read-only summaries (guid, parentGuid, name, address, status,
versions) of the nodes this panel manages. A parent panel calls it on
a node (via the node API token) to surface transitive sub-nodes in a
chained topology. Counts are computed by the parent, not returned
here.
id: >-
read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
id: return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
- content: Read-only summaries (guid, parentGuid, name, address, status, versions)
of the nodes this panel manages. A parent panel calls it on a node
(via the node API token) to surface transitive sub-nodes in a chained
topology. Counts are computed by the parent, not returned here.
id: read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
- content: Generate a new X25519 keypair for Reality.
id: generate-a-new-x25519-keypair-for-reality
- content: >-
Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
- content: Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
{privateKey, publicKey, seed}.
id: >-
generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
- content: >-
Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
id: generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
- content: Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
{clientKey, serverKey}.
id: >-
generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
- content: >-
Generate VLESS encryption auth options. Returns an auths array each
id: generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
- content: Generate VLESS encryption auth options. Returns an auths array each
with id, label, encryption, and decryption fields.
id: >-
generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
id: generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
- content: Stop the Xray binary. All proxies go offline immediately.
id: stop-the-xray-binary-all-proxies-go-offline-immediately
- content: >-
Reload Xray with the current config. Typically required after
- content: Reload Xray with the current config. Typically required after
structural inbound or routing changes.
id: >-
reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
- content: >-
Download and install the specified Xray version. Pass "latest" for the
id: reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
- content: Download and install the specified Xray version. Pass "latest" for the
newest release.
id: >-
download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
- content: >-
Self-update the panel to the latest version. The server restarts on
id: download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
- content: Self-update the panel to the latest version. The server restarts on
success.
id: >-
self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
- content: >-
Toggle the panel update channel between stable and the rolling
id: self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
- content: Toggle the panel update channel between stable and the rolling
per-commit dev release. Only effective on dev builds.
id: >-
toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
- content: >-
Refresh the default GeoIP / GeoSite data files. Body can include a
id: toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
- content: Refresh the default GeoIP / GeoSite data files. Body can include a
fileName, or use the /:fileName variant.
id: >-
refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
id: refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
- content: Refresh a single Geo file by filename (e.g. geoip.dat, geosite.dat).
id: refresh-a-single-geo-file-by-filename-eg-geoipdat-geositedat
- content: Return the last N lines of the panels own log.
id: return-the-last-n-lines-of-the-panels-own-log
- content: Return the last N lines of the Xray process log.
id: return-the-last-n-lines-of-the-xray-process-log
- content: >-
Restore the panel DB from an uploaded SQLite file (multipart form,
field name "db"). The panel restarts after restore. Destructive.
id: >-
restore-the-panel-db-from-an-uploaded-sqlite-file-multipart-form-field-name-db-the-panel-restarts-after-restore-destructive
- content: >-
Generate a new ECH (Encrypted Client Hello) keypair and config list
for the given SNI.
id: >-
generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
- content: >-
Compute the hex SHA-256 of a certificate (DER) for pinning
- content: Return live AmneziaWG peer activity (handshake, endpoint, transfer)
plus the panels own AmneziaWG event lines.
id: return-live-amneziawg-peer-activity-handshake-endpoint-transfer-plus-the-panels-own-amneziawg-event-lines
- content: Restore the panel DB from an uploaded backup (multipart form, field
name "db"). SQLite panels accept a SQLite database (.db) or a SQLite
migration dump (.dump); PostgreSQL panels accept a pg_dump archive
(.dump), a SQLite database (.db), or a SQLite migration dump. The
panel restarts after restore. Destructive.
id: restore-the-panel-db-from-an-uploaded-backup-multipart-form-field-name-db-sqlite-panels-accept-a-sqlite-database-db-or-a-sqlite-migration-dump-dump-postgresql-panels-accept-a-pg_dump-archive-dump-a-sqlite-database-db-or-a-sqlite-migration-dump-the-panel-restarts-after-restore-destructive
- content: Generate a new ECH (Encrypted Client Hello) keypair and config list for
the given SNI.
id: generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
- content: Compute the hex SHA-256 of a certificate (DER) for pinning
(pinnedPeerCertSha256). Provide either a server file path or inline
PEM/DER content.
id: >-
compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
- content: >-
Run `xray tls ping` against a remote server and return its live
id: compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
- content: Run `xray tls ping` against a remote server and return its live
leaf-certificate SHA-256 hash(es) for pinning (pinnedPeerCertSha256).
id: >-
run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
- content: >-
Fetch the fully aggregated inbound_client_ips database table. Used by
id: run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
- content: Run a live TLS 1.3 probe against a candidate REALITY target and return
a feasibility verdict (TLS 1.3 + h2 + X25519 + trusted certificate)
plus the certificate SAN DNS names. A target on a private/loopback
address is reported with privateTarget=true and probed only when
allowPrivate is set.
id: run-a-live-tls-13-probe-against-a-candidate-reality-target-and-return-a-feasibility-verdict-tls-13--h2--x25519--trusted-certificate-plus-the-certificate-san-dns-names-a-target-on-a-privateloopback-address-is-reported-with-privatetargettrue-and-probed-only-when-allowprivate-is-set
- content: Probe/discover REALITY targets and return each verdict ranked by
feasibility then latency. Each comma-separated token may be a domain
(validated with SNI), a bare IP, or a CIDR range (discovered without
SNI by reading the certificate domain). When empty, a built-in seed
list is probed.
id: probediscover-reality-targets-and-return-each-verdict-ranked-by-feasibility-then-latency-each-comma-separated-token-may-be-a-domain-validated-with-sni-a-bare-ip-or-a-cidr-range-discovered-without-sni-by-reading-the-certificate-domain-when-empty-a-built-in-seed-list-is-probed
- content: Fetch the fully aggregated inbound_client_ips database table. Used by
nodes to sync recently active IPs across the cluster.
id: >-
fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
- content: >-
Submit a list of recently active IP timestamps. The panel merges them
id: fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
- content: Submit a list of recently active IP timestamps. The panel merges them
with the existing database to maintain a unified global IP-limit view.
id: >-
submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
id: submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
contents: []
---
@@ -375,7 +329,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/openapi.json","method":"get"},{"path":"/panel/api/server/status","method":"get"},{"path":"/panel/api/server/fail2banStatus","method":"get"},{"path":"/panel/api/server/cpuHistory/{bucket}","method":"get"},{"path":"/panel/api/server/history/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayMetricsState","method":"get"},{"path":"/panel/api/server/xrayMetricsHistory/{metric}/{bucket}","method":"get"},{"path":"/panel/api/server/xrayObservatory","method":"get"},{"path":"/panel/api/server/xrayObservatoryHistory/{tag}/{bucket}","method":"get"},{"path":"/panel/api/server/getXrayVersion","method":"get"},{"path":"/panel/api/server/getPanelUpdateInfo","method":"get"},{"path":"/panel/api/server/getUpdateStatus","method":"get"},{"path":"/panel/api/server/getConfigJson","method":"get"},{"path":"/panel/api/server/getDb","method":"get"},{"path":"/panel/api/server/getMigration","method":"get"},{"path":"/panel/api/server/getNewUUID","method":"get"},{"path":"/panel/api/server/getWebCertFiles","method":"get"},{"path":"/panel/api/server/descendants","method":"get"},{"path":"/panel/api/server/getNewX25519Cert","method":"get"},{"path":"/panel/api/server/getNewmldsa65","method":"get"},{"path":"/panel/api/server/getNewmlkem768","method":"get"},{"path":"/panel/api/server/getNewVlessEnc","method":"get"},{"path":"/panel/api/server/stopXrayService","method":"post"},{"path":"/panel/api/server/restartXrayService","method":"post"},{"path":"/panel/api/server/installXray/{version}","method":"post"},{"path":"/panel/api/server/updatePanel","method":"post"},{"path":"/panel/api/server/setUpdateChannel","method":"post"},{"path":"/panel/api/server/updateGeofile","method":"post"},{"path":"/panel/api/server/updateGeofile/{fileName}","method":"post"},{"path":"/panel/api/server/logs/{count}","method":"post"},{"path":"/panel/api/server/xraylogs/{count}","method":"post"},{"path":"/panel/api/server/amneziawglogs/{count}","method":"post"},{"path":"/panel/api/server/importDB","method":"post"},{"path":"/panel/api/server/getNewEchCert","method":"post"},{"path":"/panel/api/server/getCertHash","method":"post"},{"path":"/panel/api/server/getRemoteCertHash","method":"post"},{"path":"/panel/api/server/scanRealityTarget","method":"post"},{"path":"/panel/api/server/scanRealityTargets","method":"post"},{"path":"/panel/api/server/clientIps","method":"get"},{"path":"/panel/api/server/clientIps","method":"post"}]} showTitle />
</>
);
}
+56 -71
View File
@@ -1,7 +1,6 @@
---
title: Settings
description: >-
Panel configuration and user credentials. All endpoints live under
description: Panel configuration and user credentials. All endpoints live under
/panel/api/setting and require a logged-in session or Bearer token.
full: true
_openapi:
@@ -9,101 +8,87 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.
url: >-
#return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
title: 'Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.'
url: '#return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits'
- depth: 2
title: >-
Return the computed default settings based on the request host. Useful
to preview what a fresh install would use.
url: >-
#return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
title: Return the computed default settings based on the request host. Useful to
preview what a fresh install would use.
url: '#return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use'
- depth: 2
title: >-
Persist every setting at once. The body mirrors the shape returned by
title: Return the shipped (factory) default value per browser-safe setting key,
so clients can tell a stored value apart from the default it would fall
back to. Per-install material (secret, panelGuid, mTLS keys) and
credential fields are never included.
url: '#return-the-shipped-factory-default-value-per-browser-safe-setting-key-so-clients-can-tell-a-stored-value-apart-from-the-default-it-would-fall-back-to-per-install-material-secret-panelguid-mtls-keys-and-credential-fields-are-never-included'
- depth: 2
title: Persist every setting at once. The body mirrors the shape returned by
/all. Invalid values (bad ports, missing cert pairs, etc.) are rejected
before write.
url: >-
#persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
url: '#persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write'
- depth: 2
title: >-
Change the panel admin username and password. Requires the current
title: Validate any regular expression with the backend Go RE2 compiler without
saving it.
url: '#validate-any-regular-expression-with-the-backend-go-re2-compiler-without-saving-it'
- depth: 2
title: Change the panel admin username and password. Requires the current
credentials for verification. The session is refreshed with the new
values on success.
url: >-
#change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
url: '#change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success'
- depth: 2
title: >-
Restart the entire 3x-ui process after a 3-second grace period. The
title: Restart the entire 3x-ui process after a 3-second grace period. The
connection drops immediately; the panel comes back online ~5-10 seconds
later.
url: >-
#restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
url: '#restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later'
- depth: 2
title: >-
Test SMTP connection with stage-by-stage reporting (connect, auth,
send). Returns structured result with stage and message.
url: >-
#test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
title: Test SMTP connection with stage-by-stage reporting (connect, auth, send).
Returns structured result with stage and message.
url: '#test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message'
- depth: 2
title: >-
Test Telegram bot connection by sending a test message to the configured
title: Test Telegram bot connection by sending a test message to the configured
chat.
url: >-
#test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
url: '#test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat'
- depth: 2
title: >-
Return the built-in default Xray JSON config template that ships with
title: Return the built-in default Xray JSON config template that ships with
this panel version.
url: >-
#return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
url: '#return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version'
structuredData:
headings:
- content: >-
Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.
id: >-
return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
- content: >-
Return the computed default settings based on the request host. Useful
- content: 'Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.'
id: return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
- content: Return the computed default settings based on the request host. Useful
to preview what a fresh install would use.
id: >-
return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
- content: >-
Persist every setting at once. The body mirrors the shape returned by
id: return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
- content: Return the shipped (factory) default value per browser-safe setting
key, so clients can tell a stored value apart from the default it
would fall back to. Per-install material (secret, panelGuid, mTLS
keys) and credential fields are never included.
id: return-the-shipped-factory-default-value-per-browser-safe-setting-key-so-clients-can-tell-a-stored-value-apart-from-the-default-it-would-fall-back-to-per-install-material-secret-panelguid-mtls-keys-and-credential-fields-are-never-included
- content: Persist every setting at once. The body mirrors the shape returned by
/all. Invalid values (bad ports, missing cert pairs, etc.) are
rejected before write.
id: >-
persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
- content: >-
Change the panel admin username and password. Requires the current
id: persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
- content: Validate any regular expression with the backend Go RE2 compiler
without saving it.
id: validate-any-regular-expression-with-the-backend-go-re2-compiler-without-saving-it
- content: Change the panel admin username and password. Requires the current
credentials for verification. The session is refreshed with the new
values on success.
id: >-
change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
- content: >-
Restart the entire 3x-ui process after a 3-second grace period. The
id: change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
- content: Restart the entire 3x-ui process after a 3-second grace period. The
connection drops immediately; the panel comes back online ~5-10
seconds later.
id: >-
restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
- content: >-
Test SMTP connection with stage-by-stage reporting (connect, auth,
id: restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
- content: Test SMTP connection with stage-by-stage reporting (connect, auth,
send). Returns structured result with stage and message.
id: >-
test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
- content: >-
Test Telegram bot connection by sending a test message to the
id: test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
- content: Test Telegram bot connection by sending a test message to the
configured chat.
id: >-
test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
- content: >-
Return the built-in default Xray JSON config template that ships with
id: test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
- content: Return the built-in default Xray JSON config template that ships with
this panel version.
id: >-
return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
contents: []
---
@@ -116,7 +101,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/factoryDefaults","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/validateRegex","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
</>
);
}
@@ -0,0 +1,60 @@
---
title: Subscription Balancers
description: 'Client-side balancers for the JSON subscription: each enabled
balancer is emitted as one extra config document whose members are the proxy
outbounds of the selected inbounds (routing.balancers + burstObservatory).
Managed in Settings → Sub Balancers.'
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: List all subscription balancers in sort order (sort_order asc, id asc).
url: '#list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc'
- depth: 2
title: Create a subscription balancer. It appears in the JSON subscription of
every client that sits on at least one selected inbound.
url: '#create-a-subscription-balancer-it-appears-in-the-json-subscription-of-every-client-that-sits-on-at-least-one-selected-inbound'
- depth: 2
title: Update a balancer by id. Accepts the same form fields as create (full-row
update, including the enabled toggle).
url: '#update-a-balancer-by-id-accepts-the-same-form-fields-as-create-full-row-update-including-the-enabled-toggle'
- depth: 2
title: Delete a balancer by id.
url: '#delete-a-balancer-by-id'
- depth: 2
title: Delete a balancer by id (POST alias of DELETE for clients that cannot
send DELETE).
url: '#delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete'
structuredData:
headings:
- content: List all subscription balancers in sort order (sort_order asc, id asc).
id: list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc
- content: Create a subscription balancer. It appears in the JSON subscription of
every client that sits on at least one selected inbound.
id: create-a-subscription-balancer-it-appears-in-the-json-subscription-of-every-client-that-sits-on-at-least-one-selected-inbound
- content: Update a balancer by id. Accepts the same form fields as create
(full-row update, including the enabled toggle).
id: update-a-balancer-by-id-accepts-the-same-form-fields-as-create-full-row-update-including-the-enabled-toggle
- content: Delete a balancer by id.
id: delete-a-balancer-by-id
- content: Delete a balancer by id (POST alias of DELETE for clients that cannot
send DELETE).
id: delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete
contents: []
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
export default function Layout(props) {
const { APIPage, OpenAPIPage } = props.components ?? {};
// "APIPage" is the old name from v10, this allows both for backward compatibility
const Comp = OpenAPIPage ?? APIPage;
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/sub-balancers","method":"get"},{"path":"/panel/api/sub-balancers","method":"post"},{"path":"/panel/api/sub-balancers/{id}","method":"post"},{"path":"/panel/api/sub-balancers/{id}","method":"delete"},{"path":"/panel/api/sub-balancers/{id}/del","method":"post"}]} showTitle />
</>
);
}
@@ -1,59 +1,48 @@
---
title: Subscription Server
description: >-
A separate HTTP/HTTPS server that serves proxy subscription links (standard,
JSON, and Clash) to clients. The server listens on its own port (default
10882) and is configured in Settings → Subscription. Paths are configurable;
defaults are shown below. All subscription endpoints set response headers for
client apps to read traffic/expiry info.
description: A separate HTTP/HTTPS server that serves proxy subscription links
(standard, JSON, and Clash) to clients. The server listens on its own port
(default 10882) and is configured in Settings → Subscription. Paths are
configurable; defaults are shown below. All subscription endpoints set
response headers for client apps to read traffic/expiry info.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return base64-encoded subscription links for all enabled clients
title: 'Return base64-encoded subscription links for all enabled clients
matching the subscription ID. When the request has an Accept: text/html
header or ?html=1, renders a styled info page instead. Default path:
/sub/:subid.
url: >-
#return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-default-path-subsubid
header or ?html=1, renders a styled info page instead. With
?format=info, returns the page view-model as JSON (traffic, expiry,
online status; no links) for live polling. Default path: /sub/:subid.'
url: '#return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-with-formatinfo-returns-the-page-view-model-as-json-traffic-expiry-online-status-no-links-for-live-polling-default-path-subsubid'
- depth: 2
title: >-
Return subscription as a JSON array of proxy configs (one per enabled
title: 'Return subscription as a JSON array of proxy configs (one per enabled
client). Only when JSON subscription is enabled in settings. Default
path: /json/:subid.
url: >-
#return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
path: /json/:subid.'
url: '#return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid'
- depth: 2
title: >-
Return subscription as a Clash/Mihomo-compatible YAML config, including
title: 'Return subscription as a Clash/Mihomo-compatible YAML config, including
configured global Clash routing rules. Only when Clash subscription is
enabled in settings. Default path: /clash/:subid.
url: >-
#return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
enabled in settings. Default path: /clash/:subid.'
url: '#return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid'
structuredData:
headings:
- content: >-
Return base64-encoded subscription links for all enabled clients
- content: 'Return base64-encoded subscription links for all enabled clients
matching the subscription ID. When the request has an Accept:
text/html header or ?html=1, renders a styled info page instead.
Default path: /sub/:subid.
id: >-
return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-default-path-subsubid
- content: >-
Return subscription as a JSON array of proxy configs (one per enabled
text/html header or ?html=1, renders a styled info page instead. With
?format=info, returns the page view-model as JSON (traffic, expiry,
online status; no links) for live polling. Default path: /sub/:subid.'
id: return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-with-formatinfo-returns-the-page-view-model-as-json-traffic-expiry-online-status-no-links-for-live-polling-default-path-subsubid
- content: 'Return subscription as a JSON array of proxy configs (one per enabled
client). Only when JSON subscription is enabled in settings. Default
path: /json/:subid.
id: >-
return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
- content: >-
Return subscription as a Clash/Mihomo-compatible YAML config,
path: /json/:subid.'
id: return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
- content: 'Return subscription as a Clash/Mihomo-compatible YAML config,
including configured global Clash routing rules. Only when Clash
subscription is enabled in settings. Default path: /clash/:subid.
id: >-
return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
subscription is enabled in settings. Default path: /clash/:subid.'
id: return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
contents: []
---
@@ -1,7 +1,6 @@
---
title: WebSocket
description: >-
Real-time status updates via WebSocket. Connect once at
description: Real-time status updates via WebSocket. Connect once at
<code>ws://<panel>/ws</code> to receive a stream of JSON messages without
polling. Requires an authenticated session cookie (Bearer token auth is not
supported). Each message has a <code>type</code> field that identifies the
@@ -12,22 +11,18 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Upgrade an HTTP connection to a WebSocket. Requires an authenticated
title: Upgrade an HTTP connection to a WebSocket. Requires an authenticated
session cookie (Bearer token auth is not supported here). Returns 101
Switching Protocols on success. The server then pushes JSON messages
described below.
url: >-
#upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
url: '#upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below'
structuredData:
headings:
- content: >-
Upgrade an HTTP connection to a WebSocket. Requires an authenticated
- content: Upgrade an HTTP connection to a WebSocket. Requires an authenticated
session cookie (Bearer token auth is not supported here). Returns 101
Switching Protocols on success. The server then pushes JSON messages
described below.
id: >-
upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
id: upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
contents: []
---
@@ -1,244 +1,210 @@
---
title: Xray Settings
description: >-
Xray configuration template, outbound management, Warp/Nord integration, and
config testing. All endpoints under /panel/api/xray.
description: Xray configuration template, outbound management, Warp/Nord/PIA
integration, and config testing. All endpoints under /panel/api/xray.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return the Xray config template (JSON string), available inbound tags,
title: Return the Xray config template (JSON string), available inbound tags,
client reverse tags, and the configured outbound test URL in one
response.
url: >-
#return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
url: '#return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response'
- depth: 2
title: >-
Return the built-in default Xray config shipped with the panel
(identical to /panel/api/setting/getDefaultJsonConfig).
url: >-
#return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
title: Return the built-in default Xray config shipped with the panel (identical
to /panel/api/setting/getDefaultJsonConfig).
url: '#return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig'
- depth: 2
title: >-
Return traffic statistics for every outbound. Each outbound shows
title: Return traffic statistics for every outbound. Each outbound shows
up/down/total counters.
url: >-
#return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
url: '#return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters'
- depth: 2
title: >-
Return the most recent Xray process stdout/stderr output. Useful to
check for startup errors or runtime warnings.
url: >-
#return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
title: Return the most recent Xray process stdout/stderr output. Useful to check
for startup errors or runtime warnings.
url: '#return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings'
- depth: 2
title: >-
Save the Xray JSON config template and optionally the outbound test URL.
title: Save the Xray JSON config template and optionally the outbound test URL.
Both are sent as form fields.
url: >-
#save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
url: '#save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields'
- depth: 2
title: >-
Manage Cloudflare Warp integration. The action parameter selects the
title: Manage Cloudflare Warp integration. The action parameter selects the
operation.
url: >-
#manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
url: '#manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Manage NordVPN integration. The action parameter selects the operation.
url: '#manage-nordvpn-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Manage PIA WireGuard integration. The action parameter selects the
operation.
url: '#manage-pia-wireguard-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Reset traffic counters for a specific outbound by tag.
url: '#reset-traffic-counters-for-a-specific-outbound-by-tag'
- depth: 2
title: >-
Test an outbound configuration. Sends the outbound JSON (required),
title: Test an outbound configuration. Sends the outbound JSON (required),
optionally all outbounds (to resolve sockopt.dialerProxy dependencies),
and a mode flag.
url: >-
#test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
url: '#test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag'
- depth: 2
title: >-
Test a batch of outbounds (max 50) through one shared temp xray
instance. Returns an array of results in input order, each with the
outbound tag, delay, HTTP status and a connect/TLS/TTFB timing
breakdown.
url: >-
#test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
title: Test a batch of outbounds (max 50) through one shared temp xray instance.
Returns an array of results in input order, each with the outbound tag,
delay, HTTP status and a connect/TLS/TTFB timing breakdown.
url: '#test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown'
- depth: 2
title: >-
Live state of routing balancers in the running core
title: 'Live state of routing balancers in the running core
(RoutingService.GetBalancerInfo): current override and the targets the
strategy prefers. Returns a map keyed by balancer tag.
url: >-
#live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
strategy prefers. Returns a map keyed by balancer tag.'
url: '#live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag'
- depth: 2
title: >-
Force a balancer in the running core to always pick one outbound
title: Force a balancer in the running core to always pick one outbound
(RoutingService.OverrideBalancerTarget). Applied live without a restart;
cleared automatically when Xray restarts.
url: >-
#force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
url: '#force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts'
- depth: 2
title: >-
Ask the running core which outbound its router would pick for a
synthetic connection (RoutingService.TestRoute). No traffic is sent.
url: >-
#ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
title: Ask the running core which outbound its router would pick for a synthetic
connection (RoutingService.TestRoute). No traffic is sent.
url: '#ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent'
- depth: 2
title: >-
List all outbound subscriptions (remote URLs that supply additional
title: List the geo databases (.dat files) in the Xray asset folder, with the
layout detected from their contents, size, modification time and
category count. A database that fails to parse is still listed, with the
reason in "error".
url: '#list-the-geo-databases-dat-files-in-the-xray-asset-folder-with-the-layout-detected-from-their-contents-size-modification-time-and-category-count-a-database-that-fails-to-parse-is-still-listed-with-the-reason-in-error'
- depth: 2
title: One page of a database's categories, each with its entry count and the
attributes its domains carry (e.g. "ads", "cn").
url: '#one-page-of-a-databases-categories-each-with-its-entry-count-and-the-attributes-its-domains-carry-eg-ads-cn'
- depth: 2
title: One page of the rules inside a category — domain rules typed as
domain/full/keyword/regexp for geosite databases, CIDRs for geoip ones.
url: '#one-page-of-the-rules-inside-a-category--domain-rules-typed-as-domainfullkeywordregexp-for-geosite-databases-cidrs-for-geoip-ones'
- depth: 2
title: 'Check routing tokens against the databases on disk and return only the
ones that do not resolve. Plain domains and CIDRs are ignored. Each
issue carries a reason: syntax, fileMissing or categoryMissing.'
url: '#check-routing-tokens-against-the-databases-on-disk-and-return-only-the-ones-that-do-not-resolve-plain-domains-and-cidrs-are-ignored-each-issue-carries-a-reason-syntax-filemissing-or-categorymissing'
- depth: 2
title: List all outbound subscriptions (remote URLs that supply additional
outbounds), newest first.
url: >-
#list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
url: '#list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first'
- depth: 2
title: >-
Create an outbound subscription. The URL is fetched, parsed into
title: Create an outbound subscription. The URL is fetched, parsed into
outbounds with stable tags, and merged additively into the running Xray
config.
url: >-
#create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
url: '#create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config'
- depth: 2
title: >-
Update an existing outbound subscription by id. Accepts the same form
title: Update an existing outbound subscription by id. Accepts the same form
fields as create.
url: >-
#update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
url: '#update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create'
- depth: 2
title: Delete an outbound subscription by id.
url: '#delete-an-outbound-subscription-by-id'
- depth: 2
title: >-
Delete an outbound subscription by id (POST alias of DELETE for
axios-friendly clients).
url: >-
#delete-an-outbound-subscription-by-id-post-alias-of-delete-for-axios-friendly-clients
title: Delete an outbound subscription by id (POST alias of DELETE for clients
that cannot send DELETE).
url: '#delete-an-outbound-subscription-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete'
- depth: 2
title: >-
Force an immediate re-fetch of the subscription and return the parsed
title: Force an immediate re-fetch of the subscription and return the parsed
outbounds. Signals Xray to reload.
url: >-
#force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
url: '#force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload'
- depth: 2
title: >-
Reorder a subscription one step up or down in priority (controls its
title: Reorder a subscription one step up or down in priority (controls its
position in the merged outbounds).
url: >-
#reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
url: '#reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds'
- depth: 2
title: >-
Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.
url: >-
#preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
title: 'Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.'
url: '#preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything'
structuredData:
headings:
- content: >-
Return the Xray config template (JSON string), available inbound tags,
- content: Return the Xray config template (JSON string), available inbound tags,
client reverse tags, and the configured outbound test URL in one
response.
id: >-
return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
- content: >-
Return the built-in default Xray config shipped with the panel
id: return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
- content: Return the built-in default Xray config shipped with the panel
(identical to /panel/api/setting/getDefaultJsonConfig).
id: >-
return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
- content: >-
Return traffic statistics for every outbound. Each outbound shows
id: return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
- content: Return traffic statistics for every outbound. Each outbound shows
up/down/total counters.
id: >-
return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
- content: >-
Return the most recent Xray process stdout/stderr output. Useful to
id: return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
- content: Return the most recent Xray process stdout/stderr output. Useful to
check for startup errors or runtime warnings.
id: >-
return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
- content: >-
Save the Xray JSON config template and optionally the outbound test
id: return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
- content: Save the Xray JSON config template and optionally the outbound test
URL. Both are sent as form fields.
id: >-
save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
- content: >-
Manage Cloudflare Warp integration. The action parameter selects the
operation.
id: >-
manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
- content: >-
Manage NordVPN integration. The action parameter selects the
id: save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
- content: Manage Cloudflare Warp integration. The action parameter selects the
operation.
id: manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
- content: Manage NordVPN integration. The action parameter selects the operation.
id: manage-nordvpn-integration-the-action-parameter-selects-the-operation
- content: Manage PIA WireGuard integration. The action parameter selects the
operation.
id: manage-pia-wireguard-integration-the-action-parameter-selects-the-operation
- content: Reset traffic counters for a specific outbound by tag.
id: reset-traffic-counters-for-a-specific-outbound-by-tag
- content: >-
Test an outbound configuration. Sends the outbound JSON (required),
- content: Test an outbound configuration. Sends the outbound JSON (required),
optionally all outbounds (to resolve sockopt.dialerProxy
dependencies), and a mode flag.
id: >-
test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
- content: >-
Test a batch of outbounds (max 50) through one shared temp xray
id: test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
- content: Test a batch of outbounds (max 50) through one shared temp xray
instance. Returns an array of results in input order, each with the
outbound tag, delay, HTTP status and a connect/TLS/TTFB timing
breakdown.
id: >-
test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
- content: >-
Live state of routing balancers in the running core
id: test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
- content: 'Live state of routing balancers in the running core
(RoutingService.GetBalancerInfo): current override and the targets the
strategy prefers. Returns a map keyed by balancer tag.
id: >-
live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
- content: >-
Force a balancer in the running core to always pick one outbound
strategy prefers. Returns a map keyed by balancer tag.'
id: live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
- content: Force a balancer in the running core to always pick one outbound
(RoutingService.OverrideBalancerTarget). Applied live without a
restart; cleared automatically when Xray restarts.
id: >-
force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
- content: >-
Ask the running core which outbound its router would pick for a
id: force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
- content: Ask the running core which outbound its router would pick for a
synthetic connection (RoutingService.TestRoute). No traffic is sent.
id: >-
ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
- content: >-
List all outbound subscriptions (remote URLs that supply additional
id: ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
- content: List the geo databases (.dat files) in the Xray asset folder, with the
layout detected from their contents, size, modification time and
category count. A database that fails to parse is still listed, with
the reason in "error".
id: list-the-geo-databases-dat-files-in-the-xray-asset-folder-with-the-layout-detected-from-their-contents-size-modification-time-and-category-count-a-database-that-fails-to-parse-is-still-listed-with-the-reason-in-error
- content: One page of a database's categories, each with its entry count and the
attributes its domains carry (e.g. "ads", "cn").
id: one-page-of-a-databases-categories-each-with-its-entry-count-and-the-attributes-its-domains-carry-eg-ads-cn
- content: One page of the rules inside a category — domain rules typed as
domain/full/keyword/regexp for geosite databases, CIDRs for geoip
ones.
id: one-page-of-the-rules-inside-a-category--domain-rules-typed-as-domainfullkeywordregexp-for-geosite-databases-cidrs-for-geoip-ones
- content: 'Check routing tokens against the databases on disk and return only the
ones that do not resolve. Plain domains and CIDRs are ignored. Each
issue carries a reason: syntax, fileMissing or categoryMissing.'
id: check-routing-tokens-against-the-databases-on-disk-and-return-only-the-ones-that-do-not-resolve-plain-domains-and-cidrs-are-ignored-each-issue-carries-a-reason-syntax-filemissing-or-categorymissing
- content: List all outbound subscriptions (remote URLs that supply additional
outbounds), newest first.
id: >-
list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
- content: >-
Create an outbound subscription. The URL is fetched, parsed into
id: list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
- content: Create an outbound subscription. The URL is fetched, parsed into
outbounds with stable tags, and merged additively into the running
Xray config.
id: >-
create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
- content: >-
Update an existing outbound subscription by id. Accepts the same form
id: create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
- content: Update an existing outbound subscription by id. Accepts the same form
fields as create.
id: >-
update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
id: update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
- content: Delete an outbound subscription by id.
id: delete-an-outbound-subscription-by-id
- content: >-
Delete an outbound subscription by id (POST alias of DELETE for
axios-friendly clients).
id: >-
delete-an-outbound-subscription-by-id-post-alias-of-delete-for-axios-friendly-clients
- content: >-
Force an immediate re-fetch of the subscription and return the parsed
- content: Delete an outbound subscription by id (POST alias of DELETE for clients
that cannot send DELETE).
id: delete-an-outbound-subscription-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete
- content: Force an immediate re-fetch of the subscription and return the parsed
outbounds. Signals Xray to reload.
id: >-
force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
- content: >-
Reorder a subscription one step up or down in priority (controls its
id: force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
- content: Reorder a subscription one step up or down in priority (controls its
position in the merged outbounds).
id: >-
reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
- content: >-
Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.
id: >-
preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
id: reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
- content: 'Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.'
id: preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
contents: []
---
@@ -251,7 +217,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/xray/","method":"post"},{"path":"/panel/api/xray/getDefaultJsonConfig","method":"get"},{"path":"/panel/api/xray/getOutboundsTraffic","method":"get"},{"path":"/panel/api/xray/getXrayResult","method":"get"},{"path":"/panel/api/xray/update","method":"post"},{"path":"/panel/api/xray/warp/{action}","method":"post"},{"path":"/panel/api/xray/nord/{action}","method":"post"},{"path":"/panel/api/xray/resetOutboundsTraffic","method":"post"},{"path":"/panel/api/xray/testOutbound","method":"post"},{"path":"/panel/api/xray/testOutbounds","method":"post"},{"path":"/panel/api/xray/balancerStatus","method":"post"},{"path":"/panel/api/xray/balancerOverride","method":"post"},{"path":"/panel/api/xray/routeTest","method":"post"},{"path":"/panel/api/xray/outbound-subs","method":"get"},{"path":"/panel/api/xray/outbound-subs","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}","method":"delete"},{"path":"/panel/api/xray/outbound-subs/{id}/del","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}/refresh","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}/move","method":"post"},{"path":"/panel/api/xray/outbound-subs/parse","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/xray/","method":"post"},{"path":"/panel/api/xray/getDefaultJsonConfig","method":"get"},{"path":"/panel/api/xray/getOutboundsTraffic","method":"get"},{"path":"/panel/api/xray/getXrayResult","method":"get"},{"path":"/panel/api/xray/update","method":"post"},{"path":"/panel/api/xray/warp/{action}","method":"post"},{"path":"/panel/api/xray/nord/{action}","method":"post"},{"path":"/panel/api/xray/pia/{action}","method":"post"},{"path":"/panel/api/xray/resetOutboundsTraffic","method":"post"},{"path":"/panel/api/xray/testOutbound","method":"post"},{"path":"/panel/api/xray/testOutbounds","method":"post"},{"path":"/panel/api/xray/balancerStatus","method":"post"},{"path":"/panel/api/xray/balancerOverride","method":"post"},{"path":"/panel/api/xray/routeTest","method":"post"},{"path":"/panel/api/xray/geodata/files","method":"get"},{"path":"/panel/api/xray/geodata/categories","method":"get"},{"path":"/panel/api/xray/geodata/entries","method":"get"},{"path":"/panel/api/xray/geodata/validate","method":"post"},{"path":"/panel/api/xray/outbound-subs","method":"get"},{"path":"/panel/api/xray/outbound-subs","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}","method":"delete"},{"path":"/panel/api/xray/outbound-subs/{id}/del","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}/refresh","method":"post"},{"path":"/panel/api/xray/outbound-subs/{id}/move","method":"post"},{"path":"/panel/api/xray/outbound-subs/parse","method":"post"}]} showTitle />
</>
);
}
@@ -1,11 +1,12 @@
---
title: خروجی‌ها و مسیریابی
description: مدیریت ترافیک خروجی در 3x-ui — خروجی‌های WARP و NordVPN، اشتراک‌های خروجی (مجموعه سرورها)، قواعد مسیریابی و متعادل‌کننده‌های بار.
description: مدیریت ترافیک خروجی در 3x-ui — خروجی‌های WARP، NordVPN، WireGuard PIA، اشتراک‌های خروجی (مجموعه سرورها)، قواعد مسیریابی و متعادل‌کننده‌های بار.
icon: Route
---
ورودی‌ها کلاینت‌ها را می‌پذیرند؛ **خروجی‌ها** تعیین می‌کنند ترافیک آن‌ها در ادامه به کجا برود.
3x-ui می‌تواند ترافیک را از طریق Cloudflare WARP، NordVPN یا مجموعه‌های خروجی دلخواه
3x-ui می‌تواند ترافیک را از طریق Cloudflare WARP، NordVPN، Private Internet Access
(خروجی WireGuard) یا مجموعه‌های خروجی دلخواه
وارد‌شده از یک اشتراک مسیریابی کند و با قواعد مسیریابی و متعادل‌کننده‌ها میان آن‌ها
انتخاب نماید.
@@ -86,6 +87,23 @@ WARP به سرور شما امکان می‌دهد ترافیک خود را از
یک کلید خصوصی را مستقیماً بپذیرد) و کشورها/سرورها را فهرست کند تا بتوانید یک خروجی NordVPN
بسازید.
## خروجی WireGuard PIA
3x-ui می‌تواند با نام کاربری و رمز عبور PIA وارد شود، کشورها/منطقه‌ها/سرورها را
از فهرست امضاشده نشان دهد و یک خروجی WireGuard بسازد. از
**Xray → خروجی‌ها → بیشتر → PIA** وارد شوید، سرور را انتخاب کنید و خروجی را
اضافه کنید. می‌توان چند سرور افزود (هر hostname یک خروجی). برچسب
`pia-<region>-<server>` است (مثلاً `pia-us-east-useast1`). افزودن یا **Reset**
در هر ردیف کلید را با `/addKey` ثبت می‌کند. یک hostname را نمی‌توان دو بار
افزود. خروج فقط توکن ذخیره‌شده را پاک می‌کند؛ حذف خروجی از فهرست خروجی‌ها.
Reset یا حذف، peer مربوط به WireGuard را در حساب PIA باطل نمی‌کند.
گذرواژه ذخیره نمی‌شود. توکن API مربوط به PIA با همان تنظیم
`NODE_TOKEN_ENCRYPTION` گره‌ها ذخیره می‌شود. اگر کلید قدیمی
`XUI_NODE_TOKEN_KEY` را بدون ورود دوباره به PIA کنار بگذارید، Add/Reset
تا ورود مجدد شکست می‌خورد. `allowedIPs` فقط
`0.0.0.0/0` است.
## اشتراک‌های خروجی (مجموعه سرورها)
یک **اشتراک خروجی** یک اشتراک share-link از راه دور را وارد می‌کند و سرورهای آن را به‌عنوان
+57 -10
View File
@@ -37,11 +37,10 @@ _openapi:
- depth: 2
title: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess, password
for Trojan/Shadowsocks, auth for Hysteria) are generated server-side
when omitted, so callers can send only the universal fields.
call. Body is JSON. Per-protocol secrets are generated server-side when
omitted, so callers can send only the universal fields.
url: >-
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
@@ -352,12 +351,10 @@ _openapi:
fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess,
password for Trojan/Shadowsocks, auth for Hysteria) are generated
server-side when omitted, so callers can send only the universal
fields.
call. Body is JSON. Per-protocol secrets are generated server-side
when omitted, so callers can send only the universal fields.
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload — supply the full
@@ -610,7 +607,57 @@ _openapi:
dokodemo, tunnel) contribute nothing.
id: >-
return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents: []
contents:
- content: >-
Fields the server fills in when they are omitted — a valid value sent
by the caller is never overwritten. Re-adding an email that already
exists, with its stored `subId`, reuses the stored `id`, `password`,
`auth` and `secret` instead of minting new ones, so the identity stays
in sync across its inbounds.
- **VLESS / VMess** — `id`, a fresh UUID
- **Trojan** — `password`
- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a
supplied password that does not base64-decode to the key length of the
cipher (16 or 32 bytes) is replaced by a generated key and the call
still succeeds, so read the client back if you did not let the server
pick. Legacy ciphers keep any non-empty password
- **Hysteria** — `auth`
- **mtproto** — `secret`, a FakeTLS secret derived from the fronting
domain of the inbound, or from `www.cloudflare.com` when it has none
- **WireGuard** — `privateKey` and `publicKey` when both are blank, or
`publicKey` alone when only a `privateKey` was sent, plus
`allowedIPs`: one free `/32` taken from the /24 the existing peers of
that inbound already sit in, or from `10.0.0.0/24` when it has none
Accepted on the same body but never generated: `preSharedKey` and
`keepAlive` (WireGuard), `adTag` (mtproto).
WireGuard is the only one of these that can fail. Allocation widens
the search to the containing /16 before giving up with `wireguard: no
free address available in <scope>`, and an `allowedIPs` supplied by
the caller is validated instead of allocated: `wireguard: allowedIPs
entry already used by another client: <address>` when a different
client of that same inbound already holds it. The check is per
inbound, so the same address on two different inbounds is accepted.
The same validation runs on POST /panel/api/clients/{email}/attach,
where a client that already carries an address brings it along.
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound
instead of being given a fresh address, so the call fails with
`wireguard: allowedIPs entry already used by another client:
<address>` when a different client of the target inbound already holds
it. Free the address on that inbound first — see POST
/panel/api/clients/add for the full rule.'
heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
+1 -1
View File
@@ -102,7 +102,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{id}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{id}","method":"post"},{"path":"/panel/api/hosts/del/{id}","method":"post"},{"path":"/panel/api/hosts/setEnable/{id}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{groupId}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{groupId}","method":"post"},{"path":"/panel/api/hosts/del/{groupId}","method":"post"},{"path":"/panel/api/hosts/setEnable/{groupId}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
</>
);
}
@@ -1,12 +1,13 @@
---
title: Исходящие соединения и маршрутизация
description: Управляйте исходящим трафиком в 3x-ui — outbound-соединения WARP и NordVPN, подписки на исходящие соединения (пулы серверов), правила маршрутизации и балансировщики нагрузки.
description: Управляйте исходящим трафиком в 3x-ui — WARP, NordVPN, PIA WireGuard, подписки на исходящие соединения (пулы серверов), правила маршрутизации и балансировщики нагрузки.
icon: Route
---
Inbound-соединения принимают клиентов; **outbound-соединения** определяют, куда
дальше пойдёт их трафик. 3x-ui может направлять трафик через Cloudflare WARP,
NordVPN или произвольные пулы исходящих соединений, импортированные из подписки,
NordVPN, Private Internet Access (WireGuard) или произвольные пулы
исходящих соединений, импортированные из подписки,
а также выбирать между ними с помощью правил маршрутизации и балансировщиков.
## Редактирование исходящих соединений и маршрутизации
@@ -93,6 +94,24 @@ WARP. Также можно применить бесплатную лиценз
(или принимать приватный ключ напрямую) и выводить список стран/серверов, чтобы вы
могли построить outbound-соединение NordVPN.
## PIA WireGuard
3x-ui может войти с именем пользователя и паролем PIA, показать
страны/регионы/серверы из подписанного списка и собрать WireGuard-исходящее.
Откройте **Xray → Исходящие → Ещё → PIA**, войдите, выберите сервер и добавьте
исходящее. Можно добавить несколько серверов (по одному исходящему на hostname).
Тег: `pia-<region>-<server>` (например `pia-us-east-useast1`). Добавление или
**Reset** в строке регистрирует ключ через PIA `/addKey`. Один и тот же hostname
нельзя добавить дважды. Выход очищает только сохранённый токен; удаляйте
исходящие в списке исходящих. Reset и удаление не отзывают WireGuard-peer
в аккаунте PIA.
Пароль не сохраняется. Токен PIA API хранится с той же настройкой
`NODE_TOKEN_ENCRYPTION`, что и токены API узлов. Если убрать старый
`XUI_NODE_TOKEN_KEY` без повторного входа в PIA, Add/Reset не будут
работать, пока вы не войдёте снова. `allowedIPs` только
`0.0.0.0/0`.
## Подписки на исходящие соединения (пулы серверов)
**Подписка на исходящие соединения** импортирует удалённую подписку со
+57 -10
View File
@@ -37,11 +37,10 @@ _openapi:
- depth: 2
title: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess, password
for Trojan/Shadowsocks, auth for Hysteria) are generated server-side
when omitted, so callers can send only the universal fields.
call. Body is JSON. Per-protocol secrets are generated server-side when
omitted, so callers can send only the universal fields.
url: >-
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
@@ -352,12 +351,10 @@ _openapi:
fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess,
password for Trojan/Shadowsocks, auth for Hysteria) are generated
server-side when omitted, so callers can send only the universal
fields.
call. Body is JSON. Per-protocol secrets are generated server-side
when omitted, so callers can send only the universal fields.
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload — supply the full
@@ -610,7 +607,57 @@ _openapi:
dokodemo, tunnel) contribute nothing.
id: >-
return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents: []
contents:
- content: >-
Fields the server fills in when they are omitted — a valid value sent
by the caller is never overwritten. Re-adding an email that already
exists, with its stored `subId`, reuses the stored `id`, `password`,
`auth` and `secret` instead of minting new ones, so the identity stays
in sync across its inbounds.
- **VLESS / VMess** — `id`, a fresh UUID
- **Trojan** — `password`
- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a
supplied password that does not base64-decode to the key length of the
cipher (16 or 32 bytes) is replaced by a generated key and the call
still succeeds, so read the client back if you did not let the server
pick. Legacy ciphers keep any non-empty password
- **Hysteria** — `auth`
- **mtproto** — `secret`, a FakeTLS secret derived from the fronting
domain of the inbound, or from `www.cloudflare.com` when it has none
- **WireGuard** — `privateKey` and `publicKey` when both are blank, or
`publicKey` alone when only a `privateKey` was sent, plus
`allowedIPs`: one free `/32` taken from the /24 the existing peers of
that inbound already sit in, or from `10.0.0.0/24` when it has none
Accepted on the same body but never generated: `preSharedKey` and
`keepAlive` (WireGuard), `adTag` (mtproto).
WireGuard is the only one of these that can fail. Allocation widens
the search to the containing /16 before giving up with `wireguard: no
free address available in <scope>`, and an `allowedIPs` supplied by
the caller is validated instead of allocated: `wireguard: allowedIPs
entry already used by another client: <address>` when a different
client of that same inbound already holds it. The check is per
inbound, so the same address on two different inbounds is accepted.
The same validation runs on POST /panel/api/clients/{email}/attach,
where a client that already carries an address brings it along.
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound
instead of being given a fresh address, so the call fails with
`wireguard: allowedIPs entry already used by another client:
<address>` when a different client of the target inbound already holds
it. Free the address on that inbound first — see POST
/panel/api/clients/add for the full rule.'
heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
+1 -1
View File
@@ -103,7 +103,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{id}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{id}","method":"post"},{"path":"/panel/api/hosts/del/{id}","method":"post"},{"path":"/panel/api/hosts/setEnable/{id}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{groupId}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{groupId}","method":"post"},{"path":"/panel/api/hosts/del/{groupId}","method":"post"},{"path":"/panel/api/hosts/setEnable/{groupId}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
</>
);
}
@@ -1,11 +1,12 @@
---
title: 出站与路由
description: 在 3x-ui 中调整出口流量——WARPNordVPN 出站、出站订阅(服务器池)、路由规则以及负载均衡器。
description: 在 3x-ui 中调整出口流量——WARPNordVPN、PIA WireGuard、出站订阅(服务器池)、路由规则以及负载均衡器。
icon: Route
---
入站负责接受客户端;**出站**则决定客户端的流量接下来发往何处。
3x-ui 可以让流量经由 Cloudflare WARP、NordVPN,或从订阅导入的任意出站池转发,
3x-ui 可以让流量经由 Cloudflare WARP、NordVPN、Private Internet Access
(WireGuard),或从订阅导入的任意出站池转发,
并通过路由规则和均衡器在它们之间进行选择。
## 编辑出站与路由
@@ -81,6 +82,19 @@ WARP 账户,并将其接入一个标签为 **`warp`** 的 WireGuard 出站:
直接接受一个私钥),并列出国家/服务器,从而让你构建一个
NordVPN 出站。
## PIA WireGuard
3x-ui 可以用 PIA 用户名和密码登录,从已验签的服务器列表里选择国家/区域/服务器,
并生成 WireGuard 出站。打开 **Xray → 出站 → 更多 → PIA**,登录后选服务器并添加出站。
可以添加多台服务器(每个 hostname 一条出站)。标签为 `pia-<region>-<server>`(例如
`pia-us-east-useast1`)。添加或对该行 **Reset** 会向该服务器的 PIA `/addKey` 注册密钥。
同一 hostname 不能添加两次。登出只清除保存的 token;删除出站请在出站列表里操作。
Reset 或删除出站不会撤销 PIA 账户侧的 WireGuard peer。
密码不落库。PIA API token 与节点 API token 共用 `NODE_TOKEN_ENCRYPTION`。
若在未重新登录 PIA 的情况下淘汰旧的 `XUI_NODE_TOKEN_KEY`Add/Reset 会失败,直到再次登录。
对端 `allowedIPs` 仅为 `0.0.0.0/0`IPv4)。
## 出站订阅(服务器池)
**出站订阅**会导入一个远程分享链接订阅,并将其中的服务器作为**出站**注入到正在运行的
+30 -9
View File
@@ -30,11 +30,9 @@ _openapi:
#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- depth: 2
title: >-
在一次调用中创建一个新客户端并将其挂载到一个或多个入站。请求体为 JSON。各协议的密钥
VLESS/VMess 的 UUID、Trojan/Shadowsocks 的 password、Hysteria 的 auth)在
省略时由服务端生成,因此调用方只需发送通用字段。
在一次调用中创建一个新客户端并将其挂载到一个或多个入站。请求体为 JSON。各协议的密钥在省略时由服务端生成,因此调用方只需发送通用字段。
url: >-
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- depth: 2
title: >-
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷——
@@ -290,11 +288,9 @@ _openapi:
id: >-
fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: >-
在一次调用中创建一个新客户端并将其挂载到一个或多个入站。请求体为 JSON。各协议的密钥
VLESS/VMess 的 UUID、Trojan/Shadowsocks 的 password、Hysteria 的 auth)在
省略时由服务端生成,因此调用方只需发送通用字段。
在一次调用中创建一个新客户端并将其挂载到一个或多个入站。请求体为 JSON。各协议的密钥在省略时由服务端生成,因此调用方只需发送通用字段。
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
按 email 更新现有客户端。变更会传播到每个挂载的入站。请求体为 JSON 客户端载荷——
请提供你希望保留的完整字段集(服务端会替换整条记录,而非局部更新)。
@@ -493,7 +489,32 @@ _openapi:
socks、http、mixed、wireguard、dokodemo、tunnel)不产生任何内容。
id: >-
return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents: []
contents:
- content: >-
服务端在字段被省略时自动填充;调用方提供的有效值不会被覆盖。若以已存在的 email 重新添加,且其已存储的 `subId` 一致,则沿用已存储的 `id`、`password`、`auth` 和 `secret`,而不是重新生成,以保证同一身份在其各个入站之间保持一致。
- **VLESS / VMess** —— `id`,新生成的 UUID
- **Trojan** —— `password`
- **Shadowsocks** —— `password`。在 `2022-blake3-*` 入站上,若调用方提供的 password 经 base64 解码后的长度不等于该加密方式所需的密钥长度(16 或 32 字节),它会被替换为服务端生成的密钥,且调用仍然返回成功;因此若不打算交由服务端生成,请回读该客户端确认。传统加密方式则保留任何非空 password
- **Hysteria** —— `auth`
- **mtproto** —— `secret`,由该入站的伪装域名派生的 FakeTLS 密钥;该入站未设置伪装域名时,则取自 `www.cloudflare.com`
- **WireGuard** —— 两个密钥都为空时生成 `privateKey` 与 `publicKey`;只提供了 `privateKey` 时仅推导 `publicKey`。此外还会分配 `allowedIPs`:从该入站现有对端所在的 /24 中取一个空闲的 `/32`,若该入站尚无对端,则取自 `10.0.0.0/24`
同一请求体也接受、但服务端不会自动生成的字段:`preSharedKey` 与 `keepAlive`WireGuard)、`adTag`mtproto)。
其中只有 WireGuard 这一步可能失败。分配地址时会先把搜索范围扩大到所属的 /16,之后才以 `wireguard: no free address available in <scope>` 放弃;而调用方自行提供的 `allowedIPs` 只做校验、不做分配:当同一入站上的另一个客户端已占用该地址时,返回 `wireguard: allowedIPs entry already used by another client: <address>`。该校验按入站进行,因此同一地址出现在两个不同入站上是允许的。POST /panel/api/clients/{email}/attach 也执行同样的校验——已带有地址的客户端会把该地址带入新的入站。
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
WireGuard 客户端会把已存储的 `allowedIPs` 带入新入站,而不是获得新分配的地址;因此当目标入站上的另一个客户端已占用该地址时,调用会以 `wireguard: allowedIPs entry already used by another client: <address>` 失败。请先在该入站上释放该地址——完整规则见 POST /panel/api/clients/add。
heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
+1 -1
View File
@@ -102,7 +102,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{id}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{id}","method":"post"},{"path":"/panel/api/hosts/del/{id}","method":"post"},{"path":"/panel/api/hosts/setEnable/{id}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/hosts/list","method":"get"},{"path":"/panel/api/hosts/get/{groupId}","method":"get"},{"path":"/panel/api/hosts/byInbound/{inboundId}","method":"get"},{"path":"/panel/api/hosts/tags","method":"get"},{"path":"/panel/api/hosts/add","method":"post"},{"path":"/panel/api/hosts/update/{groupId}","method":"post"},{"path":"/panel/api/hosts/del/{groupId}","method":"post"},{"path":"/panel/api/hosts/setEnable/{groupId}","method":"post"},{"path":"/panel/api/hosts/reorder","method":"post"},{"path":"/panel/api/hosts/bulk/setEnable","method":"post"},{"path":"/panel/api/hosts/bulk/del","method":"post"}]} showTitle />
</>
);
}
+22 -22
View File
@@ -22,28 +22,28 @@ The panel uses standard Go `html/template` to render the subscription page.
When rendering the template, the following variables are injected into the template context (`{{ .variable }}`):
* `{{ .sId }}`: Subscription ID (UUID).
* `{{ .enabled }}`: Whether the subscription/client is enabled (boolean).
* `{{ .isOnline }}`: Whether the subscription's client has a live connection right now (boolean). Computed from the panel's online-client tracking (local Xray plus any remote nodes) at render time.
* `{{ .download }}`: Formatted download traffic (e.g. "2.5 GB").
* `{{ .upload }}`: Formatted upload traffic.
* `{{ .total }}`: Formatted total traffic limit.
* `{{ .used }}`: Formatted used traffic (download + upload).
* `{{ .remained }}`: Formatted remaining traffic.
* `{{ .expire }}`: Expiration time as an int64 Unix timestamp in **seconds** (`0` means never). Multiply by 1000 for a JavaScript `Date`.
* `{{ .lastOnline }}`: Last online time as an int64 Unix timestamp in **milliseconds** (`0` means never seen).
* `{{ .downloadByte }}`: Download traffic in exact bytes (int64).
* `{{ .uploadByte }}`: Upload traffic in exact bytes (int64).
* `{{ .totalByte }}`: Total traffic limit in exact bytes (int64).
* `{{ .subUrl }}`: The URL of the subscription page.
* `{{ .subJsonUrl }}`: The URL for the JSON configuration of the subscription.
* `{{ .subClashUrl }}`: The URL for the Clash/Mihomo configuration.
* `{{ .subTitle }}`: The subscription title configured in the panel (Subscription → Information). Useful for page branding/headings. May be empty.
* `{{ .subSupportUrl }}`: The support URL configured in the panel. Useful for a "Contact support" link. May be empty.
* `{{ .links }}`: A list (slice) of string configurations (VMess, VLESS, etc. URLs). You can loop through them using `{{ range .links }} ... {{ end }}`.
* `{{ .emails }}`: A list (slice) of client emails, parallel to `links` — the email at index *i* owns the link at index *i*. May contain duplicates when one client has several links.
* `{{ .announce }}`: The announcement text configured in the panel (Settings → Subscription → Announce). May be empty.
* `{{ .datepicker }}`: Current calendar format used by the panel (e.g. "gregorian" or "jalali").
- `{{ .sId }}`: Subscription ID (UUID).
- `{{ .enabled }}`: Whether the subscription/client is enabled (boolean).
- `{{ .isOnline }}`: Whether the subscription's client has a live connection right now (boolean). Computed from the panel's online-client tracking (local Xray plus any remote nodes) at render time.
- `{{ .download }}`: Formatted download traffic (e.g. "2.5 GB").
- `{{ .upload }}`: Formatted upload traffic.
- `{{ .total }}`: Formatted total traffic limit.
- `{{ .used }}`: Formatted used traffic (download + upload).
- `{{ .remained }}`: Formatted remaining traffic.
- `{{ .expire }}`: Expiration time as an int64 Unix timestamp in **seconds** (`0` means never). Multiply by 1000 for a JavaScript `Date`.
- `{{ .lastOnline }}`: Last online time as an int64 Unix timestamp in **milliseconds** (`0` means never seen).
- `{{ .downloadByte }}`: Download traffic in exact bytes (int64).
- `{{ .uploadByte }}`: Upload traffic in exact bytes (int64).
- `{{ .totalByte }}`: Total traffic limit in exact bytes (int64).
- `{{ .subUrl }}`: The URL of the subscription page.
- `{{ .subJsonUrl }}`: The URL for the JSON configuration of the subscription.
- `{{ .subClashUrl }}`: The URL for the Clash/Mihomo configuration.
- `{{ .subTitle }}`: The subscription title configured in the panel (Subscription → Information). Useful for page branding/headings. May be empty.
- `{{ .subSupportUrl }}`: The support URL configured in the panel. Useful for a "Contact support" link. May be empty.
- `{{ .links }}`: A list (slice) of string configurations (VMess, VLESS, etc. URLs). You can loop through them using `{{ range .links }} ... {{ end }}`.
- `{{ .emails }}`: A list (slice) of client emails, parallel to `links` — the email at index _i_ owns the link at index _i_. May contain duplicates when one client has several links.
- `{{ .announce }}`: The announcement text configured in the panel (Settings → Subscription → Announce). May be empty.
- `{{ .datepicker }}`: Current calendar format used by the panel (e.g. "gregorian" or "jalali").
## Live Status JSON (`?format=info`)
-21
View File
@@ -1,21 +0,0 @@
import coreWebVitals from 'eslint-config-next/core-web-vitals';
import typescript from 'eslint-config-next/typescript';
/** @type {import('eslint').Linter.Config[]} */
const config = [
{
ignores: [
'.next/**',
'.source/**',
'out/**',
'node_modules/**',
'next-env.d.ts',
// Generated API reference pages (fumadocs-openapi output)
'content/docs/**/reference/api/**',
],
},
...coreWebVitals,
...typescript,
];
export default config;
+12 -1
View File
@@ -2,7 +2,15 @@ import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
import { Heart } from 'lucide-react';
import { Logo } from '@/components/logo';
import { TelegramIcon } from '@/components/icons';
import { appName, productRepoUrl, telegramChannel, telegramChannelUrl, donateUrl, siteUrl } from './shared';
import { DocsThemeSwitch } from '@/components/theme-switch';
import {
appName,
productRepoUrl,
telegramChannel,
telegramChannelUrl,
donateUrl,
siteUrl,
} from './shared';
import { getSiteMessages } from './site-i18n';
// Build locale-aware shared layout options. With `hideLocale: 'default-locale'`,
@@ -12,6 +20,9 @@ export function baseOptions(lang: string): BaseLayoutProps {
const m = getSiteMessages(lang);
return {
slots: {
themeSwitch: DocsThemeSwitch,
},
nav: {
title: (
<span className="inline-flex items-center gap-2 font-semibold">
+2 -1
View File
@@ -222,7 +222,8 @@ const zh: SiteMessages = {
},
{
title: '自托管且可脚本化',
description: '单个 Go 二进制文件或 Docker 镜像、SQLite/PostgreSQL 后端,以及用于自动化的完整 REST API。',
description:
'单个 Go 二进制文件或 Docker 镜像、SQLite/PostgreSQL 后端,以及用于自动化的完整 REST API。',
},
],
licenseBefore: '基于 ',
+20 -6
View File
@@ -31,7 +31,7 @@ const base = {
describe('buildCurl', () => {
it('GET emits the Bearer header, a single-quoted URL, and no body flag', () => {
const cmd = buildCurl({ ...base, method: 'GET' });
expect(cmd).toContain("-X GET");
expect(cmd).toContain('-X GET');
expect(cmd).toContain("-H 'Authorization: Bearer TKN'");
expect(cmd).toContain("'https://panel.example.com:2053/panel/api/inbounds/list'");
expect(cmd).not.toContain('--data');
@@ -39,14 +39,23 @@ describe('buildCurl', () => {
});
it('POST with a body emits --data and a JSON content type', () => {
const cmd = buildCurl({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
const cmd = buildCurl({
...base,
method: 'POST',
path: '/panel/api/inbounds/add',
body: '{"up":0}',
});
expect(cmd).toContain('-X POST');
expect(cmd).toContain("--data '{\"up\":0}'");
expect(cmd).toContain("Content-Type: application/json");
expect(cmd).toContain('--data \'{"up":0}\'');
expect(cmd).toContain('Content-Type: application/json');
});
it('POST without a body omits --data', () => {
const cmd = buildCurl({ ...base, method: 'POST', path: '/panel/api/inbounds/resetAllTraffics' });
const cmd = buildCurl({
...base,
method: 'POST',
path: '/panel/api/inbounds/resetAllTraffics',
});
expect(cmd).not.toContain('--data');
});
});
@@ -60,7 +69,12 @@ describe('buildFetchSnippet', () => {
});
it('POST with a body includes a JSON.stringify body', () => {
const snip = buildFetchSnippet({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
const snip = buildFetchSnippet({
...base,
method: 'POST',
path: '/panel/api/inbounds/add',
body: '{"up":0}',
});
expect(snip).toContain("method: 'POST'");
expect(snip).toContain('body: JSON.stringify(');
});
+6 -1
View File
@@ -160,7 +160,12 @@ describe('buildOutbound — wireguard & warp', () => {
const ob = buildOutbound({
kind: 'wireguard',
tag: 'wg',
wireguard: { secretKey: 'sk', address: ['10.0.0.2/32'], publicKey: 'pk', endpoint: 'host:51820' },
wireguard: {
secretKey: 'sk',
address: ['10.0.0.2/32'],
publicKey: 'pk',
endpoint: 'host:51820',
},
});
const s = ob.settings as Record<string, unknown>;
expect(s.secretKey).toBe('sk');
+5 -1
View File
@@ -162,7 +162,11 @@ function buildSettings(o: OutboundInput): Record<string, unknown> {
],
};
case 'trojan':
return { servers: [{ address: s?.address ?? '', port: toPort(s?.port), password: s?.password ?? '' }] };
return {
servers: [
{ address: s?.address ?? '', port: toPort(s?.port), password: s?.password ?? '' },
],
};
case 'shadowsocks':
return {
servers: [
+6 -1
View File
@@ -18,7 +18,12 @@ describe('buildBalancer', () => {
});
it('includes fallbackTag when set', () => {
const b = buildBalancer({ tag: 'lb', selector: ['a'], strategy: 'random', fallbackTag: 'direct' });
const b = buildBalancer({
tag: 'lb',
selector: ['a'],
strategy: 'random',
fallbackTag: 'direct',
});
expect(b.fallbackTag).toBe('direct');
});
});
+4 -1
View File
@@ -121,7 +121,10 @@ export function buildRouting(input: RoutingInput): Record<string, unknown> {
if (input.observatory) {
Object.assign(out, buildObservatory(input.observatory));
} else if (input.balancers.some((b) => b.strategy === 'leastLoad')) {
Object.assign(out, buildObservatory({ mode: 'burst', subjectSelector: uniqueSelectors(input.balancers) }));
Object.assign(
out,
buildObservatory({ mode: 'burst', subjectSelector: uniqueSelectors(input.balancers) }),
);
} else if (input.balancers.some((b) => b.strategy === 'leastPing')) {
Object.assign(
out,
+12 -2
View File
@@ -214,12 +214,20 @@ function proxyOutbound(c: SubClient): Record<string, unknown> {
};
break;
case 'trojan':
settings = { servers: [{ address: c.address, port: c.port, password: c.password ?? '', level: 8 }] };
settings = {
servers: [{ address: c.address, port: c.port, password: c.password ?? '', level: 8 }],
};
break;
case 'ss':
settings = {
servers: [
{ address: c.address, port: c.port, password: c.password ?? '', level: 8, method: c.method || '' },
{
address: c.address,
port: c.port,
password: c.password ?? '',
level: 8,
method: c.method || '',
},
],
};
break;
@@ -233,6 +241,8 @@ function proxyOutbound(c: SubClient): Record<string, unknown> {
};
}
// Mirrors the one-document-per-client model only; the panel also emits
// balancer documents (sub_balancers) that are intentionally out of scope here.
function jsonConfig(c: SubClient): Record<string, unknown> {
return {
remarks: c.remark,
+12 -5
View File
@@ -36,7 +36,10 @@ describe('parseAdminIds', () => {
});
it('accepts negative group ids and captures invalid entries', () => {
expect(parseAdminIds('-1001234567, abc, 42')).toEqual({ ids: [-1001234567, 42], invalid: ['abc'] });
expect(parseAdminIds('-1001234567, abc, 42')).toEqual({
ids: [-1001234567, 42],
invalid: ['abc'],
});
});
it('returns empty for blank input', () => {
@@ -78,9 +81,9 @@ describe('telegramApiBase', () => {
describe('renderMessageTemplate', () => {
it('substitutes known variables', () => {
expect(renderMessageTemplate('Host {{host}} up {{uptime}}', { host: 'srv', uptime: '3d' })).toBe(
'Host srv up 3d',
);
expect(
renderMessageTemplate('Host {{host}} up {{uptime}}', { host: 'srv', uptime: '3d' }),
).toBe('Host srv up 3d');
});
it('leaves unknown variables literal', () => {
@@ -90,7 +93,11 @@ describe('renderMessageTemplate', () => {
describe('buildBotConfigSummary', () => {
it('emits the panel settings keys with admin ids joined', () => {
const s = buildBotConfigSummary({ token: VALID_TOKEN, adminIds: '111, 222', runTime: '@daily' });
const s = buildBotConfigSummary({
token: VALID_TOKEN,
adminIds: '111, 222',
runTime: '@daily',
});
expect(s.tgBotEnable).toBe(true);
expect(s.tgBotToken).toBe(VALID_TOKEN);
expect(s.tgBotChatId).toBe('111,222');
+4 -1
View File
@@ -43,7 +43,10 @@ export function validateBotToken(token: string): TokenValidation {
export function parseAdminIds(raw: string): AdminIdsResult {
const ids: number[] = [];
const invalid: string[] = [];
for (const part of raw.split(',').map((s) => s.trim()).filter(Boolean)) {
for (const part of raw
.split(',')
.map((s) => s.trim())
.filter(Boolean)) {
// Telegram chat ids are integers; group/channel ids are negative.
if (/^-?\d+$/.test(part)) ids.push(Number(part));
else invalid.push(part);
+20 -21
View File
@@ -11,42 +11,41 @@
"postinstall": "fumadocs-mdx",
"gen:api": "node scripts/gen-openapi.ts",
"typecheck": "fumadocs-mdx && next typegen && tsc --noEmit",
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "oxlint .",
"format": "oxfmt .",
"format:check": "oxfmt --check .",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@orama/orama": "^3.1.18",
"fumadocs-core": "^16.11.5",
"fumadocs-core": "^16.14.5",
"fumadocs-docgen": "^3.1.0",
"fumadocs-mdx": "^15.2.0",
"fumadocs-openapi": "^11.2.2",
"fumadocs-ui": "^16.11.5",
"lucide-react": "^1.25.0",
"mermaid": "^11.16.0",
"next": "16.2.11",
"fumadocs-mdx": "^15.3.0",
"fumadocs-openapi": "^11.2.4",
"fumadocs-ui": "^16.14.5",
"lucide-react": "^1.33.0",
"mermaid": "^11.17.0",
"next": "16.3.1",
"next-themes": "^0.4.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-qr-code": "^2.2.0",
"tailwind-merge": "^3.6.0",
"zbsearch": "4.0.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
"@types/mdx": "^2.0.14",
"@types/node": "^26.1.1",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"eslint": "^9.39.5",
"eslint-config-next": "16.2.11",
"postcss": "^8.5.21",
"prettier": "^3.9.6",
"@types/node": "^26.2.0",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"oxfmt": "0.64.0",
"oxlint": "1.79.0",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.3",
"typescript": "^6.0.3",
"vitest": "^4.1.10"
"typescript": "7.0.2",
"vitest": "^4.1.11"
},
"packageManager": "pnpm@11.15.1+sha512.81350b07e53c9538a02f1f2303b4290fa2d7be04e56e2a970c4cc4b417dc761de196edabd49d55c7dc9580db81007c44143e4e3d7e462b3000d23c255122d065"
"packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621"
}
+1564 -3629
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -8,5 +8,8 @@ overrides:
'postcss@<8.5.10': '^8.5.15'
'sharp@<0.35.0': '^0.35.3'
minimumReleaseAgeExclude:
- '@mermaid-js/parser@1.2.0'
- mermaid@11.16.0
- '@mermaid-js/parser@1.2.1'
- mermaid@11.17.0
- lucide-react@1.33.0
- postcss@8.5.26
- fumadocs-mdx@15.3.0
+3235 -384
View File
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
# PWA installability verification
This change adds a network-only PWA surface to the login and panel pages. It
does not cache panel data, API responses, credentials, or WebSocket traffic.
## Local checks
Run these commands from the repository root after installing the pinned Node
and Go toolchains:
```text
cd frontend
npm run typecheck
npm run lint
npx vitest run --project unit
npx vitest run --project components
npm run build
cd ..
go test ./...
go build ./...
```
The built binary must serve these paths beneath the configured `webBasePath`:
- `manifest.webmanifest`
- `pwa-register.js`
- `service-worker.js`
- `icons/3x-ui-16.png`
- `icons/3x-ui-24.png`
- `icons/3x-ui-32.png`
- `icons/3x-ui-64.png`
- `icons/3x-ui-192.png`
- `icons/3x-ui-512.png`
The login and panel HTML must contain a manifest link and registration script
whose URLs begin with the same runtime base path. The manifest must contain
`display: "standalone"`, relative `start_url` and `scope`, and all six icon
entries.
## Live rollout checks
Before replacing a server binary, record the current x-ui binary checksum and
create a timestamped copy of the binary and `/etc/x-ui/x-ui.db`. Restart only
the `x-ui` service after the candidate is staged. Because x-ui manages Xray as
a child process, the restart can briefly interrupt VPN connections.
After the restart, verify:
1. `x-ui` is active and its child Xray process is running.
2. The existing panel URL serves HTML with the PWA manifest link.
3. The manifest, registration script, worker, and all six icons return `200`.
4. Login, authenticated API requests, panel navigation, logout, and the panel
WebSocket all work.
5. At least one VPN client can complete a fresh connection cycle.
If any check fails, restore the exact binary backup, restart x-ui once, and
repeat the checks against the original build.
+10 -10
View File
@@ -14,11 +14,11 @@ list, and multi-node sync — so once it is set, everything downstream just work
Open an inbound → **Transport / Stream Settings** → enable **Sockopt** → use the
**Real client IP** preset selector:
| Preset | What it does | Use for |
|---|---|---|
| **Off / direct** | Clears both fields. | Inbound reachable directly by clients. |
| **Cloudflare CDN** | Sets `sockopt.trustedXForwardedFor = ["CF-Connecting-IP"]`. | WebSocket / HTTPUpgrade / XHTTP behind Cloudflare's CDN (orange cloud). |
| **L4 relay / Spectrum (PROXY)** | Sets `acceptProxyProtocol = true`. | An L4 tunnel/relay in front, or Cloudflare **Spectrum**. |
| Preset | What it does | Use for |
| ------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------- |
| **Off / direct** | Clears both fields. | Inbound reachable directly by clients. |
| **Cloudflare CDN** | Sets `sockopt.trustedXForwardedFor = ["CF-Connecting-IP"]`. | WebSocket / HTTPUpgrade / XHTTP behind Cloudflare's CDN (orange cloud). |
| **L4 relay / Spectrum (PROXY)** | Sets `acceptProxyProtocol = true`. | An L4 tunnel/relay in front, or Cloudflare **Spectrum**. |
The raw `Proxy Protocol` switch and `Trusted X-Forwarded-For` list stay visible below the preset
selector for manual / advanced tuning — the presets just fill them in for you.
@@ -65,16 +65,16 @@ and XHTTP; **not** on mKCP. The front must be configured to send the header, e.g
## Transport support matrix
| Mechanism | TCP/RAW | mKCP | WebSocket | gRPC | HTTPUpgrade | XHTTP |
|---|:--:|:--:|:--:|:--:|:--:|:--:|
| `trustedXForwardedFor` (header) | | | ✅ | | ✅ | ✅ |
| `acceptProxyProtocol` (PROXY) | ✅ | – | ✅ | ✅ | ✅ | ✅ |
| Mechanism | TCP/RAW | mKCP | WebSocket | gRPC | HTTPUpgrade | XHTTP |
| ------------------------------- | :-----: | :--: | :-------: | :--: | :---------: | :---: |
| `trustedXForwardedFor` (header) | | | ✅ | | ✅ | ✅ |
| `acceptProxyProtocol` (PROXY) | ✅ | – | ✅ | ✅ | ✅ | ✅ |
The form shows a warning when you select a preset that the current transport cannot honor.
> **Use one, not both.** `acceptProxyProtocol` and `trustedXForwardedFor` are independent — the
> first reads the real IP from the L4 PROXY header, the second from an HTTP request header. On
> WebSocket / HTTPUpgrade / XHTTP, xray applies the HTTP header *last*, so a stale
> WebSocket / HTTPUpgrade / XHTTP, xray applies the HTTP header _last_, so a stale
> `trustedXForwardedFor` would override (and defeat) a PROXY-protocol setup. The presets are
> mutually exclusive and clear the other field for you; only mix them by hand if you know your
> upstream chain needs it.
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"ignorePatterns": [
"node_modules",
"src/generated",
"public",
"tools/oxlint/__fixtures__"
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"node_modules/**"
],
"plugins": [
"typescript",
"react",
"jsx-a11y"
],
"jsPlugins": [
"./tools/oxlint/input-number-guard.mjs"
],
"categories": {
"correctness": "error"
},
"env": {
"browser": true,
"es2022": true
},
"rules": {
"typescript/no-explicit-any": "error",
"typescript/no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
],
"typescript/ban-ts-comment": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-namespace": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-unused-expressions": "warn",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/triple-slash-reference": "error",
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error",
"jsx-a11y/no-autofocus": "off",
"input-number/no-synthetic-clear": "off",
"jsx-a11y/prefer-tag-over-role": "off"
},
"overrides": [
{
"files": [
"src/pages/settings/**/*.tsx",
"src/pages/xray/**/*.tsx"
],
"rules": {
"input-number/no-synthetic-clear": "error"
}
},
{
"files": [
"src/pages/xray/**/*Modal.tsx"
],
"rules": {
"input-number/no-synthetic-clear": "off"
}
}
]
}
+3 -2
View File
@@ -31,8 +31,9 @@ The `@` import alias maps to `src/`.
Form *state* runs on React Hook Form (`src/components/form/rhf/`), not Ant
Design's `Form` store.
- Function components + hooks only; no class components.
- No `//` line comments in committed TS/TSX. HTML comments are fine.
- TS strict; `no-explicit-any` is an error. Build forms with `useZodForm` +
- Comments in committed TS/TSX: 2 lines MAX per comment block, spent on the
*why* a name cannot hold (same rule as root CLAUDE.md). HTML comments are fine.
- TS strict; oxlint's `typescript/no-explicit-any` is an error. Build forms with `useZodForm` +
`FormField` from `@/components/form/rhf` (wrap the tree in `FormProvider`);
validate through the `zodResolver` or per-field
`rules={{ validate: rhfZodValidate(Schema.shape.field) }}` — messages are Zod
+27 -11
View File
@@ -33,7 +33,10 @@ production-style links work without round-tripping through Go.
| `npm run build` | Regenerates OpenAPI + Zod, then builds into `../internal/web/dist/` |
| `npm run preview` | Serve the built bundle locally |
| `npm run typecheck` | `tsc --noEmit` (strict, no emit) |
| `npm run lint` | ESLint flat config (`@typescript-eslint` + `react-hooks`) |
| `npm run lint` | oxlint over `src/` + `tools/` (`.oxlintrc.json`) |
| `npm run lint:deprecated` | Type-aware sweep for JSDoc `@deprecated` APIs (on demand) |
| `npm run format` | oxfmt (`.oxfmtrc.json`) — rewrites `src/` + `tools/` in place |
| `npm run format:check` | oxfmt in check mode (no writes) |
| `npm run test` | Vitest single run (schema fixtures, link parsers, …) |
| `npm run test:watch` | Vitest watch mode |
| `npm run storybook` | Storybook dev server on `:6006` (component workbench + autodocs) |
@@ -41,8 +44,8 @@ production-style links work without round-tripping through Go.
| `npm run gen:api` | Build `public/openapi.json` from `pages/api-docs/endpoints.ts` |
| `npm run gen:zod` | Run the Go-side openapigen tool → `src/generated/{zod,types}.ts` |
CI runs `typecheck`, `lint`, `test`, `build`, and `build-storybook` on
every PR (see `../.github/workflows/ci.yml`).
CI runs `typecheck`, `lint`, `format:check`, `test`, `build`, and
`build-storybook` on every PR (see `../.github/workflows/ci.yml`).
### One-off: scan for deprecated APIs
@@ -51,12 +54,13 @@ with the JSDoc `@deprecated` tag (AntD prop renames, Zod renames,
removed Web APIs, etc.):
```sh
npx eslint --config eslint.deprecated.config.js src
npm run lint:deprecated
```
It's a type-aware ESLint run against `eslint.deprecated.config.js`
and is not wired into `npm run lint` because typed linting triples
the wall-clock time.
It is oxlint's type-aware mode (`oxlint-tsgolint`, which drives the
TypeScript 7 `typescript-go` checker) narrowed to `no-deprecated`, and
is not wired into `npm run lint` because typed linting needs a full
type-check pass.
## Production build
@@ -70,15 +74,27 @@ react-query into separate vendor bundles to keep the per-page
initial JS small. The Go binary embeds this directory at compile
time and `internal/web/controller/dist.go` serves the per-page HTML.
### PWA mode
The login and panel pages expose a minimal network-only Progressive Web App.
The manifest, service worker, registration script, and icons are embedded with
the frontend and served under the runtime `webBasePath`. The service worker
does not use Cache Storage, does not intercept requests, and does not provide
offline access; panel authentication, API calls, and WebSocket traffic remain
normal network requests.
## Layout
```
frontend/
├── index.html, login.html, subpage.html # 3 Vite entries
├── tsconfig.json
├── eslint.config.js
├── eslint.deprecated.config.js # On-demand type-aware lint config that flags
│ # usages of APIs marked with JSDoc @deprecated
├── .oxlintrc.json # oxlint config (replaces the ESLint flat config)
├── .oxfmtrc.json # oxfmt config (Prettier-compatible settings)
├── tools/oxlint/
│ └── input-number-guard.mjs # oxlint JS plugin: the #6121/#6127 cleared-
│ # InputNumber guard (oxlint has no
│ # no-restricted-syntax)
├── vitest.config.ts
├── vite.config.js
├── .storybook/ # Storybook config (main.ts, preview.tsx)
@@ -146,7 +162,7 @@ Patterns:
- Wire request: `Schema.parse(payload)` inside `mutationFn` — throws,
because a malformed payload here is always a developer bug
- **No `.loose()` or `[key: string]: any`** in production schemas.
`@typescript-eslint/no-explicit-any: error` is enforced.
`typescript/no-explicit-any: error` is enforced by oxlint.
## Form pattern (Pattern A)
-89
View File
@@ -1,89 +0,0 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import globals from 'globals';
export default [
{ ignores: ['node_modules/**', '../internal/web/dist/**'] },
js.configs.recommended,
...tseslint.configs.recommended.map((config) => ({
...config,
files: ['**/*.{ts,tsx}'],
})),
{
files: ['**/*.{ts,tsx}'],
plugins: {
'react-hooks': reactHooks,
},
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
globals: {
...globals.browser,
},
},
rules: {
...reactHooks.configs.recommended.rules,
'@typescript-eslint/no-unused-vars': ['warn', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
}],
// Zod migration goal (Step 7): every production module is held to
// strict no-explicit-any. The two legacy class files at the bottom
// of the rule list keep their existing file-level eslint-disable
// until DBInbound is migrated off Inbound.toInbound() — see the
// migration spec Non-Goals section.
'@typescript-eslint/no-explicit-any': 'error',
'no-empty': ['error', { allowEmptyCatch: true }],
'react-hooks/set-state-in-effect': 'off',
'react-hooks/purity': 'off',
'react-hooks/react-compiler': 'off',
'react-hooks/preserve-manual-memoization': 'off',
'react-hooks/immutability': 'off',
'react-hooks/refs': 'off',
},
},
{
files: ['**/*.tsx'],
plugins: { 'jsx-a11y': jsxA11y },
rules: {
...jsxA11y.flatConfigs.recommended.rules,
'jsx-a11y/no-autofocus': 'off',
},
},
{
// The settings and xray pages write numeric InputNumber changes straight
// into state, so a null-collapsing handler (`Number(v) || N`, or the
// ternary `typeof v === 'number' ? v : N`) turns a cleared field into a
// stored N — the cleared-port bug, #6121. Handlers here go through
// onNumber() (src/utils/onNumber.ts) instead. Known limit: a handler
// extracted into a variable and passed as onChange={handler} is not
// matched; the inline shapes below are the ones that drift in practice.
files: ['src/pages/settings/**/*.tsx', 'src/pages/xray/**/*.tsx'],
rules: {
'no-restricted-syntax': ['error', {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] LogicalExpression[operator="||"] > CallExpression[callee.name="Number"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}, {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] ConditionalExpression[test.left.operator="typeof"][alternate.type="Literal"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}, {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] LogicalExpression[operator="??"][right.type="Literal"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}],
},
},
{
// The xray form modals (OutboundFormModal, BalancerFormModal,
// DnsServerModal, WarpModal, …) stage values behind Zod validation like
// the clients/inbounds modals do, and some of their fields carry a
// deliberate clear-means-zero semantic — the direct-write rule above
// does not apply to them.
files: ['src/pages/xray/**/*Modal.tsx'],
rules: {
'no-restricted-syntax': 'off',
},
},
];
-26
View File
@@ -1,26 +0,0 @@
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{ ignores: ['node_modules/**', '../internal/web/dist/**', 'src/generated/**'] },
{
files: ['**/*.{ts,tsx}'],
plugins: {
'@typescript-eslint': tseslint.plugin,
'react-hooks': reactHooks,
},
languageOptions: {
parser: tseslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
'@typescript-eslint/no-deprecated': 'warn',
},
linterOptions: {
reportUnusedDisableDirectives: 'off',
},
},
];
+2312 -3618
View File
File diff suppressed because it is too large Load Diff
+41 -39
View File
@@ -1,7 +1,7 @@
{
"name": "3x-ui-frontend",
"private": true,
"version": "0.6.0",
"version": "1.0.0",
"type": "module",
"description": "3x-ui panel frontend (React 19 + Ant Design 6 + Vite 8).",
"engines": {
@@ -12,7 +12,11 @@
"dev": "vite",
"build": "npm run gen:api && vite build",
"preview": "vite preview",
"lint": "eslint src",
"lint": "oxlint src tools",
"lint:fix": "oxlint --fix src tools",
"lint:deprecated": "oxlint --type-aware -A all -D typescript/no-deprecated src",
"format": "oxfmt src tools",
"format:check": "oxfmt --check src tools",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
@@ -24,64 +28,61 @@
"prepare": "cd .. && husky frontend/.husky || true"
},
"lint-staged": {
"src/**/*.{ts,tsx}": "eslint --fix"
"src/**/*.{ts,tsx}": [
"oxfmt",
"oxlint --fix"
]
},
"dependencies": {
"@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^5.5.7",
"@noble/hashes": "^2.2.0",
"@tanstack/react-query": "^5.101.4",
"@tanstack/react-query-devtools": "^5.101.4",
"antd": "^6.5.2",
"@hookform/resolvers": "^5.9.1",
"@noble/hashes": "^2.3.0",
"@tanstack/react-query": "^5.102.2",
"@tanstack/react-query-devtools": "^5.102.2",
"antd": "^6.6.1",
"codemirror": "^6.0.2",
"dayjs": "^1.11.21",
"i18next": "^26.3.6",
"dayjs": "^1.11.23",
"i18next": "^26.4.0",
"otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.5",
"persian-calendar-suite": "^1.5.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-hook-form": "^7.83.0",
"react-i18next": "^17.0.11",
"react-hook-form": "^7.86.0",
"react-i18next": "^17.0.12",
"react-router": "^8.3.0",
"swagger-ui-react": "^5.32.11",
"swagger-ui-react": "^5.32.14",
"uplot": "^1.6.32",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@storybook/addon-a11y": "^10.5.5",
"@storybook/addon-docs": "^10.5.5",
"@storybook/addon-vitest": "^10.5.5",
"@storybook/react-vite": "^10.5.5",
"@storybook/addon-a11y": "^10.5.10",
"@storybook/addon-docs": "^10.5.10",
"@storybook/addon-vitest": "^10.5.10",
"@storybook/react-vite": "^10.5.10",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.5",
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.0.4",
"@vitest/browser-playwright": "4.1.10",
"@vitest/coverage-v8": "^4.1.10",
"eslint": "^10.8.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react-hooks": "^7.1.1",
"globals": "^17.8.0",
"@vitejs/plugin-react": "^6.1.0",
"@vitest/browser-playwright": "4.1.11",
"@vitest/coverage-v8": "^4.1.11",
"husky": "^9.1.7",
"jsdom": "^30.0.1",
"lint-staged": "^17.2.0",
"lint-staged": "^17.3.0",
"msw": "^2.15.0",
"playwright": "^1.62.0",
"storybook": "^10.5.5",
"typescript": "6.0.3",
"typescript-eslint": "^8.65.0",
"vite": "8.1.5",
"vitest": "^4.1.10"
"oxfmt": "0.64.0",
"oxlint": "1.79.0",
"oxlint-tsgolint": "^7.0.2001",
"playwright": "^1.62.1",
"storybook": "^10.5.10",
"typescript": "7.0.2",
"vite": "8.2.2",
"vitest": "^4.1.11"
},
"overrides": {
"eslint-plugin-jsx-a11y": {
"eslint": "$eslint"
},
"dompurify": "^3.4.11",
"react-copy-to-clipboard": "^5.1.1",
"react-inspector": "^9.0.0",
@@ -89,7 +90,8 @@
"react": "^19.0.0"
},
"swagger-ui-react": {
"js-yaml": "^4.2.0"
"js-yaml": "^4.2.0",
"brace-expansion": "^5.0.9"
},
"@typeschema/valibot": {
"valibot": "^1.1.0"
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

+41
View File
@@ -0,0 +1,41 @@
{
"name": "3x-ui",
"short_name": "3x-ui",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#0f172a",
"theme_color": "#1677ff",
"icons": [
{
"src": "icons/3x-ui-16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "icons/3x-ui-24.png",
"sizes": "24x24",
"type": "image/png"
},
{
"src": "icons/3x-ui-32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "icons/3x-ui-64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "icons/3x-ui-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/3x-ui-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+21 -9
View File
@@ -7,8 +7,8 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.14.7'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const PACKAGE_VERSION = '2.15.0'
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
@@ -137,8 +137,18 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)
// Omit the body of server-sent event stream responses.
// Cloning such responses would prevent client-side stream cancelations
// from reaching the original stream (a teed stream only cancels its
// source once both of its branches cancel) and would buffer the
// entire stream into the unconsumed clone indefinitely.
const isEventStreamResponse = response.headers
.get('content-type')
?.toLowerCase()
.startsWith('text/event-stream')
// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()
const responseClone = isEventStreamResponse ? null : response.clone()
sendToClient(
client,
@@ -151,15 +161,17 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
type: response.type,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: responseClone ? responseClone.body : null,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
responseClone && responseClone.body
? [serializedRequest.body, responseClone.body]
: [],
)
}
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
(() => {
if (!('serviceWorker' in navigator)) return;
const script = document.currentScript;
if (!(script instanceof HTMLScriptElement)) return;
const scriptUrl = new URL(script.src, window.location.href);
const baseUrl = new URL('./', scriptUrl);
const workerUrl = new URL('service-worker.js', baseUrl);
navigator.serviceWorker.register(workerUrl.pathname, {
scope: baseUrl.pathname,
}).catch(() => {});
})();

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