Compare commits

...

27 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
298 changed files with 29381 additions and 1475 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ question it already answers.
3x-ui is an open-source web control panel for managing Xray-core servers.
- Backend: Go 1.26, module `github.com/mhsanaei/3x-ui/v3`, Gin and GORM.
- 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
+69 -5
View File
@@ -494,6 +494,44 @@ jobs:
- uses: actions/checkout@v7
with:
persist-credentials: false
# An `@claude review` vouches for the head that existed when it was typed;
# a push after it would swap the code out from under that approval.
- name: Pin the head this run reviews
id: pinned-sha
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
PR: ${{ github.event.pull_request.number || github.event.issue.number }}
PAYLOAD_SHA: ${{ github.event.pull_request.head.sha }}
COMMENT_AT: ${{ github.event.comment.created_at }}
run: |
set -euo pipefail
if [ -n "$PAYLOAD_SHA" ]; then
echo "sha=${PAYLOAD_SHA}" >> "$GITHUB_OUTPUT"
exit 0
fi
head=$(gh api "repos/${REPO}/pulls/${PR}" --jq '"\(.head.sha) \(.head.repo.pushed_at // "")"')
HEAD_SHA=${head%% *}
HEAD_PUSHED_AT=${head#* }
if [ -z "$HEAD_PUSHED_AT" ]; then
gh pr comment "$PR" --repo "$REPO" --body "The head repository of this pull request is gone, so the code to review cannot be verified. Nothing was reviewed."
echo "::error::The head repository is unavailable; refusing to check it out."
exit 1
fi
if [ "$(date -d "$HEAD_PUSHED_AT" +%s)" -gt "$(date -d "$COMMENT_AT" +%s)" ]; then
gh pr comment "$PR" --repo "$REPO" --body "The head branch was pushed to at ${HEAD_PUSHED_AT}, after this review was requested at ${COMMENT_AT}, so the code that would be checked out here is not the code the request vouched for. Nothing was reviewed. Ask again to review the current head."
echo "::error::The head moved after the request; refusing to check it out."
exit 1
fi
echo "sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
# Read-only, and pinned to one immutable commit: this job holds a
# write-scoped token, so running anything out of pr-head/ would be a pwn-request.
- uses: actions/checkout@v7
with:
ref: ${{ steps.pinned-sha.outputs.sha }}
path: pr-head
persist-credentials: false
allow-unsafe-pr-checkout: true
- uses: anthropics/claude-code-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
@@ -501,13 +539,18 @@ jobs:
allowed_non_write_users: "*"
plugin_marketplaces: "https://github.com/anthropics/claude-code.git"
plugins: "code-review@claude-code-plugins"
prompt: "/code-review:code-review --comment ${{ github.repository }}/pull/${{ github.event.pull_request.number || github.event.issue.number }}"
# The skill reads CLAUDE.md on its own but NOT REVIEW.md - that file
# reaches a review only through the append-system-prompt below.
prompt: "/code-review:code-review max --comment ${{ github.repository }}/pull/${{ github.event.pull_request.number || github.event.issue.number }}"
# allowedTools only pre-approves; it denies nothing. Only the deny
# list stops the review executing what it just checked out.
claude_args: |
--model claude-opus-5
--effort xhigh
--max-turns 100
--allowedTools "mcp__github_inline_comment__create_inline_comment"
--append-system-prompt "Before reviewing, read REVIEW.md at the repository root and follow it: it defines what counts as a blocking finding in this repository, what not to report, and the repo-specific checks. Two overrides apply here. First, the skip gate for already-reviewed PRs: an existing Claude review comment justifies skipping ONLY when its 'Reviewed head:' SHA equals the PR's current head SHA; when the head has moved on, or this run was triggered by an explicit '@claude review' comment, run the full review, focusing on the commits since the previously reviewed head. Second, this is a headless run that terminates the moment you end your turn: launch every subagent with run_in_background set to false and wait for its result inside the same turn - never end your turn while a subagent is still running, and never end it before the review comment is posted. A run that ends without posting the review has failed."
--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh api:*),Bash(gh pr diff:*),Bash(grep:*),Bash(rg:*),Bash(ls:*),Bash(find:*),Bash(sed:*),Bash(git log:*),Bash(git show:*),Bash(git diff:*),Bash(go doc:*),Bash(go env:*),Read,Glob,Grep,WebFetch,WebSearch"
--disallowedTools "Bash(go build:*),Bash(go run:*),Bash(go test:*),Bash(go generate:*),Bash(go install:*),Bash(make:*),Bash(npm:*),Bash(npx:*),Bash(pnpm:*),Bash(yarn:*),Bash(node:*),Bash(bash:*),Bash(sh:*),Bash(docker:*),Bash(chmod:*),Edit,Write,NotebookEdit"
--append-system-prompt "Before reviewing, read REVIEW.md at the repository root and follow it: it defines the severity marker every finding carries, what counts as Important in this repository, what not to report, and the repo-specific checks. Five overrides apply here. First, the skip gate for already-reviewed PRs: an existing Claude review comment justifies skipping ONLY when its 'Reviewed head:' SHA equals the PR's current head SHA; when the head has moved on, or this run was triggered by an explicit '@claude review' comment, run the full review, focusing on the commits since the previously reviewed head. Second, this is a headless run that terminates the moment you end your turn: launch every subagent with run_in_background set to false and wait for its result inside the same turn - never end your turn while a subagent is still running, and never end it before the review comment is posted. A run that ends without posting the review has failed. Third, the comment you post is the only part of this run anyone can see: it must open with the tally and end with the coverage list REVIEW.md asks for, whether or not you found anything. Fourth, the default working tree is the BASE branch, and a read-only checkout of the pull request head sits beside it in pr-head/: read and grep the changed files under pr-head/, and treat anything read outside it as the pre-merge baseline rather than as the code under review. Never build, install or execute anything from pr-head/ - this job holds a write-scoped token, so running pull-request code with it is the workflow vulnerability REVIEW.md itself calls blocking. Fifth, you cannot build or test here, but CI already did: read the head commit's checks with 'gh api repos/OWNER/REPO/commits/HEAD_SHA/check-runs' and report what they actually concluded instead of writing that verification was unavailable. A required check that failed, or that never ran on this head, is itself a finding."
- name: Upload the run transcript
if: always()
env:
@@ -519,7 +562,7 @@ jobs:
if-no-files-found: ignore
retention-days: 7
- name: Fail if the review posted nothing
if: ${{ !cancelled() }}
if: ${{ !cancelled() && steps.pinned-sha.outcome == 'success' }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
@@ -656,6 +699,10 @@ jobs:
resolve-conflicts:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, 'resolve pr conflicts') && github.event.comment.user.login == github.repository_owner && github.event.comment.author_association == 'OWNER'
runs-on: ubuntu-latest
# claude-code-action replaces these with the base branch's copies before it
# runs, so a change to them is the action's doing, never the agent's.
env:
RESTORED_PATHS: ".claude .claude-pr .mcp.json .claude.json .gitmodules .ripgreprc CLAUDE.md CLAUDE.local.md .husky"
concurrency:
group: claude-conflicts-${{ github.event.issue.number }}
cancel-in-progress: false
@@ -746,6 +793,18 @@ jobs:
hand_back "The merge of \`${base}\` conflicts over paths this job refuses to hand to its tooling:
$(printf '%s\n' "$odd" | sed 's/^/- /')
Nothing was changed. Resolve those by hand."
fi
clobbered=$(printf '%s\n' "$files" | while IFS= read -r f; do
for p in $RESTORED_PATHS; do
case "$f" in "$p" | "$p"/*) printf '%s\n' "$f" ;; esac
done
done)
if [ -n "$clobbered" ]; then
git merge --abort 2>/dev/null || true
hand_back "The merge of \`${base}\` conflicts over paths the bot's own tooling replaces with the \`${base}\` copy before it runs, so a resolution there cannot survive:
$(printf '%s\n' "$clobbered" | sed 's/^/- /')
Nothing was changed. Resolve those by hand."
fi
rules=""
@@ -856,7 +915,12 @@ jobs:
stray=""
while IFS= read -r f; do
[ -z "$f" ] && continue
if ! grep -qxF "$f" <<< "$FILES"; then
grep -qxF "$f" <<< "$FILES" && continue
restored=false
for p in $RESTORED_PATHS; do
case "$f" in "$p" | "$p"/*) restored=true ;; esac
done
if [ "$restored" = false ]; then
stray="${stray} ${f}"
fi
done <<< "$(git diff --name-only)"
+13 -7
View File
@@ -8,7 +8,7 @@ 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
@@ -41,6 +41,14 @@ file locations when it can answer in one hop.
- `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).
@@ -50,7 +58,7 @@ 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/` — 17 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/`.
@@ -59,8 +67,7 @@ file locations when it can answer in one hop.
- `tools/openapigen/` — Go generator that emits frontend types + Zod/JSON schemas
into `frontend/src/generated/` from Go structs. The OpenAPI doc itself
(`frontend/public/openapi.json`) is assembled from those + `endpoints.ts` by
`frontend/scripts/build-openapi.mjs`. (`tools/seedperf/` is a separate seeding
/load helper.)
`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
@@ -125,7 +132,7 @@ file locations when it can answer in one hop.
## Frontend conventions (summary; full version in frontend/CLAUDE.md)
- Ant Design 6 only — no Tailwind/shadcn. Targeted tweaks, not rewrites.
- TS strict; oxlint's `typescript/no-explicit-any` is an error. Zod schemas in
- 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
@@ -147,8 +154,7 @@ 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 # gen-check + lint + format-check + typecheck + test + build
# + build-storybook
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
+1 -1
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.
+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
+88 -16
View File
@@ -5,9 +5,32 @@ 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.
## What a blocking finding means here
## Severity
Reserve blocking severity for:
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
@@ -28,9 +51,7 @@ Reserve blocking severity for:
- 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 is blocking.
Style, naming and refactoring suggestions are nits at most.
executes pull-request code.
## Always check
@@ -40,23 +61,43 @@ Style, naming and refactoring suggestions are nits at most.
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 blocking, not a nit.
- A new i18n key exists in ALL 13 locale files in `internal/web/translation/`
and is referenced from `frontend/src` or Go in the same PR.
- A bug fix carries a test that would fail without the fix. A test that
passes either way, asserts only `err != nil` or `len(x) > 0`, or was made
green by regenerating golden fixtures or Vitest snapshots is a real finding.
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, `npm audit`, govulncheck.
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
@@ -67,9 +108,40 @@ Style, naming and refactoring suggestions are nits at most.
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 nits
## Cap the volume
Report at most five nits per review and say "plus N similar" in the summary
for the rest. Lead the summary with "No blocking issues" when everything found
is a nit. After the first review of a PR, report blocking findings only.
🔴 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.
+45 -2
View File
@@ -37,8 +37,8 @@ func section(t *testing.T, doc, from, to string) string {
t.Fatalf("%s no longer contains the heading %q", botContextPath, from)
}
rest := doc[i+len(from):]
if j := strings.Index(rest, to); j >= 0 {
return rest[:j]
if before, _, ok := strings.Cut(rest, to); ok {
return before
}
return rest
}
@@ -153,3 +153,46 @@ func TestBotContextSkipGatesExist(t *testing.T) {
})
}
}
// 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)
}
}
+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
+6 -4
View File
@@ -51,7 +51,7 @@ 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`).
@@ -136,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):
@@ -163,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, geodata)
│ │ │ ├── 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
@@ -202,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
@@ -372,6 +373,7 @@ All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` me
| `@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 |
@@ -497,7 +499,7 @@ for AutoMigrate in `internal/database/db.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` |
| **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` |
+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,12 +1,8 @@
---
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:
+147 -48
View File
@@ -14,24 +14,29 @@ _openapi:
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 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'
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: 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
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: 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: 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'
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
@@ -49,10 +54,10 @@ _openapi:
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
are not affected. Triggers an Xray restart if any counter actually
@@ -65,10 +70,10 @@ _openapi:
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'
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
/bulkCreate and /import accept — so the payload round-trips straight
@@ -89,12 +94,16 @@ _openapi:
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
applied with a single read-modify-write per inbound; the running Xray
@@ -189,6 +198,13 @@ _openapi:
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: 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: 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
@@ -205,6 +221,17 @@ _openapi:
- depth: 2
title: Reset the recorded IP list for a client.
url: '#reset-the-recorded-ip-list-for-a-client'
- depth: 2
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.
@@ -255,23 +282,26 @@ _openapi:
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
- 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
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: 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 (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
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
@@ -285,10 +315,10 @@ _openapi:
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: 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.
@@ -299,10 +329,10 @@ _openapi:
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
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
@@ -321,11 +351,15 @@ _openapi:
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
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
@@ -409,6 +443,13 @@ _openapi:
/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: 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.
@@ -421,6 +462,14 @@ _openapi:
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 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
@@ -458,7 +507,57 @@ _openapi:
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: []
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. */}
@@ -470,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 />
</>
);
}
+42 -43
View File
@@ -13,66 +13,65 @@ _openapi:
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: 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: []
---
@@ -85,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 />
</>
);
}
@@ -33,6 +33,15 @@ _openapi:
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'
@@ -59,6 +68,10 @@ _openapi:
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'
- depth: 2
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.
@@ -94,10 +107,6 @@ _openapi:
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'
- depth: 2
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'
structuredData:
headings:
- content: List every inbound owned by the authenticated user, including each
@@ -121,6 +130,14 @@ _openapi:
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,
@@ -141,6 +158,9 @@ _openapi:
- 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: 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
@@ -169,9 +189,6 @@ _openapi:
- 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
- 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
contents: []
---
@@ -184,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"},{"path":"/panel/api/inbounds/{id}/subSortIndex","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",
+26 -20
View File
@@ -22,6 +22,11 @@ _openapi:
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'
- 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'
@@ -32,12 +37,15 @@ _openapi:
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'
@@ -72,11 +80,6 @@ _openapi:
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'
- 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'
structuredData:
headings:
- content: List every configured node with its connection details, health, and
@@ -91,6 +94,10 @@ _openapi:
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
- 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
@@ -98,11 +105,14 @@ _openapi:
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
- 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.
@@ -129,10 +139,6 @@ _openapi:
- 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
- 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
contents: []
---
@@ -145,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"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"}]} 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 />
</>
);
}
+74 -12
View File
@@ -7,6 +7,12 @@ _openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
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: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
@@ -49,12 +55,19 @@ _openapi:
- 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
text) on SQLite, or a .db SQLite database built from the live data on
@@ -123,9 +136,16 @@ _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: 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.
@@ -139,6 +159,20 @@ _openapi:
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'
- depth: 2
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.
@@ -149,6 +183,11 @@ _openapi:
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: 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.'
@@ -181,11 +220,16 @@ _openapi:
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: 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 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.'
@@ -236,9 +280,15 @@ _openapi:
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: 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
@@ -249,6 +299,18 @@ _openapi:
- 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: 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
@@ -267,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 />
</>
);
}
@@ -15,11 +15,21 @@ _openapi:
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: 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'
- depth: 2
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
@@ -50,10 +60,18 @@ _openapi:
- 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: 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: 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.
@@ -83,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 />
</>
);
}
@@ -13,9 +13,10 @@ _openapi:
- depth: 2
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
client). Only when JSON subscription is enabled in settings. Default
@@ -30,9 +31,10 @@ _openapi:
headings:
- 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
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.'
@@ -1,6 +1,6 @@
---
title: Xray Settings
description: Xray configuration template, outbound management, Warp/Nord
description: Xray configuration template, outbound management, Warp/Nord/PIA
integration, and config testing. All endpoints under /panel/api/xray.
full: true
_openapi:
@@ -35,6 +35,10 @@ _openapi:
- 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'
@@ -62,6 +66,25 @@ _openapi:
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 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.
@@ -79,9 +102,9 @@ _openapi:
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
outbounds. Signals Xray to reload.
@@ -117,6 +140,9 @@ _openapi:
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),
@@ -139,6 +165,22 @@ _openapi:
- 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 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
@@ -151,9 +193,9 @@ _openapi:
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: 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
@@ -175,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 />
</>
);
}
+2
View File
@@ -241,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,
+3165 -462
View File
File diff suppressed because it is too large Load Diff
+192 -188
View File
@@ -1,46 +1,46 @@
{
"name": "3x-ui-frontend",
"version": "0.6.0",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "3x-ui-frontend",
"version": "0.6.0",
"version": "1.0.0",
"dependencies": {
"@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^5.9.1",
"@noble/hashes": "^2.3.0",
"@tanstack/react-query": "^5.101.4",
"@tanstack/react-query-devtools": "^5.101.4",
"@tanstack/react-query": "^5.102.2",
"@tanstack/react-query-devtools": "^5.102.2",
"antd": "^6.6.1",
"codemirror": "^6.0.2",
"dayjs": "^1.11.23",
"i18next": "^26.3.6",
"i18next": "^26.4.0",
"otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-hook-form": "^7.85.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.14",
"uplot": "^1.6.32",
"zod": "^4.4.3"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.5.9",
"@storybook/addon-docs": "^10.5.9",
"@storybook/addon-vitest": "^10.5.9",
"@storybook/react-vite": "^10.5.9",
"@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.18",
"@types/react-dom": "^19.2.4",
"@types/react-dom": "^19.2.5",
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.0.5",
"@vitejs/plugin-react": "^6.1.0",
"@vitest/browser-playwright": "4.1.11",
"@vitest/coverage-v8": "^4.1.11",
"husky": "^9.1.7",
@@ -51,9 +51,9 @@
"oxlint": "1.79.0",
"oxlint-tsgolint": "^7.0.2001",
"playwright": "^1.62.1",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"typescript": "7.0.2",
"vite": "8.2.1",
"vite": "8.2.2",
"vitest": "^4.1.11"
},
"engines": {
@@ -2051,9 +2051,9 @@
}
},
"node_modules/@oxc-resolver/binding-android-arm-eabi": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.24.2.tgz",
"integrity": "sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm-eabi/-/binding-android-arm-eabi-11.21.2.tgz",
"integrity": "sha512-xQoCRv+gKax9KTdwdaQNnAFOai8neay7g3jExDIORzhbrejwGSJaZNTdOJHR5ziLg2joMxOCMOFMo4zuxza2uQ==",
"cpu": [
"arm"
],
@@ -2065,9 +2065,9 @@
]
},
"node_modules/@oxc-resolver/binding-android-arm64": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm64/-/binding-android-arm64-11.24.2.tgz",
"integrity": "sha512-cl4icWaZFnLdg8m6qtnh5rBMuGbxc/ptStFHLeCNwr+2cZjkjNwQu/jYRS0CHlnPecOJMpuS5M6/BH+0J/YkEg==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-android-arm64/-/binding-android-arm64-11.21.2.tgz",
"integrity": "sha512-HF5oiE2L05yInPYCFD/4uxSrEZW4SuIfn99Y6L1xnJnzl066JR+MJs2rIdstw8A2MPlAKH+13dpFPNycjqzvGg==",
"cpu": [
"arm64"
],
@@ -2079,9 +2079,9 @@
]
},
"node_modules/@oxc-resolver/binding-darwin-arm64": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-arm64/-/binding-darwin-arm64-11.24.2.tgz",
"integrity": "sha512-At29QEMF6HajbQvgY8K6OXnHD1x9rad74xBEfmCB6ZqCGsdq75aK7tOYcTbOanMy8qdIBrfL3SMr3p/lfSlb9w==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-arm64/-/binding-darwin-arm64-11.21.2.tgz",
"integrity": "sha512-UX4u49CVCAD8QZNELaW8eMGgMAGwFWYEPbvNsh+3r/gs4NX3KfpiACMVwRQT0EuH3uat9hM5Zl+Ppm9pJD8tgg==",
"cpu": [
"arm64"
],
@@ -2093,9 +2093,9 @@
]
},
"node_modules/@oxc-resolver/binding-darwin-x64": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-x64/-/binding-darwin-x64-11.24.2.tgz",
"integrity": "sha512-A5Kqr1EUj4oIL5CF4WRssq/o5P0Y11cwoFouMRmQ7YnC/A8V93nv1nb7aSU8HwcgmXropjLNkVTl4MN87cu28Q==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-darwin-x64/-/binding-darwin-x64-11.21.2.tgz",
"integrity": "sha512-J9xPx7YBkrRmJ+xl561ztnMWEc1aOyjEIxBiGX1dVb3u7bGSnfObfcZk+Pd+uM0HZAPNsQ1xvD8j52A/uOSqNQ==",
"cpu": [
"x64"
],
@@ -2107,9 +2107,9 @@
]
},
"node_modules/@oxc-resolver/binding-freebsd-x64": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-freebsd-x64/-/binding-freebsd-x64-11.24.2.tgz",
"integrity": "sha512-R5xkRBRRz7ceH/P5Jrc6G7FmdUdgpLYyESFAUDVTNQ9K0sGPxcp4ljiwEwEqsvNcQ4sYbMRrWcHHBCu7ksAJVw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-freebsd-x64/-/binding-freebsd-x64-11.21.2.tgz",
"integrity": "sha512-fRlt7OvSaQkWj6+EDTVxawVxOlqJB2QSnBfkeCyK4RTvsGctbw3BiH2Tb7DzMs7bikc4BRBpvWP5zF9K8b54Zg==",
"cpu": [
"x64"
],
@@ -2121,9 +2121,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-arm-gnueabihf": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-11.24.2.tgz",
"integrity": "sha512-k/RuYL4L/R58IBn3wT5ma3Wh4k62bp1eYCFRWCmMsasUOqL+H6sW0VGFadEzKWXFFlz+2uIMoeMk9ySSZJHgbg==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-11.21.2.tgz",
"integrity": "sha512-gK+vPUcPQITkGwBKpZGrcDHSlU6eDGl7AQacxS2CEKAZIBHWkOVFeJwLZ4tYnA1acJqRM5lt7yYwPCVqGHIJ7A==",
"cpu": [
"arm"
],
@@ -2135,9 +2135,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-arm-musleabihf": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-11.24.2.tgz",
"integrity": "sha512-bnHAak3ujYfH5pKk4NieFNbvYvernfoQDgwLddbZ3OtMYrem87/qjlA+u+aKG0oZcqSLGCful/6/CEA+aeAgaA==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-11.21.2.tgz",
"integrity": "sha512-L/Rgas7SrOKy/z7IH+HxSFRqVO4PuLDKLEGKvnhoCBBq3UJ0YzGBou3qMzaAGgkJwsIvX2pBF+7ojzfUhLiZxQ==",
"cpu": [
"arm"
],
@@ -2149,9 +2149,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-arm64-gnu": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-11.24.2.tgz",
"integrity": "sha512-vDT3KHgzYp47gmtNOqL2VNhCyl5Zv643eyxm//A68J8DeUGXrvD1pZFiaT4jSfe+RInfnn1R2yVHye4enx6RnA==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-11.21.2.tgz",
"integrity": "sha512-CUEYvlX1Fk7E9kUMzuswru1J9HLxMwnpDeQGjQuI4ZH+iNCoa2X9T+pvyzrbsgl7WnIeTFTlNlHsRfVdf5g9/g==",
"cpu": [
"arm64"
],
@@ -2166,9 +2166,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-arm64-musl": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-musl/-/binding-linux-arm64-musl-11.24.2.tgz",
"integrity": "sha512-+kMlQvbzfyEYtu5FcjE4p+ttBLpKW4d/AsAsuE69BxV6V4twZJeIQZFfD8gh/wqglY0MkPSezWXQH0jBV13MUw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-arm64-musl/-/binding-linux-arm64-musl-11.21.2.tgz",
"integrity": "sha512-ViN1ZibQyxwC67GpoP33oo+S9UyUnkog13vzQb9+v9bCNvrVzJuk0MRdacjtv/9xfRMVF/eqHFyl8YOeykI10Q==",
"cpu": [
"arm64"
],
@@ -2183,9 +2183,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-ppc64-gnu": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-11.24.2.tgz",
"integrity": "sha512-shjfMhmZ3gq9fv/w7bi3PnZlgOPG+2QAOFf0BJF0EgBSIGZ6PMLN2zbGEblTUYB/NKVDRyYhE2ff3dJ1QqNPkA==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-11.21.2.tgz",
"integrity": "sha512-CU1sCqWnhGqYD5I1HedHk5pujrn7ssDkNB/AEQd/pd3D/EojVSgJUlpbafwIbyhia3PgIfkvdFpRPWSALzVumA==",
"cpu": [
"ppc64"
],
@@ -2200,9 +2200,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-riscv64-gnu": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-11.24.2.tgz",
"integrity": "sha512-zGelwFR5oRo+b69k8Lrzun86DyUHzfKN6cnjbR9l7Z7NIRznOE/2ZvPa1IUKqAL2PzAXOdwkfVqNvO1H2RlpAw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-11.21.2.tgz",
"integrity": "sha512-jWVyZtIHca4Gb96x7dag+y69vlei7ffjrsveLkmf2ZhqEAz6ZSBnY1GWvgZUaZlwZP62A3xD092BW97Q5VGc+g==",
"cpu": [
"riscv64"
],
@@ -2217,9 +2217,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-riscv64-musl": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-11.24.2.tgz",
"integrity": "sha512-qxZ1SWCXJY0eyhAlP6Lmo9F2Nrtx7EkYj9oCgL8apDPCwXwCEDA2U697bbT81JIc2IrVjxO4KX6WU2N+oN9Z4w==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-11.21.2.tgz",
"integrity": "sha512-LF29obFqNgBUgDX7rmUK7M4D0JQG5LxhYzn3xXmECcHU9aQAdWG7NiY052qybtesEdwHQXKNTWYQ7mTsybNvWg==",
"cpu": [
"riscv64"
],
@@ -2234,9 +2234,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-s390x-gnu": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-11.24.2.tgz",
"integrity": "sha512-sGCecF3cx2DFlH4t/z7ApnOnXqN48p5p5mlHDEnHTAukQa2P+qMVE4CwyWE9W+q/m3QJ7kKfGrIjax31f44oFQ==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-11.21.2.tgz",
"integrity": "sha512-+NYcm+cCHBbtdQQ3A4phQTSuVRYnNHz7wrl9XRAPEovcdoqi0mb1K5ZOl+jN54ZD+q1zz3V0vltbFJmzecJKmw==",
"cpu": [
"s390x"
],
@@ -2251,9 +2251,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-x64-gnu": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-gnu/-/binding-linux-x64-gnu-11.24.2.tgz",
"integrity": "sha512-k/VlMMcSzMlahb3/fENM4rTlsJ0s3fFROA0KXPBmKggqmTSaE383sl8F3KCOXPLmVsYfW6hCitMhXCEtNeZxxg==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-gnu/-/binding-linux-x64-gnu-11.21.2.tgz",
"integrity": "sha512-UQqZDdG2r2HhAOsZEgufkIWHPQ886IUyuJQkoZByvzhW8j51R4UNzGBJFkTiTnLhQnggwJRdJgFWK4uY6ZVIMw==",
"cpu": [
"x64"
],
@@ -2268,9 +2268,9 @@
]
},
"node_modules/@oxc-resolver/binding-linux-x64-musl": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-musl/-/binding-linux-x64-musl-11.24.2.tgz",
"integrity": "sha512-8hbnZyNi97b/8wapYaIF9+t9GmZKBW2vunaOc3h9HGJptH7b7XpvZqOTBSm/MpTjr7H497BlgOaSfLUdhmy2bw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-linux-x64-musl/-/binding-linux-x64-musl-11.21.2.tgz",
"integrity": "sha512-3Q9PMRjalWkT6NZ4jfujuqTCFwoWErg3y3BnOgb544B8IMw4PktiwWOigMfOHNRLMghZeJ7hpfpZf4CP7rV7Og==",
"cpu": [
"x64"
],
@@ -2285,9 +2285,9 @@
]
},
"node_modules/@oxc-resolver/binding-openharmony-arm64": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-openharmony-arm64/-/binding-openharmony-arm64-11.24.2.tgz",
"integrity": "sha512-MvyGik3a6pVgZ0t/kWlbmFxFLmXQJwgLsY2eYFHLpy0wGwRbfzeIGgDwQ3kXqE30z+kSXennRkCrT7TUvkptNg==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-openharmony-arm64/-/binding-openharmony-arm64-11.21.2.tgz",
"integrity": "sha512-Eljeq3ndtyKhM+Es8LITi4Zl2htzuRZcrPMF3kMCsrILztvU6AjZ3FuEhHHKobPUB9rMpzLpJP5bDqXI7r+iog==",
"cpu": [
"arm64"
],
@@ -2299,9 +2299,9 @@
]
},
"node_modules/@oxc-resolver/binding-wasm32-wasi": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-wasm32-wasi/-/binding-wasm32-wasi-11.24.2.tgz",
"integrity": "sha512-vHcssMPwO08RTvj/c0iOBz90attxyG3wQJ0dTcyEQK43LRpcdLWZlV5feBhv6Isn6ahbQIzHbCgfa81+RiML0Q==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-wasm32-wasi/-/binding-wasm32-wasi-11.21.2.tgz",
"integrity": "sha512-HGDbNsIywqc4LxU38+CTJNnB/6BF7rheWOJ259b4eE0aEnelYblC8x+1tEd63bp31fYne63RQz9Jb4yVnC7Yig==",
"cpu": [
"wasm32"
],
@@ -2309,18 +2309,18 @@
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "1.11.2",
"@emnapi/runtime": "1.11.2",
"@napi-rs/wasm-runtime": "^1.1.6"
"@emnapi/core": "1.11.0",
"@emnapi/runtime": "1.11.0",
"@napi-rs/wasm-runtime": "^1.1.5"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@oxc-resolver/binding-wasm32-wasi/node_modules/@emnapi/core": {
"version": "1.11.2",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.2.tgz",
"integrity": "sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.0.tgz",
"integrity": "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -2330,9 +2330,9 @@
}
},
"node_modules/@oxc-resolver/binding-wasm32-wasi/node_modules/@emnapi/runtime": {
"version": "1.11.2",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz",
"integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.0.tgz",
"integrity": "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -2352,9 +2352,9 @@
}
},
"node_modules/@oxc-resolver/binding-win32-arm64-msvc": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-11.24.2.tgz",
"integrity": "sha512-uokJqro2iBqkFvJdKQLP7d8/BUmFwESQFVmIJUQKj1Xn1a/LysJoe1vmeECLF5b3jsV8CAL5sEMJXX6SdK9Nhg==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-11.21.2.tgz",
"integrity": "sha512-iWx25CBEgH49iE9q5coEGI/jb1jl5kkCY9z6U5Og67xCkQ/WFMDc2J5U78+AE91SUxM2NqSLhJC8/PLfWnImww==",
"cpu": [
"arm64"
],
@@ -2366,9 +2366,9 @@
]
},
"node_modules/@oxc-resolver/binding-win32-x64-msvc": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-x64-msvc/-/binding-win32-x64-msvc-11.24.2.tgz",
"integrity": "sha512-UqGPmo56KDfLlfXFAFIrNflHT8tFxWGEivWg3Zeyp4Uy2NlKN1FGPr6/BxcLGG3+kZ6Wp14g5Uj+n71boqZfiw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/@oxc-resolver/binding-win32-x64-msvc/-/binding-win32-x64-msvc-11.21.2.tgz",
"integrity": "sha512-VPoCAhKvCQTlG7vxqaBXcmuvbh77BfnGXj8g0pbvVXpm1F/R8rDVwqIWcEbMzrI1JvJlm8v7T9uMVQb6UctMRg==",
"cpu": [
"x64"
],
@@ -4209,9 +4209,9 @@
"license": "MIT"
},
"node_modules/@storybook/addon-a11y": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/addon-a11y/-/addon-a11y-10.5.9.tgz",
"integrity": "sha512-MvXkoJIVRcZrqhWi+wynYAmFkvTWm5aHdJfYohhgPeEJVDRF91zejtOsN7zPRE/lQvBDY+IiomKxeRN3UhWNVw==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/addon-a11y/-/addon-a11y-10.5.10.tgz",
"integrity": "sha512-RpRQV5xUbrl6hCiNrd5FSMIo6pnRZ0VZxWvEW/ASLcreGkKUW5jl2AeLCe5YROE2i80s/dU+6VPzOYKrwWNFbQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4223,20 +4223,20 @@
"url": "https://opencollective.com/storybook"
},
"peerDependencies": {
"storybook": "^10.5.9"
"storybook": "^10.5.10"
}
},
"node_modules/@storybook/addon-docs": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/addon-docs/-/addon-docs-10.5.9.tgz",
"integrity": "sha512-8sFsMkZYrrdqCLdV+hnwTwDF7RaBsBPRwl4wfc8ve9Q/7Yhi5REe/Xjvd8x1yn6fBPPw9tnID9dx6Agdnr81fw==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/addon-docs/-/addon-docs-10.5.10.tgz",
"integrity": "sha512-06JoK3/a7FWI/6GzuidJP9iHp1/Vejboe6lzS1jW+d8ItpecriBt+oXh1VNmUM7i7PjI6pZnet+j51QnLyeOoQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@mdx-js/react": "^3.0.0",
"@storybook/csf-plugin": "10.5.9",
"@storybook/csf-plugin": "10.5.10",
"@storybook/icons": "^2.0.2",
"@storybook/react-dom-shim": "10.5.9",
"@storybook/react-dom-shim": "10.5.10",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"ts-dedent": "^2.0.0"
@@ -4247,7 +4247,7 @@
},
"peerDependencies": {
"@types/react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"storybook": "^10.5.9"
"storybook": "^10.5.10"
},
"peerDependenciesMeta": {
"@types/react": {
@@ -4256,9 +4256,9 @@
}
},
"node_modules/@storybook/addon-vitest": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/addon-vitest/-/addon-vitest-10.5.9.tgz",
"integrity": "sha512-TgHczbDANprH9bEj+Z/DZ4b2LaCHpNrBdMOWK7gd+ZRGZz0ZZnGm8H5WoIh2uW4AHYibZmYCyWDSf69Plblz2w==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/addon-vitest/-/addon-vitest-10.5.10.tgz",
"integrity": "sha512-JNQ9DSkLfxC8qqytBCej91zBExIZ7z97B410U2zgfQPki4HkI9Ffz97a15f5yhVZ79ppIrZ/ssI+WcyWn0ykXQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4273,7 +4273,7 @@
"@vitest/browser": "^3.0.0 || ^4.0.0",
"@vitest/browser-playwright": "^4.0.0",
"@vitest/runner": "^3.0.0 || ^4.0.0",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"vitest": "^3.0.0 || ^4.0.0"
},
"peerDependenciesMeta": {
@@ -4292,13 +4292,13 @@
}
},
"node_modules/@storybook/builder-vite": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/builder-vite/-/builder-vite-10.5.9.tgz",
"integrity": "sha512-Zg4JbGQiHFPGlFJ9HM+XPgzKmU/RFPCymhohVRJhBBYfmgaQgz0flWWzscseCDpl638MNd8/r/H+nwuoBgSYDg==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/builder-vite/-/builder-vite-10.5.10.tgz",
"integrity": "sha512-O4GgIP0tKLRueom3EmU3OaBUHKjNYj+jkOvmTIkn3PYTiWVkCuHqSKEs4ADvRyaQuLH+peHhFe4JtkNC9KbtrQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@storybook/csf-plugin": "10.5.9",
"@storybook/csf-plugin": "10.5.10",
"ts-dedent": "^2.0.0"
},
"funding": {
@@ -4306,14 +4306,14 @@
"url": "https://opencollective.com/storybook"
},
"peerDependencies": {
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
}
},
"node_modules/@storybook/csf-plugin": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/csf-plugin/-/csf-plugin-10.5.9.tgz",
"integrity": "sha512-4H5QIHQVtQYCuL43GCRLGjNQhZpQg9gL03ja0DV80kO2Dn9LEt6ol87bSnSjn4VDgcAXtgTzXFvRLknfVgAAqg==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/csf-plugin/-/csf-plugin-10.5.10.tgz",
"integrity": "sha512-TaCLBrqVEr767+w58QDotDUiCTuE5cyRJuRcDlsKQyUIyGBv+lYD3lu8wBiVCYxgIjB/gu9HmqiC+0yx1rHzaw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -4326,7 +4326,7 @@
"peerDependencies": {
"esbuild": "*",
"rollup": "*",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"vite": "*",
"webpack": "*"
},
@@ -4363,14 +4363,14 @@
}
},
"node_modules/@storybook/react": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/react/-/react-10.5.9.tgz",
"integrity": "sha512-kApGOuNT26NkpioTsr1iT/Q2c44tA7OIsNUSyFqtT7W8k3fRn/jQWfrDegYxty0WG0wxdNMZq2ndRfOOF8HaHw==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/react/-/react-10.5.10.tgz",
"integrity": "sha512-4MBV5e1SXIMfPynLHzr+Mp0dwGv/FW1bklWAsS4ynBOAbC98W9p/I9vqBnUctsvE3BJkhzHQQyPwMHL5tTcHVA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@storybook/global": "^5.0.0",
"@storybook/react-dom-shim": "10.5.9",
"@storybook/react-dom-shim": "10.5.10",
"react-docgen": "^8.0.2",
"react-docgen-typescript": "^2.2.2"
},
@@ -4383,7 +4383,7 @@
"@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"typescript": ">= 4.9.x"
},
"peerDependenciesMeta": {
@@ -4399,9 +4399,9 @@
}
},
"node_modules/@storybook/react-dom-shim": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/react-dom-shim/-/react-dom-shim-10.5.9.tgz",
"integrity": "sha512-7qZD6CSa64p1m/zX9tG4ALcEHlEk0Bx+5++4RL3MFlRCgCFfAomXsCHTzF0RyF8cI4vl+hS7Y0ryjQchVs6UQA==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/react-dom-shim/-/react-dom-shim-10.5.10.tgz",
"integrity": "sha512-rbu62ILo/VE3iXKmu+kWXFpD1H1Lwi0f19q/x7JnDsD2dxKS9w5znLEqPIq2qxpzi/wjjIb2iUP1cRG1d/9W5A==",
"dev": true,
"license": "MIT",
"funding": {
@@ -4413,7 +4413,7 @@
"@types/react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"storybook": "^10.5.9"
"storybook": "^10.5.10"
},
"peerDependenciesMeta": {
"@types/react": {
@@ -4425,16 +4425,16 @@
}
},
"node_modules/@storybook/react-vite": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/@storybook/react-vite/-/react-vite-10.5.9.tgz",
"integrity": "sha512-mDI+UssrOEP8IwgBsefLG+gqW1gZbZEPbpH5PoHK/P1WPi8BfrLEqrFi9H9wmMkal/Vh8SmL1awgOi0ir3XwcQ==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/@storybook/react-vite/-/react-vite-10.5.10.tgz",
"integrity": "sha512-xOztxefUnqKeuyvcnjspqmlDnER4cExL+liltrpdXLPJVqfFNr9lgM49FyEPajzsUVG9W/vHJWjbaQGGu1UsYQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@joshwooding/vite-plugin-react-docgen-typescript": "^0.7.0",
"@rollup/pluginutils": "^5.0.2",
"@storybook/builder-vite": "10.5.9",
"@storybook/react": "10.5.9",
"@storybook/builder-vite": "10.5.10",
"@storybook/react": "10.5.10",
"empathic": "^2.0.0",
"magic-string": "^0.30.0",
"react-docgen": "^8.0.2",
@@ -4448,7 +4448,7 @@
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"typescript": ">= 4.9.x",
"vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
},
@@ -5168,9 +5168,9 @@
}
},
"node_modules/@tanstack/query-core": {
"version": "5.101.4",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.101.4.tgz",
"integrity": "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw==",
"version": "5.102.2",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.102.2.tgz",
"integrity": "sha512-zQ5794PXBlV5Wl7N23SR1/Ss+wPE/h2Ye4XlKpm3omN8i8b/Fd4DAdqpLS2AXj5M/RMObt3k5qy3E7kzt/AvBA==",
"license": "MIT",
"funding": {
"type": "github",
@@ -5178,9 +5178,9 @@
}
},
"node_modules/@tanstack/query-devtools": {
"version": "5.101.4",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.101.4.tgz",
"integrity": "sha512-z5IPHnDX3aUWeTWlRKLyooBQekaCAw4xRpZqPQ390RiWTDBcTynjpPT221BArw0u2+pnQMdGvPQI9YNNubBcmA==",
"version": "5.102.2",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.102.2.tgz",
"integrity": "sha512-sbRVlyRWfhKm2z4cnTdHydHiaMYMcH1mCYVNwreE9oR08VmyCsSz97fhy1253gKB4ycMcaRjbfUxQLO0SSLFYw==",
"license": "MIT",
"funding": {
"type": "github",
@@ -5188,12 +5188,12 @@
}
},
"node_modules/@tanstack/react-query": {
"version": "5.101.4",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.101.4.tgz",
"integrity": "sha512-yRg2pfOCxIs4ZJW3XYYHU/WgtD04FHSnfHlpRT7h7pR77hwkdRG4wxbKe4aq6P0RvXUTBSQpQeadS1SUYUe+KA==",
"version": "5.102.2",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.102.2.tgz",
"integrity": "sha512-KxU8ZyOEuJ81eTSgXa8GQbk/jO/rz0elYtNKt3VMtM2pRjeO8ADIu7sqqmEjFKJKqco9h2N1ojIDuHs6VfDItQ==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.101.4"
"@tanstack/query-core": "5.102.2"
},
"funding": {
"type": "github",
@@ -5204,19 +5204,19 @@
}
},
"node_modules/@tanstack/react-query-devtools": {
"version": "5.101.4",
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.101.4.tgz",
"integrity": "sha512-VeK2gtmfj7kvRBjtxS7TKxt/6qKhn8VzabY4UiYMr7NV9CddjSRYRgeYyld+NpjAkgMV9dd+2Qdr8ah5I03NeA==",
"version": "5.102.2",
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.102.2.tgz",
"integrity": "sha512-5KzH1NAdess98Jgbo8R0sraP0yto49+eGgSGu6umvrLbXPNdsNJ7iOgAiXegBOoWJrHygp6hW01L2U6MvSIT5Q==",
"license": "MIT",
"dependencies": {
"@tanstack/query-devtools": "5.101.4"
"@tanstack/query-devtools": "5.102.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"@tanstack/react-query": "^5.101.4",
"@tanstack/react-query": "^5.102.2",
"react": "^18 || ^19"
}
},
@@ -5456,9 +5456,9 @@
}
},
"node_modules/@types/react-dom": {
"version": "19.2.4",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
"version": "19.2.5",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.5.tgz",
"integrity": "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg==",
"dev": true,
"license": "MIT",
"peerDependencies": {
@@ -5839,9 +5839,9 @@
}
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.5.tgz",
"integrity": "sha512-BOVzne/NL162sMdResB25mUv+vWMF5NoAjNf09TeGlE7ZpszZWSD3winycicLJw72yeVsoCn/2kOhEuCvEShMA==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.0.tgz",
"integrity": "sha512-qd2BzUBehkov86WFhg0JkEFEYyCLG9uPCe6qWTY/kRlss9OvJrOF2UbIWT7p+8IzZHkEu0DNGHc4HSv+JdDLsw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -5853,6 +5853,7 @@
"peerDependencies": {
"@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
"babel-plugin-react-compiler": "^1.0.0",
"oxc-transform-react": "^0.145.0",
"vite": "^8.0.0"
},
"peerDependenciesMeta": {
@@ -5861,6 +5862,9 @@
},
"babel-plugin-react-compiler": {
"optional": true
},
"oxc-transform-react": {
"optional": true
}
}
},
@@ -6390,9 +6394,9 @@
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.15",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.15.tgz",
"integrity": "sha512-FwMjJJ7HnyZpWe+oWxegG0fezZyBZUagI5LZEoO3GCbtbKNwRfMH9Ue5d5v01PNePBy1QSfPSDTTeVL0Hb9EzA==",
"version": "2.11.18",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.18.tgz",
"integrity": "sha512-1iEmLEYSiE1SeBoAfPo/Mnx3PzfzHUkDK61ASkCpuk3YXugYLH5DYK1SzqV55F8FMI6s0F+/tCP7Polz1QRjxw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -7050,9 +7054,9 @@
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.411",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.411.tgz",
"integrity": "sha512-gglkxzokjHfawpGxq75XdBV2/l3BAPzrsMs70qgaZdTW5rpV1tC4MdgJVP9fN126bODA4ZJQkn1wryEzJyQXIg==",
"version": "1.5.413",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.413.tgz",
"integrity": "sha512-F1XPKvt7HVfly5WND90ec16nFsdr4g5x/cVUP3EqjeyXynupabGDqpMa84wwvuYGDnldXLBz6DLXyZXWO9TPvw==",
"dev": true,
"license": "ISC"
},
@@ -7651,9 +7655,9 @@
}
},
"node_modules/i18next": {
"version": "26.3.6",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.3.6.tgz",
"integrity": "sha512-Bu5Z2nAXgfVyM8xvW3jk9EKRIuX37PudsrBViThNFx7CR7aaYTpP01cxNB/E4c4UUzTDiAZRstEhsRfPOL/8xA==",
"version": "26.4.0",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.4.0.tgz",
"integrity": "sha512-rsmK5bFqsD1AetSFSIa43wtNR4WpvvH4p0tLEsTxkC7QTrfdFm06nbQ95bh8Og4wwaCnUEcm9DVYL2cgxitiQg==",
"funding": [
{
"type": "individual",
@@ -8826,34 +8830,34 @@
}
},
"node_modules/oxc-resolver": {
"version": "11.24.2",
"resolved": "https://registry.npmjs.org/oxc-resolver/-/oxc-resolver-11.24.2.tgz",
"integrity": "sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==",
"version": "11.21.2",
"resolved": "https://registry.npmjs.org/oxc-resolver/-/oxc-resolver-11.21.2.tgz",
"integrity": "sha512-w5tLwYN3Zo24w5EeWJjJWZOwhYqTtC8PS2B1tIt7BZUuqTIcU07sQValbDw+rq7+AuAGzOHklgK+ifsy4lpXfw==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/Boshen"
},
"optionalDependencies": {
"@oxc-resolver/binding-android-arm-eabi": "11.24.2",
"@oxc-resolver/binding-android-arm64": "11.24.2",
"@oxc-resolver/binding-darwin-arm64": "11.24.2",
"@oxc-resolver/binding-darwin-x64": "11.24.2",
"@oxc-resolver/binding-freebsd-x64": "11.24.2",
"@oxc-resolver/binding-linux-arm-gnueabihf": "11.24.2",
"@oxc-resolver/binding-linux-arm-musleabihf": "11.24.2",
"@oxc-resolver/binding-linux-arm64-gnu": "11.24.2",
"@oxc-resolver/binding-linux-arm64-musl": "11.24.2",
"@oxc-resolver/binding-linux-ppc64-gnu": "11.24.2",
"@oxc-resolver/binding-linux-riscv64-gnu": "11.24.2",
"@oxc-resolver/binding-linux-riscv64-musl": "11.24.2",
"@oxc-resolver/binding-linux-s390x-gnu": "11.24.2",
"@oxc-resolver/binding-linux-x64-gnu": "11.24.2",
"@oxc-resolver/binding-linux-x64-musl": "11.24.2",
"@oxc-resolver/binding-openharmony-arm64": "11.24.2",
"@oxc-resolver/binding-wasm32-wasi": "11.24.2",
"@oxc-resolver/binding-win32-arm64-msvc": "11.24.2",
"@oxc-resolver/binding-win32-x64-msvc": "11.24.2"
"@oxc-resolver/binding-android-arm-eabi": "11.21.2",
"@oxc-resolver/binding-android-arm64": "11.21.2",
"@oxc-resolver/binding-darwin-arm64": "11.21.2",
"@oxc-resolver/binding-darwin-x64": "11.21.2",
"@oxc-resolver/binding-freebsd-x64": "11.21.2",
"@oxc-resolver/binding-linux-arm-gnueabihf": "11.21.2",
"@oxc-resolver/binding-linux-arm-musleabihf": "11.21.2",
"@oxc-resolver/binding-linux-arm64-gnu": "11.21.2",
"@oxc-resolver/binding-linux-arm64-musl": "11.21.2",
"@oxc-resolver/binding-linux-ppc64-gnu": "11.21.2",
"@oxc-resolver/binding-linux-riscv64-gnu": "11.21.2",
"@oxc-resolver/binding-linux-riscv64-musl": "11.21.2",
"@oxc-resolver/binding-linux-s390x-gnu": "11.21.2",
"@oxc-resolver/binding-linux-x64-gnu": "11.21.2",
"@oxc-resolver/binding-linux-x64-musl": "11.21.2",
"@oxc-resolver/binding-openharmony-arm64": "11.21.2",
"@oxc-resolver/binding-wasm32-wasi": "11.21.2",
"@oxc-resolver/binding-win32-arm64-msvc": "11.21.2",
"@oxc-resolver/binding-win32-x64-msvc": "11.21.2"
}
},
"node_modules/oxfmt": {
@@ -9381,9 +9385,9 @@
}
},
"node_modules/react-hook-form": {
"version": "7.85.0",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.85.0.tgz",
"integrity": "sha512-U2MTriFXnclmV4rOE20p2DcRFv5WEg3FIcBFOKcOLFHDVvGIMPvLTkTWefUsonmlaVy23khVDxDWym6uJVGOzw==",
"version": "7.86.0",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.86.0.tgz",
"integrity": "sha512-4kbWJrh5jPZt1+YqVcXcGKffGcXV/XVbozknLh0Yjh0KhpoAkus21TAQhzRYqNwFkkObmnSvRlZZ3GT+ehoIrA==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
@@ -9397,12 +9401,12 @@
}
},
"node_modules/react-i18next": {
"version": "17.0.11",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.11.tgz",
"integrity": "sha512-cDtkXgxjuFTWUH6V+aQn1Ve5vDiUztCNPWW5GtSHDccsgRXO1nE6QFWCEmc1KAutrb3OUv87wFShJL5RhUwPXg==",
"version": "17.0.12",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.12.tgz",
"integrity": "sha512-lFWPEGkxQ6RhusdUkysFBD58VHfSSzvHBzqMgN0SvfVpdQGfwtNkStTqdy08/sJd7s807qqutgx93fRpD0DJ3Q==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.2",
"@babel/runtime": "^7.29.7",
"html-parse-stringify": "^4.0.1",
"use-sync-external-store": "^1.6.0"
},
@@ -9999,9 +10003,9 @@
"license": "MIT"
},
"node_modules/storybook": {
"version": "10.5.9",
"resolved": "https://registry.npmjs.org/storybook/-/storybook-10.5.9.tgz",
"integrity": "sha512-UfdMKSjEhIKr8LbqYyIE5r7vT/drL/PxN75YaouJ+UG0FssEy6cf49OdTF3kstAqVMHskc+zEqyRoiQHZXHwgA==",
"version": "10.5.10",
"resolved": "https://registry.npmjs.org/storybook/-/storybook-10.5.10.tgz",
"integrity": "sha512-Rz8k9ejFHsi7lbtJTaxZlhCUz4GkbJIKEoKDjXeLfr/ZhXip73E6keKxW0KH8iGeKiCqHAbJCV4YIQrxTOLiig==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -10017,7 +10021,7 @@
"jsonc-parser": "^3.3.1",
"open": "^10.2.0",
"oxc-parser": "^0.127.0",
"oxc-resolver": "^11.19.1",
"oxc-resolver": "11.21.2",
"recast": "^0.23.5",
"semver": "^7.7.3",
"use-sync-external-store": "^1.5.0",
@@ -10701,16 +10705,16 @@
}
},
"node_modules/vite": {
"version": "8.2.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz",
"integrity": "sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==",
"version": "8.2.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",
"integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.5",
"postcss": "^8.5.25",
"rolldown": "~1.2.1",
"postcss": "^8.5.26",
"rolldown": "~1.2.4",
"tinyglobby": "^0.2.17"
},
"bin": {
@@ -10727,7 +10731,7 @@
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"@vitejs/devtools": "^0.4.0",
"@vitejs/devtools": "^0.4.0 || ^0.5.0",
"esbuild": "^0.27.0 || ^0.28.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
+14 -14
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": {
@@ -39,34 +39,34 @@
"@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^5.9.1",
"@noble/hashes": "^2.3.0",
"@tanstack/react-query": "^5.101.4",
"@tanstack/react-query-devtools": "^5.101.4",
"@tanstack/react-query": "^5.102.2",
"@tanstack/react-query-devtools": "^5.102.2",
"antd": "^6.6.1",
"codemirror": "^6.0.2",
"dayjs": "^1.11.23",
"i18next": "^26.3.6",
"i18next": "^26.4.0",
"otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-hook-form": "^7.85.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.14",
"uplot": "^1.6.32",
"zod": "^4.4.3"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.5.9",
"@storybook/addon-docs": "^10.5.9",
"@storybook/addon-vitest": "^10.5.9",
"@storybook/react-vite": "^10.5.9",
"@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.18",
"@types/react-dom": "^19.2.4",
"@types/react-dom": "^19.2.5",
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.0.5",
"@vitejs/plugin-react": "^6.1.0",
"@vitest/browser-playwright": "4.1.11",
"@vitest/coverage-v8": "^4.1.11",
"husky": "^9.1.7",
@@ -77,9 +77,9 @@
"oxlint": "1.79.0",
"oxlint-tsgolint": "^7.0.2001",
"playwright": "^1.62.1",
"storybook": "^10.5.9",
"storybook": "^10.5.10",
"typescript": "7.0.2",
"vite": "8.2.1",
"vite": "8.2.2",
"vitest": "^4.1.11"
},
"overrides": {
+788 -3
View File
@@ -241,6 +241,9 @@
"subJsonMux": {
"type": "string"
},
"subJsonObservatory": {
"type": "string"
},
"subJsonPath": {
"type": "string"
},
@@ -438,6 +441,7 @@
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
"subJsonObservatory",
"subJsonPath",
"subJsonRules",
"subJsonURI",
@@ -716,6 +720,9 @@
"subJsonMux": {
"type": "string"
},
"subJsonObservatory": {
"type": "string"
},
"subJsonPath": {
"type": "string"
},
@@ -920,6 +927,7 @@
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
"subJsonObservatory",
"subJsonPath",
"subJsonRules",
"subJsonURI",
@@ -962,6 +970,36 @@
],
"type": "object"
},
"AmneziaWGLogs": {
"description": "AmneziaWGLogs is what the overview's AmneziaWG log view renders: the live\nper-peer activity of every running embedded interface, plus the panel's\nown recent AmneziaWG lifecycle log lines that explain a peer being absent\nfrom Peers at all.",
"properties": {
"events": {
"example": [
"2025/01/01 12:00:00 amneziawg: started interface awg1 for inbound 1"
],
"items": {
"type": "string"
},
"type": "array"
},
"peers": {
"items": {
"$ref": "#/components/schemas/PeerActivity"
},
"type": "array"
},
"running": {
"example": true,
"type": "boolean"
}
},
"required": [
"events",
"peers",
"running"
],
"type": "object"
},
"ApiToken": {
"properties": {
"createdAt": {
@@ -1056,6 +1094,16 @@
},
"type": "array"
},
"allowedIPsByInbound": {
"additionalProperties": {
"items": {
"type": "string"
},
"type": "array"
},
"description": "AllowedIPsByInbound optionally overrides AllowedIPs on a per-inbound\nbasis, keyed by inbound id. Lets one identity attached to both\nWireGuard and AmneziaWG carry two genuinely different addresses in a\nsingle Create/Update call instead of the shared AllowedIPs field\nbeing broadcast to every attached tunnel inbound. Absent/unset for a\ngiven inbound id falls back to the shared AllowedIPs exactly as\nbefore -- fully backward compatible for callers that never set this.",
"type": "object"
},
"auth": {
"description": "Auth password (Hysteria)",
"type": "string"
@@ -1086,6 +1134,10 @@
"description": "Flow control (XTLS)",
"type": "string"
},
"forwardedPorts": {
"description": "AmneziaWG per-client port-forwarding spec, e.g. \"80,443,8000-8100\"",
"type": "string"
},
"group": {
"description": "Logical grouping label",
"type": "string"
@@ -1250,6 +1302,9 @@
"flow": {
"type": "string"
},
"forwardedPorts": {
"type": "string"
},
"group": {
"type": "string"
},
@@ -1328,6 +1383,7 @@
"enable",
"expiryTime",
"flow",
"forwardedPorts",
"group",
"id",
"keepAlive",
@@ -2071,7 +2127,8 @@
"mixed",
"tunnel",
"tun",
"mtproto"
"mtproto",
"amneziawg"
],
"example": "vless",
"type": "string"
@@ -2223,6 +2280,15 @@
},
"InboundOption": {
"properties": {
"awgServer": {
"allOf": [
{
"$ref": "#/components/schemas/ServerSettings"
}
],
"description": "AwgServer carries the full AmneziaWG server block (keys, subnet,\nobfuscation params) so the clients page can render a downloadable\nper-client .conf without a second round trip.",
"nullable": true
},
"enable": {
"example": true,
"type": "boolean"
@@ -2905,6 +2971,68 @@
],
"type": "object"
},
"PeerActivity": {
"description": "PeerActivity is one peer's live embedded-Device-reported state, the\ncounterpart of an Xray access-log entry: a tunnel logs no requests, only\nhandshakes and bytes.",
"properties": {
"allowedIPs": {
"example": "10.8.1.2/32",
"type": "string"
},
"down": {
"example": 4194304,
"format": "int64",
"type": "integer"
},
"email": {
"example": "peer@example.com",
"type": "string"
},
"endpoint": {
"example": "203.0.113.9:51820",
"type": "string"
},
"handshake": {
"description": "Handshake is unix milliseconds, 0 when the peer has never connected.",
"example": 1735732800000,
"format": "int64",
"type": "integer"
},
"inboundId": {
"example": 1,
"type": "integer"
},
"interface": {
"example": "awg1",
"type": "string"
},
"online": {
"example": true,
"type": "boolean"
},
"tag": {
"example": "inbound-51820",
"type": "string"
},
"up": {
"example": 1048576,
"format": "int64",
"type": "integer"
}
},
"required": [
"allowedIPs",
"down",
"email",
"endpoint",
"handshake",
"inboundId",
"interface",
"online",
"tag",
"up"
],
"type": "object"
},
"ProbeResultUI": {
"properties": {
"cpuPct": {
@@ -3071,6 +3199,150 @@
],
"type": "object"
},
"ServerSettings": {
"description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.",
"properties": {
"contentPaddingAddition": {
"type": "string"
},
"disableCookies": {
"type": "boolean"
},
"externalInterface": {
"description": "ExternalInterface, IPv6Enabled, and IPv6ExternalInterface are live\nagain as of Phase 3.5 -- see the matching fields on Instance for what\nthey gate (internal/amneziawgnet's IPv6-address-alias mechanism).\nIPv6Subnet was never actually vestigial either: InstanceFromInbound\nalready consumes it (via serverAddressV6) to build the server's own\ntunnel address, same as always. Only RouteThroughXray, below, remains\ngenuinely vestigial as of the hard cutover to the embedded path\n(internal/amneziawgnet) -- read from existing stored settings for\nbackward compatibility, but not acted on by anything.",
"type": "string"
},
"h1": {
"type": "string"
},
"h2": {
"type": "string"
},
"h3": {
"type": "string"
},
"h4": {
"type": "string"
},
"headerProtectionKey": {
"description": "HeaderProtectionKey and ContentPaddingAddition are AmneziaWG 3.0\nfields, flat and top-level for the same tools/openapigen reason as\nthe block above; Obfuscation() below folds them back into\nObfuscation31's own identically named fields.\nHeaderProtectionKey is a base64 32-byte key; empty (the default)\ndisables AWG 3.0 header protection. A non-empty value requires\nevery one of S1-S4 above to be >= 12 -- ValidateObfuscation\nenforces this at save time, not just at IpcSet time.\nContentPaddingAddition is a \"low-high\" range or bare integer, the\nsame grammar and uint32 cap as H1-H4.",
"type": "string"
},
"i1": {
"type": "string"
},
"i2": {
"type": "string"
},
"i3": {
"type": "string"
},
"i4": {
"type": "string"
},
"i5": {
"type": "string"
},
"ipv6Enabled": {
"type": "boolean"
},
"ipv6ExternalInterface": {
"type": "string"
},
"ipv6Subnet": {
"type": "string"
},
"jc": {
"description": "Obfuscation31's fields, repeated flat (not embedded) rather than\nnested under their own key: encoding/json would happily inline an\nembedded Obfuscation31 the same way, but the frontend's Go->Zod/TS\ngenerator (tools/openapigen) does not — it emits a genuinely nested\n`obfuscation31` object, which would silently diverge from the real\nwire JSON. See Obfuscation() below for the manager-facing conversion.",
"type": "integer"
},
"jmax": {
"type": "integer"
},
"jmin": {
"type": "integer"
},
"keepaliveTimeout": {
"type": "string"
},
"maxHandshakeAttempts": {
"type": "string"
},
"mtu": {
"type": "integer"
},
"primaryDns": {
"description": "PrimaryDNS/SecondaryDNS seed client configs' DNS line. Blank is\nmeaningful, so no omitempty: a dropped key resurrects frontend defaults.",
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"randomTrailers": {
"description": "RandomTrailers/DisableCookies mirror Instance's identically named\nAmneziaWG 3.1 fields -- see that type's own doc comment for the real\nprotocol/interop details. Both real bool fields (not omitempty):\nbuildUAPIConfig always emits both lines explicitly so the\nreconfigure-in-place diff correctly notices a true->false edit, not\njust false->true.",
"type": "boolean"
},
"rejectAfterTime": {
"type": "string"
},
"rekeyAfterTime": {
"description": "RekeyAfterTime/RekeyTimeout/RejectAfterTime/KeepaliveTimeout/\nMaxHandshakeAttempts mirror Instance's identically named fields --\nsee that type's own doc comment for the grammar/width/real-default\ndetails. Flat and top-level for the same tools/openapigen reason as\nthe rest of this struct.",
"type": "string"
},
"rekeyTimeout": {
"type": "string"
},
"routeThroughXray": {
"type": "boolean"
},
"s1": {
"type": "integer"
},
"s2": {
"type": "integer"
},
"s3": {
"type": "integer"
},
"s4": {
"type": "integer"
},
"secondaryDns": {
"type": "string"
},
"subnetCidr": {
"type": "integer"
},
"subnetIp": {
"type": "string"
}
},
"required": [
"disableCookies",
"h1",
"h2",
"h3",
"h4",
"jc",
"jmax",
"jmin",
"primaryDns",
"privateKey",
"publicKey",
"randomTrailers",
"s1",
"s2",
"s3",
"s4",
"secondaryDns",
"subnetCidr",
"subnetIp"
],
"type": "object"
},
"Setting": {
"description": "Setting stores key-value configuration settings for the 3x-ui panel.",
"properties": {
@@ -3091,6 +3363,71 @@
],
"type": "object"
},
"SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": {
"createdAt": {
"example": 1710000000000,
"format": "int64",
"type": "integer"
},
"enabled": {
"description": "No gorm default:true — a bool default makes an explicit false at insert\ncollapse back to the column default (zero value is skipped).",
"example": true,
"type": "boolean"
},
"id": {
"example": 1,
"type": "integer"
},
"inboundIds": {
"example": [
1,
3
],
"items": {
"type": "integer"
},
"type": "array"
},
"remark": {
"example": "auto-fastest",
"maxLength": 256,
"type": "string"
},
"sortOrder": {
"example": 1,
"minimum": 1,
"type": "integer"
},
"strategy": {
"enum": [
"leastLoad",
"leastPing",
"random",
"roundRobin"
],
"example": "random",
"type": "string"
},
"updatedAt": {
"example": 1710000000000,
"format": "int64",
"type": "integer"
}
},
"required": [
"createdAt",
"enabled",
"id",
"inboundIds",
"remark",
"sortOrder",
"strategy",
"updatedAt"
],
"type": "object"
},
"User": {
"description": "User represents a user account in the 3x-ui panel.",
"properties": {
@@ -3160,7 +3497,11 @@
},
{
"name": "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."
},
{
"name": "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."
},
{
"name": "Subscription Server",
@@ -3531,6 +3872,7 @@
"success": true,
"obj": [
{
"awgServer": null,
"enable": true,
"id": 1,
"listen": "",
@@ -5583,6 +5925,82 @@
}
}
},
"/panel/api/server/amneziawglogs/{count}": {
"post": {
"tags": [
"Server"
],
"summary": "Return live AmneziaWG peer activity (handshake, endpoint, transfer) plus the panels own AmneziaWG event lines.",
"operationId": "post_panel_api_server_amneziawglogs_count",
"parameters": [
{
"name": "count",
"in": "path",
"required": true,
"description": "Maximum peer rows and event lines to return.",
"schema": {
"type": "integer"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/AmneziaWGLogs"
}
}
},
"example": {
"success": true,
"obj": {
"events": [
"2025/01/01 12:00:00 amneziawg: started interface awg1 for inbound 1"
],
"peers": [
{
"allowedIPs": "10.8.1.2/32",
"down": 4194304,
"email": "peer@example.com",
"endpoint": "203.0.113.9:51820",
"handshake": 1735732800000,
"inboundId": 1,
"interface": "awg1",
"online": true,
"tag": "inbound-51820",
"up": 1048576
}
],
"running": true
}
}
}
}
}
}
}
},
"/panel/api/server/importDB": {
"post": {
"tags": [
@@ -6245,8 +6663,9 @@
"tags": [
"Clients"
],
"summary": "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.",
"summary": "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.",
"operationId": "post_panel_api_clients_add",
"description": "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.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **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\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **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\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard 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.",
"requestBody": {
"required": true,
"content": {
@@ -6423,6 +6842,7 @@
],
"summary": "Attach an existing client to one or more additional inbounds. Body is JSON.",
"operationId": "post_panel_api_clients_email_attach",
"description": "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.",
"parameters": [
{
"name": "email",
@@ -7987,6 +8407,56 @@
}
}
},
"/panel/api/clients/hwids/{email}/{id}": {
"delete": {
"tags": [
"Clients"
],
"summary": "Remove a single registered HWID device by its id, freeing one slot under the HWID limit.",
"operationId": "delete_panel_api_clients_hwids_email_id",
"parameters": [
{
"name": "email",
"in": "path",
"required": true,
"description": "Client email.",
"schema": {
"type": "string"
}
},
{
"name": "id",
"in": "path",
"required": true,
"description": "Device id, from the list endpoint.",
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/clients/onlines": {
"post": {
"tags": [
@@ -11091,6 +11561,47 @@
}
}
},
"/panel/api/xray/pia/{action}": {
"post": {
"tags": [
"Xray Settings"
],
"summary": "Manage PIA WireGuard integration. The action parameter selects the operation.",
"operationId": "post_panel_api_xray_pia_action",
"parameters": [
{
"name": "action",
"in": "path",
"required": true,
"description": "countries — list available countries from the signed PIA server list. servers — list regions and WireGuard servers in a country (sends countryCode). reg — sign in with a PIA username and password (sends username, password). data — return the signed-in account hint. del — delete stored PIA credentials. addKey — register a WireGuard key with the selected server (sends hostname) and return fields to build the outbound.",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/xray/resetOutboundsTraffic": {
"post": {
"tags": [
@@ -11837,6 +12348,280 @@
}
}
},
"/panel/api/sub-balancers": {
"get": {
"tags": [
"Subscription Balancers"
],
"summary": "List all subscription balancers in sort order (sort_order asc, id asc).",
"operationId": "get_panel_api_sub_balancers",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"type": "array",
"items": {
"$ref": "#/components/schemas/SubBalancer"
}
}
}
},
"example": {
"success": true,
"obj": [
{
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
}
]
}
}
}
}
}
},
"post": {
"tags": [
"Subscription Balancers"
],
"summary": "Create a subscription balancer. It appears in the JSON subscription of every client that sits on at least one selected inbound.",
"operationId": "post_panel_api_sub_balancers",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SubBalancer"
}
}
},
"example": {
"success": true,
"obj": {
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
}
}
}
}
}
}
}
},
"/panel/api/sub-balancers/{id}": {
"post": {
"tags": [
"Subscription Balancers"
],
"summary": "Update a balancer by id. Accepts the same form fields as create (full-row update, including the enabled toggle).",
"operationId": "post_panel_api_sub_balancers_id",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Balancer id.",
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SubBalancer"
}
}
},
"example": {
"success": true,
"obj": {
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
}
}
}
}
}
}
},
"delete": {
"tags": [
"Subscription Balancers"
],
"summary": "Delete a balancer by id.",
"operationId": "delete_panel_api_sub_balancers_id",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Balancer id.",
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SubBalancer"
}
}
},
"example": {
"success": true,
"obj": {
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
}
}
}
}
}
}
}
},
"/panel/api/sub-balancers/{id}/del": {
"post": {
"tags": [
"Subscription Balancers"
],
"summary": "Delete a balancer by id (POST alias of DELETE for clients that cannot send DELETE).",
"operationId": "post_panel_api_sub_balancers_id_del",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Balancer id.",
"schema": {
"type": "integer"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/SubBalancer"
}
}
},
"example": {
"success": true,
"obj": {
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
}
}
}
}
}
}
}
},
"/{subPath}{subid}": {
"get": {
"tags": [
@@ -77,6 +77,7 @@ export function useAllSettings() {
if (!msg?.success) return;
if (saved) markSaved(saved);
queryClient.invalidateQueries({ queryKey: keys.settings.all() });
queryClient.invalidateQueries({ queryKey: keys.settings.defaults() });
},
});
@@ -0,0 +1,33 @@
import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { keys } from '@/api/queryKeys';
import { ClientRecordSchema, type ClientRecord } from '@/schemas/client';
const ClientRecordListSchema = z
.array(ClientRecordSchema)
.nullable()
.transform((value) => value ?? []);
async function fetchClients(): Promise<ClientRecord[]> {
const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
return validated.obj ?? [];
}
export function useClientOptions(enabled = true) {
return useQuery({
queryKey: keys.clients.all(),
queryFn: fetchClients,
enabled,
staleTime: 30_000,
select: (clients) =>
clients
.map((client) => client.email.trim())
.filter(Boolean)
.sort((a, b) => a.localeCompare(b)),
});
}
@@ -0,0 +1,41 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
import { keys } from '@/api/queryKeys';
import type { SubBalancerFormValues } from '@/schemas/subBalancer';
// Deliberately urlencoded (no JSON headers): the Go side binds inboundIds from
// repeated form keys, which is exactly how HttpUtil encodes arrays.
export function useSubBalancerMutations() {
const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.subBalancers.root() });
const createMut = useMutation({
mutationFn: (payload: SubBalancerFormValues) =>
HttpUtil.post('/panel/api/sub-balancers', payload),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const updateMut = useMutation({
mutationFn: ({ id, payload }: { id: number; payload: SubBalancerFormValues }) =>
HttpUtil.post(`/panel/api/sub-balancers/${id}`, payload),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const removeMut = useMutation({
mutationFn: (id: number) => HttpUtil.post(`/panel/api/sub-balancers/${id}/del`),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
return {
create: (payload: SubBalancerFormValues) => createMut.mutateAsync(payload),
update: (id: number, payload: SubBalancerFormValues) => updateMut.mutateAsync({ id, payload }),
remove: (id: number) => removeMut.mutateAsync(id),
};
}
@@ -0,0 +1,31 @@
import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { keys } from '@/api/queryKeys';
import { SubBalancerListSchema, type SubBalancer } from '@/schemas/subBalancer';
async function fetchSubBalancers(): Promise<SubBalancer[]> {
const msg = await HttpUtil.get('/panel/api/sub-balancers', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch subscription balancers');
const validated = parseMsg(msg, SubBalancerListSchema, 'sub-balancers');
return Array.isArray(validated.obj) ? validated.obj : [];
}
export function useSubBalancersQuery() {
const query = useQuery({
queryKey: keys.subBalancers.list(),
queryFn: fetchSubBalancers,
});
const balancers = useMemo(() => query.data ?? [], [query.data]);
return {
balancers,
loading: query.isFetching,
fetched: query.data !== undefined || query.isError,
fetchError: query.error ? (query.error as Error).message : '',
refetch: query.refetch,
};
}
+4
View File
@@ -13,6 +13,10 @@ export const keys = {
byInbound: (inboundId: number) => ['hosts', 'byInbound', inboundId] as const,
tags: () => ['hosts', 'tags'] as const,
},
subBalancers: {
root: () => ['sub-balancers'] as const,
list: () => ['sub-balancers', 'list'] as const,
},
settings: {
root: () => ['settings'] as const,
all: () => ['settings', 'all'] as const,
@@ -0,0 +1,129 @@
import { Button, Modal, Popconfirm, Tag, Typography } from 'antd';
import { DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { ClientHwidInfo } from '@/lib/clients/hwid-log';
interface ClientHwidListModalProps {
open: boolean;
email?: string;
zIndex?: number;
hwids: ClientHwidInfo[];
loading: boolean;
clearing: boolean;
deletingId: number | null;
formatDate: (ts: number) => string;
onRefresh: () => void;
onClearAll: () => void;
onDelete: (id: number) => void;
onClose: () => void;
}
// The single place the HWID device list is rendered — the edit form and the
// info card share it so date format and row layout can't drift apart again.
export default function ClientHwidListModal({
open,
email,
zIndex,
hwids,
loading,
clearing,
deletingId,
formatDate,
onRefresh,
onClearAll,
onDelete,
onClose,
}: ClientHwidListModalProps) {
const { t } = useTranslation();
return (
<Modal
open={open}
title={`${t('pages.clients.hwidLog')}${email ? `${email}` : ''}`}
width={520}
zIndex={zIndex}
onCancel={onClose}
footer={[
<Button key="refresh" icon={<ReloadOutlined />} loading={loading} onClick={onRefresh}>
{t('refresh')}
</Button>,
<Popconfirm
key="clear"
title={t('pages.clients.clearHwidsConfirm')}
onConfirm={onClearAll}
okType="danger"
okText={t('delete')}
cancelText={t('cancel')}
>
<Button danger loading={clearing} disabled={hwids.length === 0}>
{t('pages.clients.clearAll')}
</Button>
</Popconfirm>,
<Button key="close" type="primary" onClick={onClose}>
{t('close')}
</Button>,
]}
>
{hwids.length > 0 ? (
<div style={{ maxHeight: 360, overflowY: 'auto' }}>
{hwids.map((entry) => (
<div
key={entry.id}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: 8,
borderBottom: '1px solid var(--ant-color-border-secondary)',
padding: '8px 0',
}}
>
<div style={{ flex: 1, minWidth: 0 }}>
<Typography.Text strong>
{entry.deviceModel || entry.userAgent || t('pages.clients.hwidDevice')}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{[entry.deviceOs, entry.osVersion].filter(Boolean).join(' ')}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{t('pages.clients.firstSeen')}: {formatDate(entry.firstSeen)}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{t('pages.clients.lastSeen')}: {formatDate(entry.lastSeen)}
</Typography.Text>
{entry.userAgent && (
<>
<br />
<Typography.Text type="secondary" style={{ wordBreak: 'break-all' }}>
{entry.userAgent}
</Typography.Text>
</>
)}
</div>
<Popconfirm
title={t('pages.clients.deleteHwidConfirm')}
onConfirm={() => onDelete(entry.id)}
okType="danger"
okText={t('delete')}
cancelText={t('cancel')}
>
<Button
danger
type="text"
size="small"
aria-label={t('pages.clients.deleteHwid')}
icon={<DeleteOutlined />}
loading={deletingId === entry.id}
/>
</Popconfirm>
</div>
))}
</div>
) : (
<Tag>{t('pages.clients.noHwids')}</Tag>
)}
</Modal>
);
}
+90
View File
@@ -66,6 +66,7 @@ export const EXAMPLES: Record<string, unknown> = {
"subJsonEnable": false,
"subJsonFinalMask": "",
"subJsonMux": "",
"subJsonObservatory": "",
"subJsonPath": "",
"subJsonRules": "",
"subJsonURI": "",
@@ -179,6 +180,7 @@ export const EXAMPLES: Record<string, unknown> = {
"subJsonEnable": false,
"subJsonFinalMask": "",
"subJsonMux": "",
"subJsonObservatory": "",
"subJsonPath": "",
"subJsonRules": "",
"subJsonURI": "",
@@ -219,6 +221,26 @@ export const EXAMPLES: Record<string, unknown> = {
"webListen": "",
"webPort": 1
},
"AmneziaWGLogs": {
"events": [
"2025/01/01 12:00:00 amneziawg: started interface awg1 for inbound 1"
],
"peers": [
{
"allowedIPs": "10.8.1.2/32",
"down": 4194304,
"email": "peer@example.com",
"endpoint": "203.0.113.9:51820",
"handshake": 1735732800000,
"inboundId": 1,
"interface": "awg1",
"online": true,
"tag": "inbound-51820",
"up": 1048576
}
],
"running": true
},
"ApiToken": {
"createdAt": 0,
"enabled": false,
@@ -242,6 +264,7 @@ export const EXAMPLES: Record<string, unknown> = {
"allowedIPs": [
""
],
"allowedIPsByInbound": {},
"auth": "",
"comment": "",
"created_at": 0,
@@ -249,6 +272,7 @@ export const EXAMPLES: Record<string, unknown> = {
"enable": false,
"expiryTime": 0,
"flow": "",
"forwardedPorts": "",
"group": "",
"id": "",
"keepAlive": 0,
@@ -286,6 +310,7 @@ export const EXAMPLES: Record<string, unknown> = {
"enable": false,
"expiryTime": 0,
"flow": "",
"forwardedPorts": "",
"group": "",
"id": 0,
"keepAlive": 0,
@@ -542,6 +567,7 @@ export const EXAMPLES: Record<string, unknown> = {
"xver": 0
},
"InboundOption": {
"awgServer": null,
"enable": true,
"id": 1,
"listen": "",
@@ -687,6 +713,18 @@ export const EXAMPLES: Record<string, unknown> = {
"runId": "1735689600123456789",
"state": "success"
},
"PeerActivity": {
"allowedIPs": "10.8.1.2/32",
"down": 4194304,
"email": "peer@example.com",
"endpoint": "203.0.113.9:51820",
"handshake": 1735732800000,
"inboundId": 1,
"interface": "awg1",
"online": true,
"tag": "inbound-51820",
"up": 1048576
},
"ProbeResultUI": {
"cpuPct": 12.5,
"error": "",
@@ -723,11 +761,63 @@ export const EXAMPLES: Record<string, unknown> = {
"tlsVersion": "1.3",
"x25519": true
},
"ServerSettings": {
"contentPaddingAddition": "",
"disableCookies": false,
"externalInterface": "",
"h1": "",
"h2": "",
"h3": "",
"h4": "",
"headerProtectionKey": "",
"i1": "",
"i2": "",
"i3": "",
"i4": "",
"i5": "",
"ipv6Enabled": false,
"ipv6ExternalInterface": "",
"ipv6Subnet": "",
"jc": 0,
"jmax": 0,
"jmin": 0,
"keepaliveTimeout": "",
"maxHandshakeAttempts": "",
"mtu": 0,
"primaryDns": "",
"privateKey": "",
"publicKey": "",
"randomTrailers": false,
"rejectAfterTime": "",
"rekeyAfterTime": "",
"rekeyTimeout": "",
"routeThroughXray": false,
"s1": 0,
"s2": 0,
"s3": 0,
"s4": 0,
"secondaryDns": "",
"subnetCidr": 0,
"subnetIp": ""
},
"Setting": {
"id": 0,
"key": "",
"value": ""
},
"SubBalancer": {
"createdAt": 1710000000000,
"enabled": true,
"id": 1,
"inboundIds": [
1,
3
],
"remark": "auto-fastest",
"sortOrder": 1,
"strategy": "random",
"updatedAt": 1710000000000
},
"User": {
"id": 0,
"password": "",
+338 -1
View File
@@ -215,6 +215,9 @@ export const SCHEMAS: Record<string, unknown> = {
"subJsonMux": {
"type": "string"
},
"subJsonObservatory": {
"type": "string"
},
"subJsonPath": {
"type": "string"
},
@@ -412,6 +415,7 @@ export const SCHEMAS: Record<string, unknown> = {
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
"subJsonObservatory",
"subJsonPath",
"subJsonRules",
"subJsonURI",
@@ -690,6 +694,9 @@ export const SCHEMAS: Record<string, unknown> = {
"subJsonMux": {
"type": "string"
},
"subJsonObservatory": {
"type": "string"
},
"subJsonPath": {
"type": "string"
},
@@ -894,6 +901,7 @@ export const SCHEMAS: Record<string, unknown> = {
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
"subJsonObservatory",
"subJsonPath",
"subJsonRules",
"subJsonURI",
@@ -936,6 +944,36 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"AmneziaWGLogs": {
"description": "AmneziaWGLogs is what the overview's AmneziaWG log view renders: the live\nper-peer activity of every running embedded interface, plus the panel's\nown recent AmneziaWG lifecycle log lines that explain a peer being absent\nfrom Peers at all.",
"properties": {
"events": {
"example": [
"2025/01/01 12:00:00 amneziawg: started interface awg1 for inbound 1"
],
"items": {
"type": "string"
},
"type": "array"
},
"peers": {
"items": {
"$ref": "#/components/schemas/PeerActivity"
},
"type": "array"
},
"running": {
"example": true,
"type": "boolean"
}
},
"required": [
"events",
"peers",
"running"
],
"type": "object"
},
"ApiToken": {
"properties": {
"createdAt": {
@@ -1030,6 +1068,16 @@ export const SCHEMAS: Record<string, unknown> = {
},
"type": "array"
},
"allowedIPsByInbound": {
"additionalProperties": {
"items": {
"type": "string"
},
"type": "array"
},
"description": "AllowedIPsByInbound optionally overrides AllowedIPs on a per-inbound\nbasis, keyed by inbound id. Lets one identity attached to both\nWireGuard and AmneziaWG carry two genuinely different addresses in a\nsingle Create/Update call instead of the shared AllowedIPs field\nbeing broadcast to every attached tunnel inbound. Absent/unset for a\ngiven inbound id falls back to the shared AllowedIPs exactly as\nbefore -- fully backward compatible for callers that never set this.",
"type": "object"
},
"auth": {
"description": "Auth password (Hysteria)",
"type": "string"
@@ -1060,6 +1108,10 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Flow control (XTLS)",
"type": "string"
},
"forwardedPorts": {
"description": "AmneziaWG per-client port-forwarding spec, e.g. \"80,443,8000-8100\"",
"type": "string"
},
"group": {
"description": "Logical grouping label",
"type": "string"
@@ -1224,6 +1276,9 @@ export const SCHEMAS: Record<string, unknown> = {
"flow": {
"type": "string"
},
"forwardedPorts": {
"type": "string"
},
"group": {
"type": "string"
},
@@ -1302,6 +1357,7 @@ export const SCHEMAS: Record<string, unknown> = {
"enable",
"expiryTime",
"flow",
"forwardedPorts",
"group",
"id",
"keepAlive",
@@ -2045,7 +2101,8 @@ export const SCHEMAS: Record<string, unknown> = {
"mixed",
"tunnel",
"tun",
"mtproto"
"mtproto",
"amneziawg"
],
"example": "vless",
"type": "string"
@@ -2197,6 +2254,15 @@ export const SCHEMAS: Record<string, unknown> = {
},
"InboundOption": {
"properties": {
"awgServer": {
"allOf": [
{
"$ref": "#/components/schemas/ServerSettings"
}
],
"description": "AwgServer carries the full AmneziaWG server block (keys, subnet,\nobfuscation params) so the clients page can render a downloadable\nper-client .conf without a second round trip.",
"nullable": true
},
"enable": {
"example": true,
"type": "boolean"
@@ -2879,6 +2945,68 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"PeerActivity": {
"description": "PeerActivity is one peer's live embedded-Device-reported state, the\ncounterpart of an Xray access-log entry: a tunnel logs no requests, only\nhandshakes and bytes.",
"properties": {
"allowedIPs": {
"example": "10.8.1.2/32",
"type": "string"
},
"down": {
"example": 4194304,
"format": "int64",
"type": "integer"
},
"email": {
"example": "peer@example.com",
"type": "string"
},
"endpoint": {
"example": "203.0.113.9:51820",
"type": "string"
},
"handshake": {
"description": "Handshake is unix milliseconds, 0 when the peer has never connected.",
"example": 1735732800000,
"format": "int64",
"type": "integer"
},
"inboundId": {
"example": 1,
"type": "integer"
},
"interface": {
"example": "awg1",
"type": "string"
},
"online": {
"example": true,
"type": "boolean"
},
"tag": {
"example": "inbound-51820",
"type": "string"
},
"up": {
"example": 1048576,
"format": "int64",
"type": "integer"
}
},
"required": [
"allowedIPs",
"down",
"email",
"endpoint",
"handshake",
"inboundId",
"interface",
"online",
"tag",
"up"
],
"type": "object"
},
"ProbeResultUI": {
"properties": {
"cpuPct": {
@@ -3045,6 +3173,150 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"ServerSettings": {
"description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.",
"properties": {
"contentPaddingAddition": {
"type": "string"
},
"disableCookies": {
"type": "boolean"
},
"externalInterface": {
"description": "ExternalInterface, IPv6Enabled, and IPv6ExternalInterface are live\nagain as of Phase 3.5 -- see the matching fields on Instance for what\nthey gate (internal/amneziawgnet's IPv6-address-alias mechanism).\nIPv6Subnet was never actually vestigial either: InstanceFromInbound\nalready consumes it (via serverAddressV6) to build the server's own\ntunnel address, same as always. Only RouteThroughXray, below, remains\ngenuinely vestigial as of the hard cutover to the embedded path\n(internal/amneziawgnet) -- read from existing stored settings for\nbackward compatibility, but not acted on by anything.",
"type": "string"
},
"h1": {
"type": "string"
},
"h2": {
"type": "string"
},
"h3": {
"type": "string"
},
"h4": {
"type": "string"
},
"headerProtectionKey": {
"description": "HeaderProtectionKey and ContentPaddingAddition are AmneziaWG 3.0\nfields, flat and top-level for the same tools/openapigen reason as\nthe block above; Obfuscation() below folds them back into\nObfuscation31's own identically named fields.\nHeaderProtectionKey is a base64 32-byte key; empty (the default)\ndisables AWG 3.0 header protection. A non-empty value requires\nevery one of S1-S4 above to be \u003e= 12 -- ValidateObfuscation\nenforces this at save time, not just at IpcSet time.\nContentPaddingAddition is a \"low-high\" range or bare integer, the\nsame grammar and uint32 cap as H1-H4.",
"type": "string"
},
"i1": {
"type": "string"
},
"i2": {
"type": "string"
},
"i3": {
"type": "string"
},
"i4": {
"type": "string"
},
"i5": {
"type": "string"
},
"ipv6Enabled": {
"type": "boolean"
},
"ipv6ExternalInterface": {
"type": "string"
},
"ipv6Subnet": {
"type": "string"
},
"jc": {
"description": "Obfuscation31's fields, repeated flat (not embedded) rather than\nnested under their own key: encoding/json would happily inline an\nembedded Obfuscation31 the same way, but the frontend's Go-\u003eZod/TS\ngenerator (tools/openapigen) does not — it emits a genuinely nested\n`obfuscation31` object, which would silently diverge from the real\nwire JSON. See Obfuscation() below for the manager-facing conversion.",
"type": "integer"
},
"jmax": {
"type": "integer"
},
"jmin": {
"type": "integer"
},
"keepaliveTimeout": {
"type": "string"
},
"maxHandshakeAttempts": {
"type": "string"
},
"mtu": {
"type": "integer"
},
"primaryDns": {
"description": "PrimaryDNS/SecondaryDNS seed client configs' DNS line. Blank is\nmeaningful, so no omitempty: a dropped key resurrects frontend defaults.",
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"randomTrailers": {
"description": "RandomTrailers/DisableCookies mirror Instance's identically named\nAmneziaWG 3.1 fields -- see that type's own doc comment for the real\nprotocol/interop details. Both real bool fields (not omitempty):\nbuildUAPIConfig always emits both lines explicitly so the\nreconfigure-in-place diff correctly notices a true-\u003efalse edit, not\njust false-\u003etrue.",
"type": "boolean"
},
"rejectAfterTime": {
"type": "string"
},
"rekeyAfterTime": {
"description": "RekeyAfterTime/RekeyTimeout/RejectAfterTime/KeepaliveTimeout/\nMaxHandshakeAttempts mirror Instance's identically named fields --\nsee that type's own doc comment for the grammar/width/real-default\ndetails. Flat and top-level for the same tools/openapigen reason as\nthe rest of this struct.",
"type": "string"
},
"rekeyTimeout": {
"type": "string"
},
"routeThroughXray": {
"type": "boolean"
},
"s1": {
"type": "integer"
},
"s2": {
"type": "integer"
},
"s3": {
"type": "integer"
},
"s4": {
"type": "integer"
},
"secondaryDns": {
"type": "string"
},
"subnetCidr": {
"type": "integer"
},
"subnetIp": {
"type": "string"
}
},
"required": [
"disableCookies",
"h1",
"h2",
"h3",
"h4",
"jc",
"jmax",
"jmin",
"primaryDns",
"privateKey",
"publicKey",
"randomTrailers",
"s1",
"s2",
"s3",
"s4",
"secondaryDns",
"subnetCidr",
"subnetIp"
],
"type": "object"
},
"Setting": {
"description": "Setting stores key-value configuration settings for the 3x-ui panel.",
"properties": {
@@ -3065,6 +3337,71 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"SubBalancer": {
"description": "SubBalancer is one extra JSON-subscription config document whose members are\nthe selected inbounds' proxy outbounds. SortOrder shares SubSortIndex semantics.",
"properties": {
"createdAt": {
"example": 1710000000000,
"format": "int64",
"type": "integer"
},
"enabled": {
"description": "No gorm default:true — a bool default makes an explicit false at insert\ncollapse back to the column default (zero value is skipped).",
"example": true,
"type": "boolean"
},
"id": {
"example": 1,
"type": "integer"
},
"inboundIds": {
"example": [
1,
3
],
"items": {
"type": "integer"
},
"type": "array"
},
"remark": {
"example": "auto-fastest",
"maxLength": 256,
"type": "string"
},
"sortOrder": {
"example": 1,
"minimum": 1,
"type": "integer"
},
"strategy": {
"enum": [
"leastLoad",
"leastPing",
"random",
"roundRobin"
],
"example": "random",
"type": "string"
},
"updatedAt": {
"example": 1710000000000,
"format": "int64",
"type": "integer"
}
},
"required": [
"createdAt",
"enabled",
"id",
"inboundIds",
"remark",
"sortOrder",
"strategy",
"updatedAt"
],
"type": "object"
},
"User": {
"description": "User represents a user account in the 3x-ui panel.",
"properties": {
+76
View File
@@ -74,6 +74,7 @@ export interface AllSetting {
subJsonEnable: boolean;
subJsonFinalMask: string;
subJsonMux: string;
subJsonObservatory: string;
subJsonPath: string;
subJsonRules: string;
subJsonURI: string;
@@ -188,6 +189,7 @@ export interface AllSettingView {
subJsonEnable: boolean;
subJsonFinalMask: string;
subJsonMux: string;
subJsonObservatory: string;
subJsonPath: string;
subJsonRules: string;
subJsonURI: string;
@@ -229,6 +231,12 @@ export interface AllSettingView {
webPort: number;
}
export interface AmneziaWGLogs {
events: string[];
peers: PeerActivity[];
running: boolean;
}
export interface ApiToken {
createdAt: number;
enabled: boolean;
@@ -252,6 +260,7 @@ export interface ApiTokenView {
export interface Client {
adTag?: string;
allowedIPs?: string[];
allowedIPsByInbound?: Record<number, string[]>;
auth?: string;
comment: string;
created_at?: number;
@@ -259,6 +268,7 @@ export interface Client {
enable: boolean;
expiryTime: number;
flow?: string;
forwardedPorts?: string;
group?: string;
id?: string;
keepAlive?: number;
@@ -298,6 +308,7 @@ export interface ClientRecord {
enable: boolean;
expiryTime: number;
flow: string;
forwardedPorts: string;
group: string;
id: number;
keepAlive: number;
@@ -510,6 +521,7 @@ export interface InboundFallback {
}
export interface InboundOption {
awgServer?: ServerSettings | null;
enable: boolean;
id: number;
listen?: string;
@@ -656,6 +668,19 @@ export interface PanelUpdateStatus {
state: string;
}
export interface PeerActivity {
allowedIPs: string;
down: number;
email: string;
endpoint: string;
handshake: number;
inboundId: number;
interface: string;
online: boolean;
tag: string;
up: number;
}
export interface ProbeResultUI {
cpuPct: number;
error: string;
@@ -692,12 +717,63 @@ export interface RealityScanResult {
x25519: boolean;
}
export interface ServerSettings {
contentPaddingAddition?: string;
disableCookies: boolean;
externalInterface?: string;
h1: string;
h2: string;
h3: string;
h4: string;
headerProtectionKey?: string;
i1?: string;
i2?: string;
i3?: string;
i4?: string;
i5?: string;
ipv6Enabled?: boolean;
ipv6ExternalInterface?: string;
ipv6Subnet?: string;
jc: number;
jmax: number;
jmin: number;
keepaliveTimeout?: string;
maxHandshakeAttempts?: string;
mtu?: number;
primaryDns: string;
privateKey: string;
publicKey: string;
randomTrailers: boolean;
rejectAfterTime?: string;
rekeyAfterTime?: string;
rekeyTimeout?: string;
routeThroughXray?: boolean;
s1: number;
s2: number;
s3: number;
s4: number;
secondaryDns: string;
subnetCidr: number;
subnetIp: string;
}
export interface Setting {
id: number;
key: string;
value: string;
}
export interface SubBalancer {
createdAt: number;
enabled: boolean;
id: number;
inboundIds: number[];
remark: string;
sortOrder: number;
strategy: string;
updatedAt: number;
}
export interface User {
id: number;
password: string;
+81 -1
View File
@@ -90,6 +90,7 @@ export const AllSettingSchema = z.object({
subJsonEnable: z.boolean(),
subJsonFinalMask: z.string(),
subJsonMux: z.string(),
subJsonObservatory: z.string(),
subJsonPath: z.string(),
subJsonRules: z.string(),
subJsonURI: z.string(),
@@ -205,6 +206,7 @@ export const AllSettingViewSchema = z.object({
subJsonEnable: z.boolean(),
subJsonFinalMask: z.string(),
subJsonMux: z.string(),
subJsonObservatory: z.string(),
subJsonPath: z.string(),
subJsonRules: z.string(),
subJsonURI: z.string(),
@@ -247,6 +249,13 @@ export const AllSettingViewSchema = z.object({
});
export type AllSettingView = z.infer<typeof AllSettingViewSchema>;
export const AmneziaWGLogsSchema = z.object({
events: z.array(z.string()),
peers: z.array(z.lazy(() => PeerActivitySchema)),
running: z.boolean(),
});
export type AmneziaWGLogs = z.infer<typeof AmneziaWGLogsSchema>;
export const ApiTokenSchema = z.object({
createdAt: z.number().int(),
enabled: z.boolean(),
@@ -272,6 +281,7 @@ export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>;
export const ClientSchema = z.object({
adTag: z.string().optional(),
allowedIPs: z.array(z.string()).optional(),
allowedIPsByInbound: z.record(z.number().int(), z.array(z.string())).optional(),
auth: z.string().optional(),
comment: z.string(),
created_at: z.number().int().optional(),
@@ -279,6 +289,7 @@ export const ClientSchema = z.object({
enable: z.boolean(),
expiryTime: z.number().int(),
flow: z.string().optional(),
forwardedPorts: z.string().optional(),
group: z.string().optional(),
id: z.string().optional(),
keepAlive: z.number().int().optional(),
@@ -320,6 +331,7 @@ export const ClientRecordSchema = z.object({
enable: z.boolean(),
expiryTime: z.number().int(),
flow: z.string(),
forwardedPorts: z.string(),
group: z.string(),
id: z.number().int(),
keepAlive: z.number().int(),
@@ -511,7 +523,7 @@ export const InboundSchema = z.object({
nodeId: z.number().int().nullable().optional(),
originNodeGuid: z.string().optional(),
port: z.number().int().min(0).max(65535),
protocol: z.enum(['vmess', 'vless', 'trojan', 'shadowsocks', 'wireguard', 'hysteria', 'http', 'mixed', 'tunnel', 'tun', 'mtproto']),
protocol: z.enum(['vmess', 'vless', 'trojan', 'shadowsocks', 'wireguard', 'hysteria', 'http', 'mixed', 'tunnel', 'tun', 'mtproto', 'amneziawg']),
remark: z.string(),
settings: z.unknown(),
shareAddr: z.string(),
@@ -548,6 +560,7 @@ export const InboundFallbackSchema = z.object({
export type InboundFallback = z.infer<typeof InboundFallbackSchema>;
export const InboundOptionSchema = z.object({
awgServer: z.lazy(() => ServerSettingsSchema).nullable().optional(),
enable: z.boolean(),
id: z.number().int(),
listen: z.string().optional(),
@@ -701,6 +714,20 @@ export const PanelUpdateStatusSchema = z.object({
});
export type PanelUpdateStatus = z.infer<typeof PanelUpdateStatusSchema>;
export const PeerActivitySchema = z.object({
allowedIPs: z.string(),
down: z.number().int(),
email: z.string(),
endpoint: z.string(),
handshake: z.number().int(),
inboundId: z.number().int(),
interface: z.string(),
online: z.boolean(),
tag: z.string(),
up: z.number().int(),
});
export type PeerActivity = z.infer<typeof PeerActivitySchema>;
export const ProbeResultUISchema = z.object({
cpuPct: z.number(),
error: z.string(),
@@ -739,6 +766,47 @@ export const RealityScanResultSchema = z.object({
});
export type RealityScanResult = z.infer<typeof RealityScanResultSchema>;
export const ServerSettingsSchema = z.object({
contentPaddingAddition: z.string().optional(),
disableCookies: z.boolean(),
externalInterface: z.string().optional(),
h1: z.string(),
h2: z.string(),
h3: z.string(),
h4: z.string(),
headerProtectionKey: z.string().optional(),
i1: z.string().optional(),
i2: z.string().optional(),
i3: z.string().optional(),
i4: z.string().optional(),
i5: z.string().optional(),
ipv6Enabled: z.boolean().optional(),
ipv6ExternalInterface: z.string().optional(),
ipv6Subnet: z.string().optional(),
jc: z.number().int(),
jmax: z.number().int(),
jmin: z.number().int(),
keepaliveTimeout: z.string().optional(),
maxHandshakeAttempts: z.string().optional(),
mtu: z.number().int().optional(),
primaryDns: z.string(),
privateKey: z.string(),
publicKey: z.string(),
randomTrailers: z.boolean(),
rejectAfterTime: z.string().optional(),
rekeyAfterTime: z.string().optional(),
rekeyTimeout: z.string().optional(),
routeThroughXray: z.boolean().optional(),
s1: z.number().int(),
s2: z.number().int(),
s3: z.number().int(),
s4: z.number().int(),
secondaryDns: z.string(),
subnetCidr: z.number().int(),
subnetIp: z.string(),
});
export type ServerSettings = z.infer<typeof ServerSettingsSchema>;
export const SettingSchema = z.object({
id: z.number().int(),
key: z.string(),
@@ -746,6 +814,18 @@ export const SettingSchema = z.object({
});
export type Setting = z.infer<typeof SettingSchema>;
export const SubBalancerSchema = z.object({
createdAt: z.number().int(),
enabled: z.boolean(),
id: z.number().int(),
inboundIds: z.array(z.number().int()),
remark: z.string().max(256),
sortOrder: z.number().int().min(1),
strategy: z.enum(['leastLoad', 'leastPing', 'random', 'roundRobin']),
updatedAt: z.number().int(),
});
export type SubBalancer = z.infer<typeof SubBalancerSchema>;
export const UserSchema = z.object({
id: z.number().int(),
password: z.string(),
+75
View File
@@ -0,0 +1,75 @@
import { useState } from 'react';
import { HttpUtil } from '@/utils';
import { normalizeClientHwids, type ClientHwidInfo } from '@/lib/clients/hwid-log';
interface ApiMsg<T = unknown> {
success?: boolean;
obj?: T;
}
// Fetch/mutate state for one client's registered-device list, shared by the
// edit form and the info card. No email (add-client form) => every action no-ops.
export function useClientHwids(email: string | undefined) {
const [clientHwids, setClientHwids] = useState<ClientHwidInfo[]>([]);
const [hwidsLoading, setHwidsLoading] = useState(false);
const [hwidsClearing, setHwidsClearing] = useState(false);
const [deletingHwidId, setDeletingHwidId] = useState<number | null>(null);
async function loadHwids() {
if (!email) return;
setHwidsLoading(true);
try {
const msg = (await HttpUtil.post(
`/panel/api/clients/hwids/${encodeURIComponent(email)}`,
)) as ApiMsg<unknown[]>;
if (!msg?.success) {
setClientHwids([]);
return;
}
setClientHwids(normalizeClientHwids(msg.obj));
} finally {
setHwidsLoading(false);
}
}
async function clearHwids() {
if (!email) return;
setHwidsClearing(true);
try {
const msg = (await HttpUtil.delete(
`/panel/api/clients/hwids/${encodeURIComponent(email)}`,
)) as ApiMsg;
if (msg?.success) setClientHwids([]);
} finally {
setHwidsClearing(false);
}
}
async function deleteHwid(id: number) {
if (!email) return;
setDeletingHwidId(id);
try {
const msg = (await HttpUtil.delete(
`/panel/api/clients/hwids/${encodeURIComponent(email)}/${id}`,
)) as ApiMsg;
if (msg?.success) setClientHwids((prev) => prev.filter((entry) => entry.id !== id));
} finally {
setDeletingHwidId(null);
}
}
function resetHwids() {
setClientHwids([]);
}
return {
clientHwids,
hwidsLoading,
hwidsClearing,
deletingHwidId,
loadHwids,
clearHwids,
deleteHwid,
resetHwids,
};
}
+10 -1
View File
@@ -6,6 +6,7 @@ import { Drawer, Layout, Menu } from 'antd';
import type { MenuProps } from 'antd';
import {
ApiOutlined,
ApartmentOutlined,
CloseOutlined,
CloudServerOutlined,
ClusterOutlined,
@@ -177,6 +178,7 @@ export default function AppSidebar() {
const { pathname, hash } = useLocation();
const { allSetting } = useAllSettings();
const showSubFormats = !!(allSetting.subJsonEnable || allSetting.subClashEnable);
const showSubBalancers = !!allSetting.subJsonEnable;
const [hovered, setHovered] = useState(() => hoveredAcrossRemounts);
const [pinned, setPinned] = useState(readSidebarPinned);
@@ -262,8 +264,15 @@ export default function AppSidebar() {
label: t('menu.subFormats'),
});
}
if (showSubBalancers) {
children.push({
key: '/settings#subscription-balancers',
icon: <ApartmentOutlined />,
label: t('pages.settings.subBalancers.menu'),
});
}
return children;
}, [t, showSubFormats]);
}, [t, showSubFormats, showSubBalancers]);
const xrayChildren = useMemo<NonNullable<MenuProps['items']>>(
() => [
+21
View File
@@ -0,0 +1,21 @@
// Shape of one entry in a client's HWID (registered-device) log, as returned
// by POST /panel/api/clients/hwids/:email.
export type ClientHwidInfo = {
id: number;
firstSeen: number;
lastSeen: number;
userAgent: string;
deviceOs: string;
osVersion: string;
deviceModel: string;
};
// normalizeClientHwids accepts the API payload and returns typed entries,
// dropping anything that isn't a real HWID row (missing/non-numeric id).
export function normalizeClientHwids(obj: unknown): ClientHwidInfo[] {
if (!Array.isArray(obj)) return [];
return obj.filter(
(x): x is ClientHwidInfo =>
!!x && typeof x === 'object' && typeof (x as ClientHwidInfo).id === 'number',
);
}
@@ -0,0 +1,125 @@
import type { AmneziawgServer } from '@/schemas/protocols/inbound/amneziawg';
/*
* Client-side AmneziaWG 3.1 obfuscation generator, mirroring the ranges and
* constraints of the Go backend's amneziawg.GenerateObfuscation31
* (internal/amneziawg/params.go). Exact parity isn't required the user can
* edit any field afterward and the backend validates on save but the two
* generators must stay range-compatible so a value produced here always
* passes the Go-side ValidateObfuscation.
*/
export type AwgObfuscation = Pick<
AmneziawgServer,
| 'jc'
| 'jmin'
| 'jmax'
| 's1'
| 's2'
| 's3'
| 's4'
| 'h1'
| 'h2'
| 'h3'
| 'h4'
| 'i1'
| 'i2'
| 'i3'
| 'i4'
| 'i5'
| 'headerProtectionKey'
| 'contentPaddingAddition'
| 'rekeyAfterTime'
| 'rekeyTimeout'
| 'rejectAfterTime'
| 'keepaliveTimeout'
| 'maxHandshakeAttempts'
| 'randomTrailers'
| 'disableCookies'
>;
const randInt = (min: number, max: number) => min + Math.floor(Math.random() * (max - min + 1));
/*
* base64 of 32 crypto-grade random bytes the exact HeaderProtectionKey
* shape amneziawg-tools parses and the Go backend validates.
*/
const generateHeaderProtectionKey = (): string => {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
return btoa(String.fromCharCode(...bytes));
};
/*
* Four non-overlapping "low-high" ranges for H1-H4: split the space into
* four bands and take a random sub-range from each (>= 1000 wide, low
* bound >= 5 since 1-4 are reserved for vanilla WireGuard message types).
*/
const generateHRanges = (): [string, string, string, string] => {
const hMax = 2147483647;
const hMinWidth = 1000;
const lo = 5;
const bandSize = Math.floor((hMax - lo + 1) / 4);
return Array.from({ length: 4 }, (_, i) => {
const bandLo = lo + i * bandSize;
const bandHi = bandLo + bandSize - 1;
const start = randInt(bandLo, bandHi - hMinWidth - 1);
const end = randInt(start + hMinWidth, bandHi - 1);
return `${start}-${end}`;
}) as [string, string, string, string];
};
export function generateAwgObfuscation(): AwgObfuscation {
const jmin = randInt(40, 89);
const s1 = randInt(15, 150);
let s2 = randInt(15, 150);
while (s1 + 56 === s2) {
s2 = randInt(15, 150);
}
const [h1, h2, h3, h4] = generateHRanges();
/*
* Timing windows bracket WireGuard's stock constants (rekey 120s, reject
* 180s, retry 5s, keepalive 10s); every reject value exceeds every rekey
* value by >= 30s by construction, matching the Go generator and its
* ValidateObfuscation cross-check. Content padding stays <= 64 total for
* the same MTU-headroom reason that caps s4 at 32.
*/
const cpLo = randInt(8, 24);
const rekeyLo = randInt(100, 120);
const rekeyHi = rekeyLo + randInt(10, 40);
const rejectLo = rekeyHi + randInt(30, 60);
const rekeyTimeoutLo = randInt(3, 6);
const keepaliveLo = randInt(8, 12);
const attemptsLo = randInt(15, 25);
return {
jc: randInt(3, 6),
jmin,
jmax: jmin + randInt(50, 250),
s1,
s2,
// Floored at 12, not the protocol's 0/8/4 minima: headerProtectionKey is
// always generated below, and IpcSet rejects it unless every s1-s4 >= 12.
s3: randInt(12, 55),
s4: randInt(12, 27),
h1,
h2,
h3,
h4,
i1: `<r ${randInt(32, 256)}>`,
i2: '',
i3: '',
i4: '',
i5: '',
headerProtectionKey: generateHeaderProtectionKey(),
contentPaddingAddition: `${cpLo}-${cpLo + randInt(8, 40)}`,
rekeyAfterTime: `${rekeyLo}-${rekeyHi}`,
rekeyTimeout: `${rekeyTimeoutLo}-${rekeyTimeoutLo + randInt(1, 4)}`,
rejectAfterTime: `${rejectLo}-${rejectLo + randInt(30, 90)}`,
keepaliveTimeout: `${keepaliveLo}-${keepaliveLo + randInt(2, 8)}`,
maxHandshakeAttempts: `${attemptsLo}-${attemptsLo + randInt(5, 25)}`,
randomTrailers: true,
disableCookies: true,
};
}
+44 -1
View File
@@ -1,5 +1,7 @@
import { RandomUtil, Wireguard } from '@/utils';
import { generateAwgObfuscation } from '@/lib/xray/amneziawg-obfuscation';
import type { AmneziawgInboundSettings } from '@/schemas/protocols/inbound/amneziawg';
import type { HttpInboundSettings } from '@/schemas/protocols/inbound/http';
import type { HysteriaClient, HysteriaInboundSettings } from '@/schemas/protocols/inbound/hysteria';
import type { MixedInboundSettings } from '@/schemas/protocols/inbound/mixed';
@@ -263,12 +265,20 @@ export interface WireguardInboundSeed {
mtu?: number;
secretKey?: string;
noKernelTun?: boolean;
subnetIp?: string;
subnetCidr?: number;
}
// WireGuard is multi-client now: a new inbound holds only the server identity
// (secretKey/mtu) and starts with no clients. Clients (peers) are added later
// through the client modal, which generates each one's keypair and a unique
// tunnel address. peers stays empty for backward-compatible parsing.
//
// subnetIp/subnetCidr default to 10.0.0.0/24 here — the same value the Go
// backend has always fallen back to for an inbound with no clients yet — so
// a freshly created inbound shows an explicit, editable value from the
// start (matching AmneziaWG's own subnet field), rather than an empty one
// that silently relies on server-side inference until an admin fills it in.
export function createDefaultWireguardInboundSettings(
seed: WireguardInboundSeed = {},
): WireguardInboundSettings {
@@ -278,6 +288,36 @@ export function createDefaultWireguardInboundSettings(
peers: [],
clients: [],
noKernelTun: seed.noKernelTun ?? false,
subnetIp: seed.subnetIp ?? '10.0.0.0',
subnetCidr: seed.subnetCidr ?? 24,
};
}
// AmneziaWG is multi-client, like WireGuard, and uses the same Curve25519
// keypair format — Wireguard.generateKeypair() works unchanged. Unlike
// WireGuard's Xray-native inbound, the server's publicKey is a real
// persisted field here (the Go backend reads it directly rather than
// re-deriving it), so it's seeded alongside privateKey. The obfuscation
// parameters are randomized per inbound (a static default would give every
// install the same DPI fingerprint), mirroring the Go backend's
// internal/amneziawg.GenerateObfuscation31.
export function createDefaultAmneziawgInboundSettings(): AmneziawgInboundSettings {
const kp = Wireguard.generateKeypair();
return {
server: {
privateKey: kp.privateKey,
publicKey: kp.publicKey,
subnetIp: '10.8.1.0',
subnetCidr: 24,
primaryDns: '8.8.8.8',
secondaryDns: '8.8.4.4',
externalInterface: '',
ipv6Enabled: false,
ipv6Subnet: '',
ipv6ExternalInterface: '',
...generateAwgObfuscation(),
},
clients: [],
};
}
@@ -297,7 +337,8 @@ export type AnyInboundSettings =
| TunInboundSettings
| TunnelInboundSettings
| WireguardInboundSettings
| MtprotoInboundSettings;
| MtprotoInboundSettings
| AmneziawgInboundSettings;
export function createDefaultInboundSettings(protocol: string): AnyInboundSettings | null {
switch (protocol) {
@@ -323,6 +364,8 @@ export function createDefaultInboundSettings(protocol: string): AnyInboundSettin
return createDefaultWireguardInboundSettings();
case 'mtproto':
return createDefaultMtprotoInboundSettings();
case 'amneziawg':
return createDefaultAmneziawgInboundSettings();
default:
return null;
}
@@ -5,6 +5,7 @@ import type {
} from '@/schemas/forms/inbound-form';
import type { InboundSettings } from '@/schemas/protocols/inbound';
import {
AmneziawgClientSchema,
HysteriaClientSchema,
MtprotoClientSchema,
ShadowsocksClientSchema,
@@ -268,6 +269,8 @@ function clientSchemaForProtocol(protocol: string): z.ZodType | null {
return WireguardClientSchema;
case 'mtproto':
return MtprotoClientSchema;
case 'amneziawg':
return AmneziawgClientSchema;
default:
return null;
}
+195 -1
View File
@@ -1,6 +1,7 @@
import { Base64, Wireguard } from '@/utils';
import type { Inbound } from '@/schemas/api/inbound';
import type { AmneziawgInboundSettings } from '@/schemas/protocols/inbound/amneziawg';
import type { VlessClient } from '@/schemas/protocols/inbound/vless';
import type { VmessSecurity } from '@/schemas/protocols/shared/vmess';
import type {
@@ -911,6 +912,168 @@ export function genWireguardConfig(input: GenWireguardLinkInput): string {
return txt;
}
// Shared input shape for both the per-client vpn:// link and .conf
// builders below — settings.clients (not a peers array; unlike WireGuard,
// AmneziaWG was multi-client from day one, so there's no legacy format).
export interface GenAmneziaWGLinkInput {
settings: AmneziawgInboundSettings;
address: string;
port: number;
remark?: string;
peerIndex: number;
}
function amneziaWGHLine(key: string, value: string | undefined, fallback: string): string {
return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
}
// Base64url (RFC 4648 §5), no padding — matches the real AmneziaVPN app's
// own Qt::Base64UrlEncoding | Qt::OmitTrailingEquals framing for vpn:// links.
function toBase64Url(text: string): string {
const bytes = new TextEncoder().encode(text);
let binary = '';
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
// AmneziaWG share link: vpn://<base64url .conf text>, matching the real
// AmneziaVPN app's own share-link scheme. The app's import path base64url-
// decodes, best-effort qUncompresses (falls back to the raw bytes when the
// input isn't qCompress-framed, which plain text never is), then parses the
// result as a flat bag of "Key = Value" lines regardless of which
// [Interface]/[Peer] section they came from — so wrapping the same .conf
// text genAmneziaWGConfig already produces is sufficient; no JSON schema or
// compression needs replicating. Confirmed against the app's own source
// (importController.cpp's checkConfigFormat/extractWireGuardConfig).
export function genAmneziaWGLink(input: GenAmneziaWGLinkInput): string {
const cfgText = genAmneziaWGConfig(input);
if (!cfgText) return '';
return `vpn://${toBase64Url(cfgText)}`;
}
// Plain-text AmneziaWG client config (.conf format). Mirrors
// genWireguardConfig, plus the obfuscation lines every AmneziaWG client must
// share with the server (see internal/amneziawg.writeObfuscation on the Go
// side).
export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
const { settings, address, port, remark = '', peerIndex } = input;
const client = settings.clients[peerIndex];
if (!client) return '';
const server = settings.server;
// These land unescaped in the .conf; a newline would inject a config line
// (e.g. a rogue PostUp) — same guard as the panel's other two emitters.
for (const v of [
client.privateKey ?? '',
server.primaryDns ?? '',
server.secondaryDns ?? '',
remark,
]) {
if (/[\r\n]/.test(v)) return '';
}
let txt = `[Interface]\n`;
txt += `PrivateKey = ${client.privateKey ?? ''}\n`;
txt += `Address = ${(client.allowedIPs ?? []).join(', ')}\n`;
const dns = [server.primaryDns, server.secondaryDns].filter((v) => !!v && v.trim() !== '');
if (dns.length > 0) txt += `DNS = ${dns.join(', ')}\n`;
if (typeof server.mtu === 'number' && server.mtu > 0) {
txt += `MTU = ${server.mtu}\n`;
}
txt += `Jc = ${server.jc}\n`;
txt += `Jmin = ${server.jmin}\n`;
txt += `Jmax = ${server.jmax}\n`;
txt += `S1 = ${server.s1}\n`;
txt += `S2 = ${server.s2}\n`;
if (server.s3) txt += `S3 = ${server.s3}\n`;
if (server.s4) txt += `S4 = ${server.s4}\n`;
txt += `${amneziaWGHLine('H1', server.h1, '1')}\n`;
txt += `${amneziaWGHLine('H2', server.h2, '2')}\n`;
txt += `${amneziaWGHLine('H3', server.h3, '3')}\n`;
txt += `${amneziaWGHLine('H4', server.h4, '4')}\n`;
if (server.i1) txt += `I1 = ${server.i1}\n`;
if (server.i2) txt += `I2 = ${server.i2}\n`;
if (server.i3) txt += `I3 = ${server.i3}\n`;
if (server.i4) txt += `I4 = ${server.i4}\n`;
if (server.i5) txt += `I5 = ${server.i5}\n`;
const optional31: Array<[string, string | undefined]> = [
['HeaderProtectionKey', server.headerProtectionKey],
['ContentPaddingAddition', server.contentPaddingAddition],
['RekeyAfterTime', server.rekeyAfterTime],
['RekeyTimeout', server.rekeyTimeout],
['RejectAfterTime', server.rejectAfterTime],
['KeepaliveTimeout', server.keepaliveTimeout],
['MaxHandshakeAttempts', server.maxHandshakeAttempts],
];
for (const [key, value] of optional31) {
if (value && value.trim() !== '') txt += `${key} = ${value}\n`;
}
if (server.randomTrailers) txt += `RandomTrailers = on\n`;
if (server.disableCookies) txt += `DisableCookies = on\n`;
// Peer field order follows wg-quick(8) and the panel's other two AmneziaWG
// emitters (amneziaWGConfigText in Go, buildAmneziaWGClientConfig); all three
// are independent implementations and must not drift apart.
txt += `\n# ${remark}\n`;
txt += `[Peer]\n`;
txt += `PublicKey = ${server.publicKey ?? ''}\n`;
if (client.preSharedKey && client.preSharedKey.length > 0) {
txt += `PresharedKey = ${client.preSharedKey}\n`;
}
txt += `AllowedIPs = 0.0.0.0/0, ::/0\n`;
txt += `Endpoint = ${address}:${port}`;
if (typeof client.keepAlive === 'number' && client.keepAlive > 0) {
txt += `\nPersistentKeepalive = ${client.keepAlive}`;
}
return txt;
}
export interface GenAmneziaWGFanoutInput {
inbound: Inbound;
remark?: string;
hostOverride?: string;
fallbackHostname: string;
}
export function genAmneziaWGLinks(input: GenAmneziaWGFanoutInput): string {
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'amneziawg') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
const settings = inbound.settings as AmneziawgInboundSettings;
const clients = settings.clients ?? [];
return clients
.map((c, i) =>
genAmneziaWGLink({
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(c)}`,
peerIndex: i,
}),
)
.join('\r\n');
}
export function genAmneziaWGConfigs(input: GenAmneziaWGFanoutInput): string {
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'amneziawg') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
const settings = inbound.settings as AmneziawgInboundSettings;
const clients = settings.clients ?? [];
return clients
.map((c, i) =>
genAmneziaWGConfig({
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(c)}`,
peerIndex: i,
}),
)
.join('\r\n');
}
export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
let url: URL;
try {
@@ -971,6 +1134,34 @@ export function wireguardConfigFromLink(link: string, fallbackRemark = ''): stri
return lines.join('\n');
}
// Reverse of toBase64Url above -- recovers a vpn:// link's plain .conf
// payload for display/copy/download/QR, the AmneziaWG counterpart of
// wireguardConfigFromLink. Simpler than that function: a vpn:// link's
// payload already *is* the .conf text (see genAmneziaWGLink's own doc
// comment), so there's nothing to reconstruct from query params -- just
// decode. Mirrors link-label.tsx's own private fromBase64Url (used there
// only to pull the remark/port back out for the tag label); duplicated
// rather than imported since both are tiny, self-contained, and each
// file already owns the matching encode or decode half of this pair.
function fromBase64Url(value: string): string {
const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new TextDecoder().decode(bytes);
}
export function amneziawgConfigFromLink(link: string): string {
const trimmed = link.trim();
if (!trimmed.startsWith('vpn://')) return '';
try {
return fromBase64Url(trimmed.slice('vpn://'.length));
} catch {
return '';
}
}
export type { WireguardInboundPeer };
function isUnixSocketListen(listen: string): boolean {
@@ -1282,7 +1473,7 @@ export interface GenInboundLinksInput {
// Top-level entrypoint that produces the full \r\n-joined block a user
// pastes into a client. Iterates per-client for protocols with clients,
// falls back to a single SS link for single-user 2022-blake3-chacha20,
// and emits per-peer .conf blocks for wireguard. Returns '' for the
// and emits per-peer .conf blocks for wireguard and amneziawg. Returns '' for the
// other clientless protocols (http, mixed, tunnel).
export function genInboundLinks(input: GenInboundLinksInput): string {
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
@@ -1308,6 +1499,9 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
if (inbound.protocol === 'wireguard') {
return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
}
if (inbound.protocol === 'amneziawg') {
return genAmneziaWGConfigs({ inbound, remark, hostOverride, fallbackHostname });
}
return '';
}
+1 -1
View File
@@ -14,7 +14,7 @@ function inboundTransports(
streamSettings: Record<string, unknown> | undefined,
settings: Record<string, unknown> | undefined,
): TransportBits {
if (protocol === 'hysteria' || protocol === 'wireguard') return UDP;
if (protocol === 'hysteria' || protocol === 'wireguard' || protocol === 'amneziawg') return UDP;
let bits: TransportBits = 0;
const network = asString(streamSettings?.network);
+28
View File
@@ -26,6 +26,7 @@ const PROTOCOL_LABELS: Record<string, string> = {
wireguard: 'WireGuard',
wg: 'WireGuard',
tg: 'MTProto',
vpn: 'AmneziaWG',
};
const PROTOCOL_COLORS: Record<string, string> = {
@@ -37,6 +38,7 @@ const PROTOCOL_COLORS: Record<string, string> = {
Hysteria2: 'magenta',
WireGuard: 'cyan',
MTProto: 'blue',
AmneziaWG: 'yellow',
};
const SECURITY_COLORS: Record<string, string> = {
@@ -50,6 +52,18 @@ const TRANSPORT_COLOR = 'gold';
const TAG_STYLE = { marginInlineEnd: 0, fontWeight: 600, letterSpacing: '0.3px' };
// Reverse of inbound-link.ts's own toBase64Url — base64url (RFC 4648 §5, no
// padding) back to the original unicode text, needed to read the remark/
// endpoint back out of a vpn:// link's opaque payload below.
function fromBase64Url(value: string): string {
const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return new TextDecoder().decode(bytes);
}
/* Pull protocol, transport, security plus the remark and port out of a share
link. vless/trojan carry network+security as `type`/`security` query params
and the remark in the URL hash; vmess packs them into the base64 JSON as
@@ -83,6 +97,20 @@ export function parseLinkParts(link: string): LinkParts | null {
} catch {
/* unparseable payload, fall back to protocol only */
}
} else if (scheme === 'vpn') {
/* AmneziaWG's vpn:// links are base64url of a plain .conf text (matching
the real AmneziaVPN app's own share-link scheme), not a structured URL
there's no query string or #hash to read a remark/port from without
corrupting the payload the app itself needs to decode. The remark and
endpoint are still in there as plain .conf lines, though, so pull them
back out directly. */
try {
const cfgText = fromBase64Url(trimmed.slice('vpn://'.length));
remark = /^#\s?(.*)$/m.exec(cfgText)?.[1]?.trim() ?? '';
port = /^Endpoint\s*=\s*.+:(\d+)\s*$/m.exec(cfgText)?.[1] ?? '';
} catch {
/* unparseable payload, fall back to protocol only */
}
} else {
try {
const url = new URL(trimmed);
@@ -75,10 +75,11 @@ export function canEnableStream(values: { protocol: string }): boolean {
return STREAM_PROTOCOLS.includes(values.protocol);
}
// mtproto is served by an external mtg process, not Xray, so the Xray sniffing
// block does not apply to it. Every other inbound supports sniffing.
// mtproto and amneziawg are served by an external process/interface, not
// Xray, so the Xray sniffing block does not apply to either. Every other
// inbound supports sniffing.
export function canEnableSniffing(values: { protocol: string }): boolean {
return values.protocol !== 'mtproto';
return values.protocol !== 'mtproto' && values.protocol !== 'amneziawg';
}
// Vision seed applies only when XTLS Vision (TCP/TLS) flow is selected
+4
View File
@@ -169,6 +169,10 @@ export class DBInbound {
return this.protocol === Protocols.WIREGUARD;
}
get isAmneziawg() {
return this.protocol === Protocols.AMNEZIAWG;
}
get isHysteria() {
return this.protocol === Protocols.HYSTERIA;
}
+1
View File
@@ -66,6 +66,7 @@ export class AllSetting {
subJsonMux = '';
subJsonRules = '';
subJsonFinalMask = '';
subJsonObservatory = '';
subThemeDir = '';
subHideSettings = false;
+8
View File
@@ -61,6 +61,11 @@ export interface XrayInfo {
color: string;
}
export interface AmneziaWGInfo {
configured: boolean;
running: boolean;
}
interface StatusInput {
cpu?: number;
cpuCores?: number;
@@ -79,6 +84,7 @@ interface StatusInput {
appUptime?: number;
appStats?: AppStats;
xray?: Partial<XrayInfo>;
amneziawg?: Partial<AmneziaWGInfo>;
}
export class Status {
@@ -99,6 +105,7 @@ export class Status {
appUptime = 0;
appStats: AppStats = { threads: 0, mem: 0, uptime: 0 };
xray: XrayInfo = { state: 'stop', errorMsg: '', version: '', color: '' };
amneziawg: AmneziaWGInfo = { configured: false, running: false };
constructor(data?: StatusInput | null) {
if (data == null) return;
@@ -121,5 +128,6 @@ export class Status {
this.appStats = data.appStats ?? this.appStats;
this.xray = { ...this.xray, ...(data.xray || {}) };
this.xray.color = XRAY_STATE_COLORS[this.xray.state] ?? 'gray';
this.amneziawg = { ...this.amneziawg, ...(data.amneziawg || {}) };
}
}
+154 -3
View File
@@ -608,6 +608,28 @@ export const sections: readonly Section[] = [
response:
'{\n "success": true,\n "obj": "2025/01/01 12:00:00 rejected vless proxy example.com reason: no valid user\\n2025/01/01 12:00:01 direct freedom ok"\n}',
},
{
method: 'POST',
path: '/panel/api/server/amneziawglogs/:count',
summary:
'Return live AmneziaWG peer activity (handshake, endpoint, transfer) plus the panels own AmneziaWG event lines.',
params: [
{
name: 'count',
in: 'path',
type: 'number',
desc: 'Maximum peer rows and event lines to return.',
},
{
name: 'filter',
in: 'body (form)',
type: 'string',
desc: 'Keyword filter — only rows/lines containing this string.',
},
],
body: 'filter=awg1',
responseSchema: 'AmneziaWGLogs',
},
{
method: 'POST',
path: '/panel/api/server/importDB',
@@ -844,13 +866,15 @@ export const sections: readonly Section[] = [
method: 'POST',
path: '/panel/api/clients/add',
summary:
'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.',
'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.',
description:
'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.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **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\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **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\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard 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.',
params: [
{
name: 'client',
in: 'body (json)',
type: 'object',
desc: 'Client fields: email, subId, id (uuid), password, auth, flow, totalGB, expiryTime, limitIp, limitHwid, tgId (numeric Telegram user ID, 0 = none), comment, enable.',
desc: 'Client fields: email, subId, id (uuid), password, auth, flow, totalGB, expiryTime, limitIp, limitHwid, tgId (numeric Telegram user ID, 0 = none), comment, enable. Protocol-specific: secret and adTag (mtproto), privateKey, publicKey, preSharedKey, allowedIPs and keepAlive (WireGuard).',
},
{
name: 'inboundIds',
@@ -898,6 +922,8 @@ export const sections: readonly Section[] = [
method: 'POST',
path: '/panel/api/clients/:email/attach',
summary: 'Attach an existing client to one or more additional inbounds. Body is JSON.',
description:
'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.',
params: [
{ name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' },
{
@@ -1187,6 +1213,16 @@ export const sections: readonly Section[] = [
'Clear all registered HWID devices for a client so new devices can register again.',
params: [{ name: 'email', in: 'path', type: 'string', desc: 'Client email.' }],
},
{
method: 'DELETE',
path: '/panel/api/clients/hwids/:email/:id',
summary:
'Remove a single registered HWID device by its id, freeing one slot under the HWID limit.',
params: [
{ name: 'email', in: 'path', type: 'string', desc: 'Client email.' },
{ name: 'id', in: 'path', type: 'number', desc: 'Device id, from the list endpoint.' },
],
},
{
method: 'POST',
path: '/panel/api/clients/onlines',
@@ -1685,7 +1721,7 @@ export const sections: readonly Section[] = [
id: 'xray-settings',
title: 'Xray Settings',
description:
'Xray configuration template, outbound management, Warp/Nord integration, and config testing. All endpoints under /panel/api/xray.',
'Xray configuration template, outbound management, Warp/Nord/PIA integration, and config testing. All endpoints under /panel/api/xray.',
endpoints: [
{
method: 'POST',
@@ -1785,6 +1821,43 @@ export const sections: readonly Section[] = [
{ name: 'key', in: 'body (form)', type: 'string', desc: 'Required when action=setKey.' },
],
},
{
method: 'POST',
path: '/panel/api/xray/pia/:action',
summary: 'Manage PIA WireGuard integration. The action parameter selects the operation.',
params: [
{
name: 'action',
in: 'path',
type: 'string',
desc: 'countries — list available countries from the signed PIA server list. servers — list regions and WireGuard servers in a country (sends countryCode). reg — sign in with a PIA username and password (sends username, password). data — return the signed-in account hint. del — delete stored PIA credentials. addKey — register a WireGuard key with the selected server (sends hostname) and return fields to build the outbound.',
},
{
name: 'username',
in: 'body (form)',
type: 'string',
desc: 'Required when action=reg.',
},
{
name: 'password',
in: 'body (form)',
type: 'string',
desc: 'Required when action=reg.',
},
{
name: 'countryCode',
in: 'body (form)',
type: 'string',
desc: 'Required when action=servers.',
},
{
name: 'hostname',
in: 'body (form)',
type: 'string',
desc: 'Required when action=addKey.',
},
],
},
{
method: 'POST',
path: '/panel/api/xray/resetOutboundsTraffic',
@@ -2138,6 +2211,84 @@ export const sections: readonly Section[] = [
],
},
{
id: 'sub-balancers',
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.',
endpoints: [
{
method: 'GET',
path: '/panel/api/sub-balancers',
summary: 'List all subscription balancers in sort order (sort_order asc, id asc).',
responseSchema: 'SubBalancer',
responseSchemaArray: true,
},
{
method: 'POST',
path: '/panel/api/sub-balancers',
summary:
'Create a subscription balancer. It appears in the JSON subscription of every client that sits on at least one selected inbound.',
params: [
{
name: 'remark',
in: 'body (form)',
type: 'string',
desc: 'Display label, used as the config remarks (required).',
},
{
name: 'strategy',
in: 'body (form)',
type: 'string',
desc: 'Balancer strategy: "leastLoad", "leastPing", "roundRobin" or "random" (xray routing balancer strategies). Default "random".',
},
{
name: 'inboundIds',
in: 'body (form)',
type: 'integer[]',
desc: 'Repeated form keys selecting the member inbounds, e.g. inboundIds=1&inboundIds=3 (required, at least one).',
},
{
name: 'sortOrder',
in: 'body (form)',
type: 'integer',
desc: '1-based position in the subscription list, interleaved with the inbounds subSortIndex. Default 1.',
},
{
name: 'enabled',
in: 'body (form)',
type: 'boolean',
desc: 'Whether the balancer is emitted. Default true.',
},
],
responseSchema: 'SubBalancer',
},
{
method: 'POST',
path: '/panel/api/sub-balancers/:id',
summary:
'Update a balancer by id. Accepts the same form fields as create (full-row update, including the enabled toggle).',
params: [{ name: 'id', in: 'path', type: 'integer', desc: 'Balancer id.' }],
responseSchema: 'SubBalancer',
},
{
method: 'DELETE',
path: '/panel/api/sub-balancers/:id',
summary: 'Delete a balancer by id.',
params: [{ name: 'id', in: 'path', type: 'integer', desc: 'Balancer id.' }],
responseSchema: 'SubBalancer',
},
{
method: 'POST',
path: '/panel/api/sub-balancers/:id/del',
summary:
'Delete a balancer by id (POST alias of DELETE for clients that cannot send DELETE).',
params: [{ name: 'id', in: 'path', type: 'integer', desc: 'Balancer id.' }],
responseSchema: 'SubBalancer',
},
],
},
{
id: 'subscription',
title: 'Subscription Server',
@@ -15,6 +15,7 @@ const MULTI_USER_PROTOCOLS = new Set([
'shadowsocks',
'wireguard',
'mtproto',
'amneziawg',
]);
interface BulkAttachInboundsModalProps {
@@ -15,6 +15,7 @@ const MULTI_USER_PROTOCOLS = new Set([
'shadowsocks',
'wireguard',
'mtproto',
'amneziawg',
]);
interface BulkDetachInboundsModalProps {
@@ -36,6 +36,7 @@ const MULTI_CLIENT_PROTOCOLS = new Set([
'trojan',
'hysteria',
'wireguard',
'amneziawg',
]);
const EMPTY: ClientBulkAddFormValues = {
+189 -145
View File
@@ -30,12 +30,15 @@ import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { Controller, FormProvider, useForm, useWatch, useFieldArray } from 'react-hook-form';
import { HttpUtil, RandomUtil, Wireguard } from '@/utils';
import { HttpUtil, IntlUtil, RandomUtil, Wireguard } from '@/utils';
import { formatInboundLabel } from '@/lib/inbounds/label';
import { generateMtprotoSecret } from '@/lib/xray/inbound-defaults';
import { normalizeClientIps, type ClientIpInfo } from '@/lib/clients/ip-log';
import { useDatepicker } from '@/hooks/useDatepicker';
import { useClientHwids } from '@/hooks/useClientHwids';
import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
import { FormField } from '@/components/form/rhf';
import ClientHwidListModal from '@/components/clients/ClientHwidList';
import { TLS_FLOW_CONTROL, TRAFFIC_RESETS } from '@/schemas/primitives';
import type {
ClientRecord,
@@ -57,6 +60,7 @@ const MULTI_CLIENT_PROTOCOLS = new Set([
'hysteria',
'wireguard',
'mtproto',
'amneziawg',
]);
const CLIENT_FORM_MODAL_Z_INDEX = 1000;
@@ -79,16 +83,6 @@ interface ApiMsg<T = unknown> {
obj?: T;
}
interface ClientHwidInfo {
id: number;
firstSeen: number;
lastSeen: number;
userAgent: string;
deviceOs: string;
osVersion: string;
deviceModel: string;
}
type Mode = 'add' | 'edit';
interface SaveMetaEdit {
@@ -117,6 +111,7 @@ interface ClientFormModalProps {
inbounds: InboundOption[];
attachedExternalLinks?: ExternalLink[];
attachedIds?: number[];
tunnelAllowedIPs?: Record<number, string>;
tgBotEnable?: boolean;
groups?: string[];
save: (
@@ -135,6 +130,8 @@ type Values = ClientFormValues & {
wgPublicKey: string;
wgPreSharedKey: string;
wgAllowedIPs: string;
awgAllowedIPs: string;
awgForwardedPorts: string;
secret: string;
adTag: string;
};
@@ -169,6 +166,8 @@ const EMPTY: Values = {
wgPublicKey: '',
wgPreSharedKey: '',
wgAllowedIPs: '',
awgAllowedIPs: '',
awgForwardedPorts: '',
secret: '',
adTag: '',
};
@@ -196,6 +195,34 @@ export function gbToBytes(gb: number): number {
return Math.round(gb * 1024 * 1024 * 1024);
}
export function parseAllowedIPsList(raw: string): string[] {
return raw
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '');
}
// Maps each of the two AllowedIPs fields to the specific wg/awg inbound the
// client is currently attached to, so a save with both protocols attached at
// once can send each its own value instead of one shared field ambiguously
// covering both (see model.Client.AllowedIPsByInbound on the Go side).
// Absent from the result when the client isn't actually attached to that
// protocol's inbound (e.g. mid-edit, before the attach takes effect).
export function resolveTunnelAllowedIPsByInbound(
attachedInboundIds: number[],
wireguardInboundIds: Set<number>,
amneziawgInboundIds: Set<number>,
wgAllowedIPs: string[],
awgAllowedIPs: string[],
): Record<number, string[]> {
const wgId = attachedInboundIds.find((id) => wireguardInboundIds.has(id));
const awgId = attachedInboundIds.find((id) => amneziawgInboundIds.has(id));
const result: Record<number, string[]> = {};
if (wgId != null) result[wgId] = wgAllowedIPs;
if (awgId != null) result[awgId] = awgAllowedIPs;
return result;
}
export function resolveTotalBytes(
originalBytes: number | null | undefined,
displayedGB: number,
@@ -213,6 +240,7 @@ export default function ClientFormModal({
inbounds,
attachedExternalLinks = [],
attachedIds = [],
tunnelAllowedIPs = {},
tgBotEnable = false,
groups = [],
save,
@@ -252,14 +280,44 @@ export default function ClientFormModal({
const [ipsLoading, setIpsLoading] = useState(false);
const [ipsClearing, setIpsClearing] = useState(false);
const [ipsModalOpen, setIpsModalOpen] = useState(false);
const [clientHwids, setClientHwids] = useState<ClientHwidInfo[]>([]);
const [hwidsLoading, setHwidsLoading] = useState(false);
const [hwidsClearing, setHwidsClearing] = useState(false);
const {
clientHwids,
hwidsLoading,
hwidsClearing,
deletingHwidId,
loadHwids,
clearHwids,
deleteHwid,
} = useClientHwids(client?.email);
const [hwidsModalOpen, setHwidsModalOpen] = useState(false);
const { datepicker } = useDatepicker();
const hwidDateLabel = (ts: number) =>
!ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker);
const fail2ban = useFail2banStatusQuery();
const limitIpDisabled = !fail2ban.usable;
const limitIpNotice = getLimitIpNotice(fail2ban, t);
// Declared ahead of the seeding effect below (which needs them to resolve
// which specific wg/awg inbound this client is attached to, for seeding
// wgAllowedIPs/awgAllowedIPs from tunnelAllowedIPs) -- both are pure
// derivations of the stable `inbounds` prop, so moving them earlier is
// just a declaration-order change, not a behavior change.
const wireguardIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
if (row && row.protocol === 'wireguard') ids.add(row.id);
}
return ids;
}, [inbounds]);
const amneziawgIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
if (row && row.protocol === 'amneziawg') ids.add(row.id);
}
return ids;
}, [inbounds]);
function addExternalLinkRow(kind: 'link' | 'subscription') {
appendExternalLink({
kind,
@@ -280,6 +338,13 @@ export default function ClientFormModal({
if (isEdit && client) {
const et = Number(client.expiryTime) || 0;
const seedIds = Array.isArray(attachedIds) ? attachedIds : [];
const attachedWireguardId = seedIds.find((id) => wireguardIds.has(id));
const attachedAmneziawgId = seedIds.find((id) => amneziawgIds.has(id));
const wgTunnelIPs =
attachedWireguardId != null ? tunnelAllowedIPs[attachedWireguardId] : undefined;
const awgTunnelIPs =
attachedAmneziawgId != null ? tunnelAllowedIPs[attachedAmneziawgId] : undefined;
const seed: Values = {
...EMPTY,
email: client.email || '',
@@ -310,7 +375,9 @@ export default function ClientFormModal({
wgPrivateKey: client.privateKey || '',
wgPublicKey: client.publicKey || '',
wgPreSharedKey: client.preSharedKey || '',
wgAllowedIPs: client.allowedIPs || '',
wgAllowedIPs: wgTunnelIPs ?? client.allowedIPs ?? '',
awgAllowedIPs: awgTunnelIPs ?? client.allowedIPs ?? '',
awgForwardedPorts: client.forwardedPorts || '',
secret: client.secret || '',
adTag: client.adTag || '',
};
@@ -367,14 +434,6 @@ export default function ClientFormModal({
return ids;
}, [inbounds]);
const wireguardIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
if (row && row.protocol === 'wireguard') ids.add(row.id);
}
return ids;
}, [inbounds]);
const mtprotoIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
@@ -429,6 +488,11 @@ export default function ClientFormModal({
[inboundIds, wireguardIds],
);
const showAmneziawg = useMemo(
() => (inboundIds || []).some((id) => amneziawgIds.has(id)),
[inboundIds, amneziawgIds],
);
const showMtproto = useMemo(
() => (inboundIds || []).some((id) => mtprotoIds.has(id)),
[inboundIds, mtprotoIds],
@@ -535,46 +599,11 @@ export default function ClientFormModal({
}
}
async function loadHwids() {
if (!isEdit || !client?.email) return;
setHwidsLoading(true);
try {
const msg = (await HttpUtil.post(
`/panel/api/clients/hwids/${encodeURIComponent(client.email)}`,
)) as ApiMsg<unknown[]>;
if (!msg?.success || !Array.isArray(msg.obj)) {
setClientHwids([]);
return;
}
setClientHwids(
msg.obj.filter(
(x): x is ClientHwidInfo =>
!!x && typeof x === 'object' && typeof (x as ClientHwidInfo).id === 'number',
),
);
} finally {
setHwidsLoading(false);
}
}
function openHwidsModal() {
setHwidsModalOpen(true);
if (clientHwids.length === 0) void loadHwids();
}
async function clearHwids() {
if (!isEdit || !client?.email) return;
setHwidsClearing(true);
try {
const msg = (await HttpUtil.delete(
`/panel/api/clients/hwids/${encodeURIComponent(client.email)}`,
)) as ApiMsg;
if (msg?.success) setClientHwids([]);
} finally {
setHwidsClearing(false);
}
}
function close() {
onOpenChange(false);
}
@@ -658,18 +687,40 @@ export default function ClientFormModal({
clientPayload.reverse = { tag: reverseTagValue };
}
if (showWireguard) {
if (showWireguard || showAmneziawg) {
// AmneziaWG peers are wire-identical to WireGuard peers (same
// privateKey/publicKey/preSharedKey/allowedIPs fields on model.Client),
// so both protocols share this one field set — see wgPrivateKey etc.
// below and the AmneziaWG-labeled variants of the same inputs.
clientPayload.privateKey = values.wgPrivateKey;
clientPayload.publicKey = values.wgPublicKey;
if (values.wgPreSharedKey) {
clientPayload.preSharedKey = values.wgPreSharedKey;
}
const allowedIPs = values.wgAllowedIPs
.split(',')
.map((s) => s.trim())
.filter((s) => s !== '');
if (allowedIPs.length > 0) {
clientPayload.allowedIPs = allowedIPs;
const wgAllowedIPs = parseAllowedIPsList(values.wgAllowedIPs);
if (showWireguard && showAmneziawg) {
// Both protocols are attached at once: the two fields hold genuinely
// different addresses, so each must land on its own inbound instead
// of one broadcast value overwriting the other's (allowedIPsByInbound
// is what Update/Create key their per-inbound override off of).
const awgAllowedIPs = parseAllowedIPsList(values.awgAllowedIPs);
clientPayload.allowedIPsByInbound = resolveTunnelAllowedIPsByInbound(
values.inboundIds || [],
wireguardIds,
amneziawgIds,
wgAllowedIPs,
awgAllowedIPs,
);
if (wgAllowedIPs.length > 0) {
clientPayload.allowedIPs = wgAllowedIPs;
}
} else if (wgAllowedIPs.length > 0) {
clientPayload.allowedIPs = wgAllowedIPs;
}
// Port-forwarding has no WireGuard equivalent — Xray-native WireGuard
// has no host-level iptables layer to hang per-client DNAT off of.
if (showAmneziawg) {
clientPayload.forwardedPorts = values.awgForwardedPorts.trim();
}
}
@@ -1137,9 +1188,15 @@ export default function ClientFormModal({
/>
</FormField>
)}
{showWireguard && (
{(showWireguard || showAmneziawg) && (
<>
<Form.Item label={t('pages.clients.wireguardPrivateKey')}>
<Form.Item
label={t(
showAmneziawg
? 'pages.clients.amneziaWgPrivateKey'
: 'pages.clients.wireguardPrivateKey',
)}
>
<Space.Compact style={{ display: 'flex' }}>
<Input
value={wgPrivateKey}
@@ -1162,23 +1219,67 @@ export default function ClientFormModal({
</Form.Item>
<FormField
name="wgPublicKey"
label={t('pages.clients.wireguardPublicKey')}
label={t(
showAmneziawg
? 'pages.clients.amneziaWgPublicKey'
: 'pages.clients.wireguardPublicKey',
)}
>
<Input disabled />
</FormField>
<FormField
name="wgPreSharedKey"
label={t('pages.clients.wireguardPreSharedKey')}
label={t(
showAmneziawg
? 'pages.clients.amneziaWgPreSharedKey'
: 'pages.clients.wireguardPreSharedKey',
)}
>
<Input />
</FormField>
<FormField
name="wgAllowedIPs"
label={t('pages.clients.wireguardAllowedIPs')}
extra={t('pages.clients.wireguardAllowedIPsHint')}
>
<Input placeholder="10.0.0.2/32" />
</FormField>
{showWireguard && showAmneziawg ? (
<>
<FormField
name="wgAllowedIPs"
label={t('pages.clients.wireguardAllowedIPs')}
extra={t('pages.clients.wireguardAllowedIPsHint')}
>
<Input placeholder="10.0.0.2/32" />
</FormField>
<FormField
name="awgAllowedIPs"
label={t('pages.clients.amneziaWgAllowedIPs')}
extra={t('pages.clients.amneziaWgAllowedIPsHint')}
>
<Input placeholder="10.8.1.2/32" />
</FormField>
</>
) : (
<FormField
name="wgAllowedIPs"
label={t(
showAmneziawg
? 'pages.clients.amneziaWgAllowedIPs'
: 'pages.clients.wireguardAllowedIPs',
)}
extra={t(
showAmneziawg
? 'pages.clients.amneziaWgAllowedIPsHint'
: 'pages.clients.wireguardAllowedIPsHint',
)}
>
<Input placeholder="10.8.1.2/32" />
</FormField>
)}
{showAmneziawg && (
<FormField
name="awgForwardedPorts"
label={t('pages.clients.amneziaWgForwardedPorts')}
extra={t('pages.clients.amneziaWgForwardedPortsHint')}
>
<Input placeholder="80, 443, 8000-8100" />
</FormField>
)}
</>
)}
{showMtproto && (
@@ -1431,77 +1532,20 @@ export default function ClientFormModal({
)}
</Modal>
<Modal
<ClientHwidListModal
open={hwidsModalOpen}
title={`${t('pages.clients.hwidLog')}${client?.email ? `${client.email}` : ''}`}
width={520}
email={client?.email}
zIndex={CLIENT_IP_LOG_MODAL_Z_INDEX}
onCancel={() => setHwidsModalOpen(false)}
footer={[
<Button
key="refresh"
icon={<ReloadOutlined />}
loading={hwidsLoading}
onClick={loadHwids}
>
{t('refresh')}
</Button>,
<Button
key="clear"
danger
loading={hwidsClearing}
disabled={clientHwids.length === 0}
onClick={clearHwids}
>
{t('pages.clients.clearAll')}
</Button>,
<Button key="close" type="primary" onClick={() => setHwidsModalOpen(false)}>
{t('close')}
</Button>,
]}
>
{clientHwids.length > 0 ? (
<div style={{ maxHeight: 360, overflowY: 'auto' }}>
{clientHwids.map((entry) => (
<div
key={entry.id}
style={{
borderBottom: '1px solid var(--ant-color-border-secondary)',
padding: '8px 0',
}}
>
<Typography.Text strong>
{entry.deviceModel || entry.userAgent || t('pages.clients.hwidDevice')}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{[entry.deviceOs, entry.osVersion].filter(Boolean).join(' ')}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{t('pages.clients.firstSeen')}:{' '}
{entry.firstSeen ? dayjs(entry.firstSeen).format('YYYY-MM-DD HH:mm') : '-'}
</Typography.Text>
<br />
<Typography.Text type="secondary">
{t('pages.clients.lastSeen')}:{' '}
{entry.lastSeen ? dayjs(entry.lastSeen).format('YYYY-MM-DD HH:mm') : '-'}
</Typography.Text>
{entry.userAgent && (
<>
<br />
<Typography.Text type="secondary" style={{ wordBreak: 'break-all' }}>
{entry.userAgent}
</Typography.Text>
</>
)}
</div>
))}
</div>
) : (
<Tag>{t('pages.clients.noHwids')}</Tag>
)}
</Modal>
hwids={clientHwids}
loading={hwidsLoading}
clearing={hwidsClearing}
deletingId={deletingHwidId}
formatDate={hwidDateLabel}
onRefresh={loadHwids}
onClearAll={clearHwids}
onDelete={deleteHwid}
onClose={() => setHwidsModalOpen(false)}
/>
</>
);
}
@@ -13,16 +13,23 @@ import { ClipboardManager, FileManager, HttpUtil, IntlUtil, SizeFormatter } from
import { formatInboundLabel } from '@/lib/inbounds/label';
import { normalizeClientIps, type ClientIpInfo } from '@/lib/clients/ip-log';
import { useDatepicker } from '@/hooks/useDatepicker';
import { useClientHwids } from '@/hooks/useClientHwids';
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
import { isPostQuantumLink } from '@/lib/xray/inbound-link';
import { LinkTags, linkMetaText, parseLinkParts } from '@/lib/xray/link-label';
import { QrPanel } from '@/pages/inbounds/qr';
import ClientHwidListModal from '@/components/clients/ClientHwidList';
import ConfigBlock from '@/components/clients/ConfigBlock';
import {
buildWireguardClientConfig,
findWireguardInbound,
isWireguardClient,
} from './wireguardConfig';
import {
buildAmneziaWGClientConfig,
findAmneziaWGInbound,
isAmneziaWGClient,
} from './amneziawgConfig';
import './ClientInfoModal.css';
const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
@@ -33,6 +40,7 @@ const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
hysteria: 'cyan',
hysteria2: 'green',
wireguard: 'gold',
amneziawg: 'yellow',
http: 'purple',
mixed: 'lime',
tunnel: 'orange',
@@ -54,6 +62,7 @@ interface ClientInfoModalProps {
open: boolean;
client: ClientRecord | null;
inboundsById: Record<number, InboundOption>;
tunnelAllowedIPs?: Record<number, string>;
isOnline: boolean;
subSettings?: SubSettings;
onOpenChange: (open: boolean) => void;
@@ -84,6 +93,7 @@ export default function ClientInfoModal({
open,
client,
inboundsById,
tunnelAllowedIPs,
isOnline,
subSettings = DEFAULT_SUB,
onOpenChange,
@@ -105,6 +115,17 @@ export default function ClientInfoModal({
const [ipsLoading, setIpsLoading] = useState(false);
const [ipsClearing, setIpsClearing] = useState(false);
const [ipsModalOpen, setIpsModalOpen] = useState(false);
const {
clientHwids,
hwidsLoading,
hwidsClearing,
deletingHwidId,
loadHwids,
clearHwids,
deleteHwid,
resetHwids,
} = useClientHwids(client?.email);
const [hwidsModalOpen, setHwidsModalOpen] = useState(false);
const [downloadingFormat, setDownloadingFormat] = useState<
keyof typeof SUBSCRIPTION_DOWNLOAD_NAMES | null
>(null);
@@ -118,6 +139,8 @@ export default function ClientInfoModal({
setLinks([]);
setClientIps([]);
setIpsModalOpen(false);
resetHwids();
setHwidsModalOpen(false);
}
}
@@ -171,6 +194,22 @@ export default function ClientInfoModal({
);
}, [client, wgInbound, subSettings?.publicHost]);
const awgInbound = useMemo(
() => findAmneziaWGInbound(client, inboundsById),
[client, inboundsById],
);
const awgConfigText = useMemo(() => {
if (!client || !awgInbound || !isAmneziaWGClient(client)) return '';
const address = awgInbound ? (tunnelAllowedIPs?.[awgInbound.id] ?? '') : '';
return buildAmneziaWGClientConfig(
client,
awgInbound,
window.location.hostname,
subSettings?.publicHost ?? '',
address,
);
}, [client, awgInbound, tunnelAllowedIPs, subSettings?.publicHost]);
async function copyValue(text: string) {
if (!text) return;
const ok = await ClipboardManager.copyText(String(text));
@@ -230,6 +269,11 @@ export default function ClientInfoModal({
if (clientIps.length === 0) void loadIps();
}
function openHwidsModal() {
setHwidsModalOpen(true);
if (clientHwids.length === 0) void loadHwids();
}
return (
<>
{messageContextHolder}
@@ -419,6 +463,24 @@ export default function ClientInfoModal({
</td>
</tr>
)}
<tr>
<td>{t('pages.clients.limitHwid')}</td>
<td>{!client.limitHwid ? <Tag></Tag> : <Tag>{client.limitHwid}</Tag>}</td>
</tr>
<tr>
<td>{t('pages.clients.hwidLog')}</td>
<td>
<Button
size="small"
icon={<EyeOutlined />}
aria-label={t('pages.clients.hwidLog')}
loading={hwidsLoading}
onClick={openHwidsModal}
>
{clientHwids.length > 0 ? clientHwids.length : ''}
</Button>
</td>
</tr>
<tr>
<td>{t('pages.inbounds.createdAt')}</td>
<td>
@@ -728,6 +790,18 @@ export default function ClientInfoModal({
/>
</>
)}
{awgConfigText && client && (
<>
<Divider>{t('pages.clients.amneziaWgConfig')}</Divider>
<ConfigBlock
label={t('pages.clients.config')}
text={awgConfigText}
fileName={`${client.email}.conf`}
qrRemark={client.email || 'peer'}
/>
</>
)}
</>
)}
</Modal>
@@ -784,6 +858,20 @@ export default function ClientInfoModal({
<Tag>{t('tgbot.noIpRecord')}</Tag>
)}
</Modal>
<ClientHwidListModal
open={hwidsModalOpen}
email={client?.email}
hwids={clientHwids}
loading={hwidsLoading}
clearing={hwidsClearing}
deletingId={deletingHwidId}
formatDate={dateLabel}
onRefresh={loadHwids}
onClearAll={clearHwids}
onDelete={deleteHwid}
onClose={() => setHwidsModalOpen(false)}
/>
</>
);
}
+43 -2
View File
@@ -11,6 +11,11 @@ import {
findWireguardInbound,
isWireguardClient,
} from './wireguardConfig';
import {
buildAmneziaWGClientConfig,
findAmneziaWGInbound,
isAmneziaWGClient,
} from './amneziawgConfig';
interface SubSettings {
enable: boolean;
@@ -24,6 +29,7 @@ interface ClientQrModalProps {
open: boolean;
client: ClientRecord | null;
inboundsById: Record<number, InboundOption>;
tunnelAllowedIPs?: Record<number, string>;
subSettings?: SubSettings;
onOpenChange: (open: boolean) => void;
}
@@ -45,6 +51,7 @@ export default function ClientQrModal({
open,
client,
inboundsById,
tunnelAllowedIPs,
subSettings = DEFAULT_SUB,
onOpenChange,
}: ClientQrModalProps) {
@@ -74,7 +81,24 @@ export default function ClientQrModal({
);
}, [client, wgInbound, subSettings?.publicHost]);
const hasAnything = !!subLink || !!subJsonLink || !!wgConfigText || links.length > 0;
const awgInbound = useMemo(
() => findAmneziaWGInbound(client, inboundsById),
[client, inboundsById],
);
const awgConfigText = useMemo(() => {
if (!client || !awgInbound || !isAmneziaWGClient(client)) return '';
const address = awgInbound ? (tunnelAllowedIPs?.[awgInbound.id] ?? '') : '';
return buildAmneziaWGClientConfig(
client,
awgInbound,
window.location.hostname,
subSettings?.publicHost ?? '',
address,
);
}, [client, awgInbound, tunnelAllowedIPs, subSettings?.publicHost]);
const hasAnything =
!!subLink || !!subJsonLink || !!wgConfigText || !!awgConfigText || links.length > 0;
// The reset runs during render so the effect only carries the request.
const openSubId = open ? (client?.subId ?? '') : '';
@@ -165,8 +189,25 @@ export default function ClientQrModal({
),
});
}
if (awgConfigText) {
out.push({
key: 'awg-config',
label: (
<Tag color="purple" style={{ margin: 0 }}>
{t('pages.clients.amneziaWgConfig')}
</Tag>
),
children: (
<QrPanel
value={awgConfigText}
remark={client?.email || 'peer'}
downloadName={`${client?.email || 'peer'}.conf`}
/>
),
});
}
return out;
}, [subLink, subJsonLink, wgConfigText, links, client?.email, t]);
}, [subLink, subJsonLink, wgConfigText, awgConfigText, links, client?.email, t]);
// Expanding the first panel is a render-time adjustment, not a side effect.
const firstKey = open && items.length > 0 ? items[0].key : null;
@@ -171,6 +171,7 @@ const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
hysteria: 'cyan',
hysteria2: 'green',
wireguard: 'gold',
amneziawg: 'yellow',
http: 'purple',
mixed: 'lime',
tunnel: 'orange',
@@ -349,10 +350,16 @@ export default function ClientsPage() {
const [editingClient, setEditingClient] = useState<ClientRecord | null>(null);
const [editingAttachedIds, setEditingAttachedIds] = useState<number[]>([]);
const [editingExternalLinks, setEditingExternalLinks] = useState<ExternalLink[]>([]);
const [editingTunnelAllowedIPs, setEditingTunnelAllowedIPs] = useState<Record<number, string>>(
{},
);
const [infoOpen, setInfoOpen] = useState(false);
const [infoClient, setInfoClient] = useState<ClientRecord | null>(null);
const [qrOpen, setQrOpen] = useState(false);
const [qrClient, setQrClient] = useState<ClientRecord | null>(null);
const [viewingTunnelAllowedIPs, setViewingTunnelAllowedIPs] = useState<Record<number, string>>(
{},
);
const [bulkAddOpen, setBulkAddOpen] = useState(false);
const [bulkAdjustOpen, setBulkAdjustOpen] = useState(false);
const [subLinksOpen, setSubLinksOpen] = useState(false);
@@ -619,6 +626,7 @@ export default function ClientsPage() {
setEditingClient(null);
setEditingAttachedIds([]);
setEditingExternalLinks([]);
setEditingTunnelAllowedIPs({});
setFormOpen(true);
}
@@ -635,6 +643,7 @@ export default function ClientsPage() {
const ids = full?.inboundIds ?? (Array.isArray(row.inboundIds) ? row.inboundIds : []);
setEditingAttachedIds([...ids]);
setEditingExternalLinks(Array.isArray(full?.externalLinks) ? [...full.externalLinks] : []);
setEditingTunnelAllowedIPs(full?.tunnelAllowedIPs ?? {});
setFormOpen(true);
},
[hydrate],
@@ -686,6 +695,7 @@ export default function ClientsPage() {
if (!row) return;
const full = await hydrate(row.email);
setInfoClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
setViewingTunnelAllowedIPs(full?.tunnelAllowedIPs ?? {});
setInfoOpen(true);
},
[hydrate],
@@ -697,6 +707,7 @@ export default function ClientsPage() {
if (!row) return;
const full = await hydrate(row.email);
setQrClient(full ? { ...row, ...full.client, inboundIds: full.inboundIds } : row);
setViewingTunnelAllowedIPs(full?.tunnelAllowedIPs ?? {});
setQrOpen(true);
},
[hydrate],
@@ -1838,6 +1849,7 @@ export default function ClientsPage() {
client={editingClient}
attachedIds={editingAttachedIds}
attachedExternalLinks={editingExternalLinks}
tunnelAllowedIPs={editingTunnelAllowedIPs}
inbounds={inbounds}
tgBotEnable={tgBotEnable}
groups={allGroups}
@@ -1851,6 +1863,7 @@ export default function ClientsPage() {
open={infoOpen}
client={infoClient}
inboundsById={inboundsById}
tunnelAllowedIPs={viewingTunnelAllowedIPs}
isOnline={infoClient ? isOnline(infoClient.email) : false}
subSettings={subSettings}
onOpenChange={setInfoOpen}
@@ -1861,6 +1874,7 @@ export default function ClientsPage() {
open={qrOpen}
client={qrClient}
inboundsById={inboundsById}
tunnelAllowedIPs={viewingTunnelAllowedIPs}
subSettings={subSettings}
onOpenChange={setQrOpen}
/>
@@ -0,0 +1,110 @@
import { formatInboundLabel } from '@/lib/inbounds/label';
import { preferPublicHost, resolveShareHost } from '@/lib/xray/inbound-link';
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
// AmneziaWG clients are wire-identical to WireGuard clients (same
// privateKey/publicKey/allowedIPs/preSharedKey/keepAlive fields on
// model.Client — see wireguardConfig.ts's isWireguardClient), so this duck
// type can't tell the two protocols apart on its own; findAmneziaWGInbound's
// protocol==='amneziawg' filter below is what actually disambiguates.
export function isAmneziaWGClient(client: ClientRecord | null | undefined): boolean {
if (!client) return false;
return !!(
client.privateKey ||
client.publicKey ||
client.allowedIPs ||
client.preSharedKey ||
client.keepAlive
);
}
export function findAmneziaWGInbound(
client: ClientRecord | null | undefined,
inboundsById: Record<number, InboundOption>,
): InboundOption | undefined {
return (client?.inboundIds || [])
.map((id) => inboundsById[id])
.find((ib) => ib?.protocol === 'amneziawg');
}
// h4Line renders one H magic-header line, matching the Go backend's
// hOrDefault fallback (blank -> the classic 1/2/3/4 WireGuard message type).
function hLine(key: string, value: string | undefined, fallback: string): string {
return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
}
// addressOverride carries this inbound's own AllowedIPs (ClientHydrateSchema's
// tunnelAllowedIPs). ClientRecord.allowedIPs is a single shared column, so for
// an identity attached to both WireGuard and AmneziaWG it holds the WireGuard
// address — writing that into the AmneziaWG .conf yields an unroutable peer.
export function buildAmneziaWGClientConfig(
client: ClientRecord,
inbound: InboundOption | undefined,
host = window.location.hostname,
publicHost = '',
addressOverride = '',
): string {
const server = inbound?.awgServer;
const endpointHost = resolveShareHost(
inbound ?? {},
inbound?.nodeAddress ?? '',
preferPublicHost(host, publicHost),
);
const address = addressOverride || client.allowedIPs || '10.8.1.2/32';
const endpoint = `${endpointHost}:${inbound?.port || ''}`;
const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : '';
const remark = [inboundName, client.email, client.comment].filter(Boolean).join(' - ');
// These land unescaped in [Interface]; a newline here would inject a
// config line (e.g. a rogue PostUp) into the downloaded .conf.
const privateKey = client.privateKey || client.password || '';
for (const v of [privateKey, server?.primaryDns ?? '', server?.secondaryDns ?? '', remark]) {
if (/[\r\n]/.test(v)) return '';
}
const dnsParts = [server?.primaryDns, server?.secondaryDns].filter((v) => !!v && v.trim() !== '');
const lines = ['[Interface]', `PrivateKey = ${privateKey}`, `Address = ${address}`];
if (dnsParts.length > 0) lines.push(`DNS = ${dnsParts.join(', ')}`);
if (server?.mtu && server.mtu > 0) lines.push(`MTU = ${server.mtu}`);
// AmneziaWG obfuscation parameters — must match the server's values.
lines.push(`Jc = ${server?.jc ?? 5}`);
lines.push(`Jmin = ${server?.jmin ?? 10}`);
lines.push(`Jmax = ${server?.jmax ?? 50}`);
lines.push(`S1 = ${server?.s1 ?? 30}`);
lines.push(`S2 = ${server?.s2 ?? 45}`);
if (server?.s3) lines.push(`S3 = ${server.s3}`);
if (server?.s4) lines.push(`S4 = ${server.s4}`);
lines.push(hLine('H1', server?.h1, '1'));
lines.push(hLine('H2', server?.h2, '2'));
lines.push(hLine('H3', server?.h3, '3'));
lines.push(hLine('H4', server?.h4, '4'));
if (server?.i1) lines.push(`I1 = ${server.i1}`);
if (server?.i2) lines.push(`I2 = ${server.i2}`);
if (server?.i3) lines.push(`I3 = ${server.i3}`);
if (server?.i4) lines.push(`I4 = ${server.i4}`);
if (server?.i5) lines.push(`I5 = ${server.i5}`);
const optional31: Array<[string, string | undefined]> = [
['HeaderProtectionKey', server?.headerProtectionKey],
['ContentPaddingAddition', server?.contentPaddingAddition],
['RekeyAfterTime', server?.rekeyAfterTime],
['RekeyTimeout', server?.rekeyTimeout],
['RejectAfterTime', server?.rejectAfterTime],
['KeepaliveTimeout', server?.keepaliveTimeout],
['MaxHandshakeAttempts', server?.maxHandshakeAttempts],
];
for (const [key, value] of optional31) {
if (value && value.trim() !== '') lines.push(`${key} = ${value}`);
}
if (server?.randomTrailers) lines.push('RandomTrailers = on');
if (server?.disableCookies) lines.push('DisableCookies = on');
lines.push('');
if (remark) lines.push(`# ${remark}`);
lines.push('[Peer]', `PublicKey = ${server?.publicKey || ''}`);
if (client.preSharedKey) lines.push(`PresharedKey = ${client.preSharedKey}`);
lines.push('AllowedIPs = 0.0.0.0/0, ::/0', `Endpoint = ${endpoint}`);
if (client.keepAlive && client.keepAlive > 0)
lines.push(`PersistentKeepalive = ${client.keepAlive}`);
return lines.join('\n');
}
+1
View File
@@ -39,6 +39,7 @@ const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
hysteria: 'cyan',
hysteria2: 'green',
wireguard: 'gold',
amneziawg: 'yellow',
http: 'purple',
mixed: 'lime',
tunnel: 'orange',
+17 -2
View File
@@ -25,8 +25,14 @@ import {
import { HttpUtil, SizeFormatter, RandomUtil } from '@/utils';
import { buildClonePayload } from '@/lib/xray/inbound-clone';
import { NODE_ELIGIBLE_PROTOCOLS } from '@/lib/xray/node-protocols';
import { genInboundLinks, genWireguardLinks, preferPublicHost } from '@/lib/xray/inbound-link';
import {
genAmneziaWGLinks,
genInboundLinks,
genWireguardLinks,
preferPublicHost,
} from '@/lib/xray/inbound-link';
import { inboundFromDb } from '@/lib/xray/inbound-from-db';
import { Protocols } from '@/schemas/primitives';
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
@@ -335,7 +341,16 @@ export default function InboundsPage() {
content: genWireguardLinks(genInput),
},
]
: undefined;
: projected.protocol === Protocols.AMNEZIAWG
? [
{ key: 'config', label: t('pages.clients.config'), content },
{
key: 'links',
label: t('pages.clients.tabLinks'),
content: genAmneziaWGLinks(genInput),
},
]
: undefined;
openText({
title: t('pages.inbounds.exportLinksTitle'),
content,
@@ -21,6 +21,7 @@ import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter, Wireguard } from
import type { RealityScanResult } from '@/generated/types';
import { rawInboundToFormValues, formValuesToWirePayload } from '@/lib/xray/inbound-form-adapter';
import { createDefaultInboundSettings } from '@/lib/xray/inbound-defaults';
import { generateAwgObfuscation } from '@/lib/xray/amneziawg-obfuscation';
import { composeInboundTag, isAutoInboundTag, type InboundTagInput } from '@/lib/xray/inbound-tag';
import {
canEnableReality,
@@ -56,6 +57,7 @@ import './InboundFormModal.css';
import { AdvancedAllEditor, AdvancedSliceEditor } from './advanced-editors';
import { formatInboundIssue, formatInboundValidation } from './formatValidationError';
import {
AmneziawgFields,
HttpFields,
HysteriaFields,
MixedFields,
@@ -347,6 +349,41 @@ export default function InboundFormModal({
setV('settings.secretKey', kp.privateKey);
};
// AmneziaWG uses the same Curve25519 keys as WireGuard, just nested under
// settings.server instead of flat on settings — see amneziawg.ts. 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, so it must be kept in
// sync even when the user free-types a new private key instead of using
// the regenerate button.
const awgPrivateKey = useWatch({ control, name: 'settings.server.privateKey' });
const awgPubKey =
typeof awgPrivateKey === 'string' && awgPrivateKey.length > 0
? Wireguard.generateKeypair(awgPrivateKey).publicKey
: '';
useEffect(() => {
if (protocol === Protocols.AMNEZIAWG) {
setV('settings.server.publicKey', awgPubKey);
}
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, [awgPubKey, protocol]);
const regenInboundAwg = () => {
const kp = Wireguard.generateKeypair();
setV('settings.server.privateKey', kp.privateKey);
setV('settings.server.publicKey', kp.publicKey);
};
// Randomizes the AmneziaWG 3.1 obfuscation set client-side; the shared
// generator mirrors the Go backend's amneziawg.GenerateObfuscation31.
const regenInboundAwgObfuscation = () => {
const obf = generateAwgObfuscation();
for (const [field, value] of Object.entries(obf)) {
setV(`settings.server.${field}`, value);
}
};
const matchesVlessAuth = (
block: { id?: string; label?: string } | undefined | null,
authId: string,
@@ -740,6 +777,14 @@ export default function InboundFormModal({
<WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} />
)}
{protocol === Protocols.AMNEZIAWG && (
<AmneziawgFields
awgPubKey={awgPubKey}
regenInboundAwg={regenInboundAwg}
regenInboundAwgObfuscation={regenInboundAwgObfuscation}
/>
)}
{protocol === Protocols.TUN && <TunFields />}
{protocol === Protocols.TUNNEL && <TunnelFields />}
@@ -1077,6 +1122,7 @@ export default function InboundFormModal({
Protocols.TUN,
Protocols.WIREGUARD,
Protocols.MTPROTO,
Protocols.AMNEZIAWG,
] as string[]
).includes(protocol) || isFallbackHost
? [
@@ -0,0 +1,216 @@
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Space, Switch } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { FormField } from '@/components/form/rhf';
interface AmneziawgFieldsProps {
awgPubKey: string;
regenInboundAwg: () => void;
regenInboundAwgObfuscation: () => void;
}
export default function AmneziawgFields({
awgPubKey,
regenInboundAwg,
regenInboundAwgObfuscation,
}: AmneziawgFieldsProps) {
const { t } = useTranslation();
return (
<>
<Form.Item label={t('pages.xray.amneziawg.privateKey')}>
<Space.Compact block>
<FormField name={['settings', 'server', 'privateKey']} noStyle>
<Input style={{ width: 'calc(100% - 32px)' }} />
</FormField>
<Button
aria-label={t('regenerate')}
icon={<ReloadOutlined />}
onClick={regenInboundAwg}
/>
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.xray.amneziawg.publicKey')}>
<Input value={awgPubKey} disabled />
</Form.Item>
<FormField
name={['settings', 'server', 'subnetIp']}
label={t('pages.xray.amneziawg.subnetIp')}
>
<Input placeholder="10.8.1.0" />
</FormField>
<FormField
name={['settings', 'server', 'subnetCidr']}
label={t('pages.xray.amneziawg.subnetCidr')}
>
<InputNumber min={1} max={32} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 'mtu']} label={t('pages.xray.amneziawg.mtu')}>
<InputNumber min={1} style={{ width: '100%' }} />
</FormField>
<FormField
name={['settings', 'server', 'primaryDns']}
label={t('pages.xray.amneziawg.primaryDns')}
>
<Input placeholder="8.8.8.8" />
</FormField>
<FormField
name={['settings', 'server', 'secondaryDns']}
label={t('pages.xray.amneziawg.secondaryDns')}
>
<Input placeholder="8.8.4.4" />
</FormField>
<FormField
name={['settings', 'server', 'externalInterface']}
label={t('pages.xray.amneziawg.externalInterface')}
extra={t('pages.xray.amneziawg.externalInterfaceHint')}
>
<Input placeholder="eth0" />
</FormField>
<FormField
name={['settings', 'server', 'ipv6Enabled']}
label={t('pages.xray.amneziawg.ipv6Enabled')}
valueProp="checked"
>
<Switch />
</FormField>
<FormField
name={['settings', 'server', 'ipv6Subnet']}
label={t('pages.xray.amneziawg.ipv6Subnet')}
extra={t('pages.xray.amneziawg.ipv6SubnetHint')}
>
<Input placeholder="fd86:ea04:1115::/64" />
</FormField>
<FormField
name={['settings', 'server', 'ipv6ExternalInterface']}
label={t('pages.xray.amneziawg.ipv6ExternalInterface')}
extra={t('pages.xray.amneziawg.ipv6ExternalInterfaceHint')}
>
<Input placeholder="eth0" />
</FormField>
<Form.Item label={t('pages.xray.amneziawg.obfuscation')}>
<Button icon={<ReloadOutlined />} onClick={regenInboundAwgObfuscation}>
{t('pages.xray.amneziawg.regenerateObfuscation')}
</Button>
</Form.Item>
<FormField name={['settings', 'server', 'jc']} label={t('pages.xray.amneziawg.jc')}>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 'jmin']} label={t('pages.xray.amneziawg.jmin')}>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 'jmax']} label={t('pages.xray.amneziawg.jmax')}>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 's1']} label={t('pages.xray.amneziawg.s1')}>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 's2']} label={t('pages.xray.amneziawg.s2')}>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 's3']} label={t('pages.xray.amneziawg.s3')}>
<InputNumber min={0} max={64} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'server', 's4']} label={t('pages.xray.amneziawg.s4')}>
<InputNumber min={0} max={32} style={{ width: '100%' }} />
</FormField>
<FormField
name={['settings', 'server', 'h1']}
label={t('pages.xray.amneziawg.h1')}
extra={t('pages.xray.amneziawg.hHint')}
>
<Input placeholder="1 or 100-800" />
</FormField>
<FormField name={['settings', 'server', 'h2']} label={t('pages.xray.amneziawg.h2')}>
<Input placeholder="2 or 100-800" />
</FormField>
<FormField name={['settings', 'server', 'h3']} label={t('pages.xray.amneziawg.h3')}>
<Input placeholder="3 or 100-800" />
</FormField>
<FormField name={['settings', 'server', 'h4']} label={t('pages.xray.amneziawg.h4')}>
<Input placeholder="4 or 100-800" />
</FormField>
<FormField
name={['settings', 'server', 'i1']}
label={t('pages.xray.amneziawg.i1')}
extra={t('pages.xray.amneziawg.i1Hint')}
>
<Input placeholder="<r 64>" />
</FormField>
<FormField name={['settings', 'server', 'i2']} label={t('pages.xray.amneziawg.i2')}>
<Input placeholder="<r 64>" />
</FormField>
<FormField name={['settings', 'server', 'i3']} label={t('pages.xray.amneziawg.i3')}>
<Input placeholder="<r 64>" />
</FormField>
<FormField name={['settings', 'server', 'i4']} label={t('pages.xray.amneziawg.i4')}>
<Input placeholder="<r 64>" />
</FormField>
<FormField name={['settings', 'server', 'i5']} label={t('pages.xray.amneziawg.i5')}>
<Input placeholder="<r 64>" />
</FormField>
<FormField
name={['settings', 'server', 'headerProtectionKey']}
label={t('pages.xray.amneziawg.headerProtectionKey')}
extra={t('pages.xray.amneziawg.headerProtectionKeyHint')}
>
<Input />
</FormField>
<FormField
name={['settings', 'server', 'contentPaddingAddition']}
label={t('pages.xray.amneziawg.contentPaddingAddition')}
extra={t('pages.xray.amneziawg.contentPaddingAdditionHint')}
>
<Input placeholder="8-64" />
</FormField>
<FormField
name={['settings', 'server', 'rekeyAfterTime']}
label={t('pages.xray.amneziawg.rekeyAfterTime')}
extra={t('pages.xray.amneziawg.timingRangeHint')}
>
<Input placeholder="100-160" />
</FormField>
<FormField
name={['settings', 'server', 'rekeyTimeout']}
label={t('pages.xray.amneziawg.rekeyTimeout')}
>
<Input placeholder="3-10" />
</FormField>
<FormField
name={['settings', 'server', 'rejectAfterTime']}
label={t('pages.xray.amneziawg.rejectAfterTime')}
>
<Input placeholder="190-250" />
</FormField>
<FormField
name={['settings', 'server', 'keepaliveTimeout']}
label={t('pages.xray.amneziawg.keepaliveTimeout')}
>
<Input placeholder="8-20" />
</FormField>
<FormField
name={['settings', 'server', 'maxHandshakeAttempts']}
label={t('pages.xray.amneziawg.maxHandshakeAttempts')}
extra={t('pages.xray.amneziawg.maxHandshakeAttemptsHint')}
>
<Input placeholder="15-50" />
</FormField>
<FormField
name={['settings', 'server', 'randomTrailers']}
label={t('pages.xray.amneziawg.randomTrailers')}
extra={t('pages.xray.amneziawg.randomTrailersHint')}
valueProp="checked"
>
<Switch />
</FormField>
<FormField
name={['settings', 'server', 'disableCookies']}
label={t('pages.xray.amneziawg.disableCookies')}
extra={t('pages.xray.amneziawg.disableCookiesHint')}
valueProp="checked"
>
<Switch />
</FormField>
</>
);
}
@@ -7,3 +7,4 @@ export { default as HttpFields } from './http';
export { default as MixedFields } from './mixed';
export { default as MtprotoFields } from './mtproto';
export { default as VlessFields } from './vless';
export { default as AmneziawgFields } from './amneziawg';
@@ -24,6 +24,12 @@ export default function WireguardFields({ wgPubKey, regenInboundWg }: WireguardF
<Form.Item label={t('pages.xray.wireguard.publicKey')}>
<Input value={wgPubKey} disabled />
</Form.Item>
<FormField name={['settings', 'subnetIp']} label={t('pages.xray.wireguard.subnetIp')}>
<Input placeholder="10.0.0.0" />
</FormField>
<FormField name={['settings', 'subnetCidr']} label={t('pages.xray.wireguard.subnetCidr')}>
<InputNumber min={1} max={32} style={{ width: '100%' }} />
</FormField>
<FormField name={['settings', 'mtu']} label="MTU">
<InputNumber />
</FormField>
@@ -10,6 +10,8 @@ import { InfinityIcon } from '@/components/ui';
import { useDatepicker } from '@/hooks/useDatepicker';
import {
genAllLinks,
genAmneziaWGConfigs,
genAmneziaWGLinks,
genWireguardConfigs,
genWireguardLinks,
preferPublicHost,
@@ -49,6 +51,8 @@ export default function InboundInfoModal({
const [links, setLinks] = useState<{ remark?: string; link: string }[]>([]);
const [wireguardConfigs, setWireguardConfigs] = useState<string[]>([]);
const [wireguardLinks, setWireguardLinks] = useState<string[]>([]);
const [amneziawgConfigs, setAmneziawgConfigs] = useState<string[]>([]);
const [amneziawgLinks, setAmneziawgLinks] = useState<string[]>([]);
const [subLink, setSubLink] = useState('');
const [subJsonLink, setSubJsonLink] = useState('');
const [refreshing, setRefreshing] = useState(false);
@@ -153,6 +157,28 @@ export default function InboundInfoModal({
fallbackHostname,
}).split('\r\n'),
);
setAmneziawgConfigs([]);
setAmneziawgLinks([]);
setLinks([]);
} else if (info.protocol === Protocols.AMNEZIAWG) {
setAmneziawgConfigs(
genAmneziaWGConfigs({
inbound: inboundForLinks,
remark: dbInbound.remark,
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
);
setAmneziawgLinks(
genAmneziaWGLinks({
inbound: inboundForLinks,
remark: dbInbound.remark,
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
);
setWireguardConfigs([]);
setWireguardLinks([]);
setLinks([]);
} else {
setLinks(
@@ -166,6 +192,8 @@ export default function InboundInfoModal({
);
setWireguardConfigs([]);
setWireguardLinks([]);
setAmneziawgConfigs([]);
setAmneziawgLinks([]);
}
if (clientSet?.subId) {
@@ -1198,6 +1226,58 @@ export default function InboundInfoModal({
</>
)}
{inbound?.protocol === Protocols.AMNEZIAWG && amneziawgConfigs.length > 0 && (
<>
<Divider>{t('pages.inbounds.copyLink')}</Divider>
{amneziawgConfigs.map((cfg, idx) => (
<Fragment key={idx}>
{cfg && (
<div className="link-panel">
<div className="link-panel-header">
<Tag color="green">
{t('pages.inbounds.info.peerNumberConfig', { n: idx + 1 })}
</Tag>
<Tooltip title={t('copy')}>
<Button
size="small"
icon={<CopyOutlined />}
aria-label={t('copy')}
onClick={() => copyText(cfg, t)}
/>
</Tooltip>
<Tooltip title={t('download')}>
<Button
size="small"
icon={<DownloadOutlined />}
aria-label={t('download')}
onClick={() => downloadText(cfg, `peer-${idx + 1}.conf`)}
/>
</Tooltip>
</div>
<code className="link-panel-text">{cfg}</code>
</div>
)}
{amneziawgLinks[idx] && (
<div className="link-panel">
<div className="link-panel-header">
<Tag color="green">Peer {idx + 1} link</Tag>
<Tooltip title={t('copy')}>
<Button
size="small"
icon={<CopyOutlined />}
aria-label={t('copy')}
onClick={() => copyText(amneziawgLinks[idx], t)}
/>
</Tooltip>
</div>
<code className="link-panel-text">{amneziawgLinks[idx]}</code>
</div>
)}
</Fragment>
))}
</>
)}
{dbInbound.isSS && !inbound.isSSMultiUser && links.length > 0 && (
<>
<Divider>{t('pages.inbounds.copyLink')}</Divider>
@@ -89,6 +89,7 @@ export function isInboundMultiUser(record: { protocol: string; settings: unknown
case 'hysteria':
case 'mtproto':
case 'wireguard':
case 'amneziawg':
return true;
case 'shadowsocks':
return isSSMultiUser({ protocol: 'shadowsocks', settings: readSettings(record.settings) });
@@ -15,6 +15,7 @@ export type ProtocolFlags = {
isMixed?: boolean;
isHTTP?: boolean;
isWireguard?: boolean;
isAmneziawg?: boolean;
isTunnel?: boolean;
};
@@ -199,7 +199,7 @@ export function useInboundColumns({
{record.protocol}
</Tag>,
];
if (record.isWireguard || record.isHysteria) {
if (record.isWireguard || record.isAmneziawg || record.isHysteria) {
tags.push(
<Tag key="n" color="green">
UDP
+57 -1
View File
@@ -6,6 +6,8 @@ import type { CollapseProps } from 'antd';
import { Protocols } from '@/schemas/primitives';
import {
genAllLinks,
genAmneziaWGConfigs,
genAmneziaWGLinks,
genWireguardConfigs,
genWireguardLinks,
isPostQuantumLink,
@@ -50,6 +52,8 @@ export default function QrCodeModal({
const [links, setLinks] = useState<{ remark?: string; link: string }[]>([]);
const [wireguardConfigs, setWireguardConfigs] = useState<string[]>([]);
const [wireguardLinks, setWireguardLinks] = useState<string[]>([]);
const [amneziawgConfigs, setAmneziawgConfigs] = useState<string[]>([]);
const [amneziawgLinks, setAmneziawgLinks] = useState<string[]>([]);
const [subLink, setSubLink] = useState('');
const [subJsonLink, setSubJsonLink] = useState('');
const [activeKey, setActiveKey] = useState<string[]>([]);
@@ -97,6 +101,31 @@ export default function QrCodeModal({
fallbackHostname,
}).split('\r\n'),
);
setAmneziawgConfigs([]);
setAmneziawgLinks([]);
setLinks([]);
} else if (inbound.protocol === Protocols.AMNEZIAWG) {
const peerRemark = client?.email
? `${dbInbound.remark}-${client.email}`
: dbInbound.remark || '';
setAmneziawgConfigs(
genAmneziaWGConfigs({
inbound,
remark: peerRemark,
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
);
setAmneziawgLinks(
genAmneziaWGLinks({
inbound,
remark: peerRemark,
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
);
setWireguardConfigs([]);
setWireguardLinks([]);
setLinks([]);
} else {
setLinks(
@@ -110,6 +139,8 @@ export default function QrCodeModal({
);
setWireguardConfigs([]);
setWireguardLinks([]);
setAmneziawgConfigs([]);
setAmneziawgLinks([]);
}
const subId = client?.subId;
@@ -154,8 +185,33 @@ export default function QrCodeModal({
});
}
});
amneziawgConfigs.forEach((cfg, idx) => {
items.push({
key: `ac${idx}`,
header: `Peer ${idx + 1} config`,
value: cfg,
downloadName: `peer-${idx + 1}.conf`,
});
if (amneziawgLinks[idx]) {
items.push({
key: `al${idx}`,
header: `Peer ${idx + 1} link`,
value: amneziawgLinks[idx],
showQr: false,
});
}
});
return items;
}, [subLink, subJsonLink, links, wireguardConfigs, wireguardLinks, t]);
}, [
subLink,
subJsonLink,
links,
wireguardConfigs,
wireguardLinks,
amneziawgConfigs,
amneziawgLinks,
t,
]);
const collapseItems: CollapseProps['items'] = useMemo(
() =>
@@ -66,6 +66,7 @@ const TRACKED_PROTOCOLS: readonly string[] = [
Protocols.HYSTERIA,
Protocols.WIREGUARD,
Protocols.MTPROTO,
Protocols.AMNEZIAWG,
];
async function fetchSlimInbounds(): Promise<unknown[]> {
@@ -0,0 +1,17 @@
.awglog-events-title {
margin-top: 14px;
font-size: 12px;
font-weight: 600;
opacity: 0.7;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.awglog-event-line {
padding: 2px 0;
word-break: break-word;
}
.xraylog-table .log-row-offline {
opacity: 0.6;
}
@@ -0,0 +1,254 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Checkbox, Empty, Form, Input, Modal, Select, Tag } from 'antd';
import { DownloadOutlined, SyncOutlined } from '@ant-design/icons';
import { HttpUtil, FileManager, IntlUtil, PromiseUtil, SizeFormatter } from '@/utils';
import { activateOnKey } from '@/utils/a11y';
import { useDatepicker } from '@/hooks/useDatepicker';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import type { AmneziaWGLogs } from '@/generated/types';
import './XrayLogModal.css';
import './AmneziaWGLogModal.css';
interface AmneziaWGLogModalProps {
open: boolean;
onClose: () => void;
}
const AUTO_UPDATE_INTERVAL = 5000;
function shortTime(value?: number): string {
if (!value) return '';
const d = new Date(value);
if (isNaN(d.getTime())) return '';
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
export default function AmneziaWGLogModal({ open, onClose }: AmneziaWGLogModalProps) {
const { t } = useTranslation();
const { datepicker } = useDatepicker();
const { isMobile } = useMediaQuery();
const [rows, setRows] = useState('50');
const [filter, setFilter] = useState('');
const [autoUpdate, setAutoUpdate] = useState(false);
const [loading, setLoading] = useState(false);
const [logs, setLogs] = useState<Partial<AmneziaWGLogs>>({});
const peers = useMemo(() => logs.peers ?? [], [logs.peers]);
const events = useMemo(() => logs.events ?? [], [logs.events]);
const runRefresh = useCallback(async () => {
try {
const msg = await HttpUtil.post<AmneziaWGLogs>(`/panel/api/server/amneziawglogs/${rows}`, {
filter,
});
if (msg?.success) setLogs(msg.obj || {});
await PromiseUtil.sleep(300);
} finally {
setLoading(false);
}
}, [rows, filter]);
const refresh = useCallback(() => {
setLoading(true);
void runRefresh();
}, [runRefresh]);
const refreshRef = useRef(refresh);
useEffect(() => {
refreshRef.current = refresh;
});
// The spinner is raised during render so the fetch effect stays side-effect
// free until its response lands.
const refreshKey = open ? `${rows}|${filter}` : null;
const [loadingKey, setLoadingKey] = useState<string | null>(null);
if (refreshKey !== loadingKey) {
setLoadingKey(refreshKey);
if (refreshKey) setLoading(true);
}
useEffect(() => {
if (open) void runRefresh();
}, [open, rows, filter, runRefresh]);
useEffect(() => {
if (!open || !autoUpdate) return;
const id = setInterval(() => refreshRef.current(), AUTO_UPDATE_INTERVAL);
return () => clearInterval(id);
}, [open, autoUpdate]);
function fullDate(value?: number): string {
return value ? IntlUtil.formatDate(value, datepicker) : '';
}
function download() {
const peerLines = peers.map((p) => {
const at = p.handshake ? new Date(p.handshake).toISOString() : 'never';
return `${at} IFACE=${p.interface || ''} INBOUND=${p.tag || ''} EMAIL=${p.email || ''} ENDPOINT=${p.endpoint || '-'} ALLOWEDIPS=${p.allowedIPs || ''} UP=${p.up ?? 0} DOWN=${p.down ?? 0} ONLINE=${p.online ? 'yes' : 'no'}`;
});
FileManager.downloadTextFile([...peerLines, '', ...events].join('\n'), 'amneziawg.log');
}
return (
<Modal
open={open}
footer={null}
width={isMobile ? '100vw' : '80vw'}
style={isMobile ? { top: 0, paddingBottom: 0, maxWidth: '100vw' } : undefined}
className={isMobile ? 'xraylog-modal-mobile' : undefined}
onCancel={onClose}
title={
<>
{t('pages.index.amneziawgLogs')}
<SyncOutlined
spin={loading}
className="reload-icon"
role="button"
tabIndex={0}
aria-label={t('refresh')}
onClick={refresh}
onKeyDown={activateOnKey(refresh)}
/>
</>
}
>
<Form layout="inline" className="log-toolbar">
<Form.Item>
<Select
value={rows}
size="small"
style={{ width: 70 }}
onChange={setRows}
options={[
{ value: '20', label: '20' },
{ value: '50', label: '50' },
{ value: '100', label: '100' },
{ value: '500', label: '500' },
]}
/>
</Form.Item>
<Form.Item label={t('filter')} className="filter-item">
<Input
value={filter}
size="small"
onChange={(e) => setFilter(e.target.value)}
onKeyUp={(e) => {
if (e.key === 'Enter') refresh();
}}
/>
</Form.Item>
<Form.Item>
<Checkbox checked={autoUpdate} onChange={(e) => setAutoUpdate(e.target.checked)}>
{t('pages.index.autoUpdate')}
</Checkbox>
</Form.Item>
<Form.Item className="download-item">
<Button
type="primary"
onClick={download}
icon={<DownloadOutlined />}
aria-label={t('download')}
/>
</Form.Item>
</Form>
<div className={`log-container ${isMobile ? 'log-container-mobile' : ''}`}>
{peers.length === 0 ? (
<div className="log-empty">
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description={t('pages.index.amneziawgNoPeers')}
/>
</div>
) : isMobile ? (
peers.map((peer, idx) => (
<div key={idx} className="log-card">
<div className="log-card-head">
<span className="log-time" title={fullDate(peer.handshake)}>
{shortTime(peer.handshake) || '—'}
</span>
<Tag color={peer.online ? 'green' : 'default'} className="log-event-tag">
{peer.online ? t('online') : t('pages.index.amneziawgIdle')}
</Tag>
</div>
<div className="log-route">
<span className="log-addr">{peer.endpoint || '—'}</span>
<span className="log-arrow"></span>
<span className="log-addr">{peer.allowedIPs}</span>
</div>
<div className="log-meta">
<span className="log-meta-pair">
<span className="log-meta-key">iface</span>
<span className="log-meta-val">{peer.interface}</span>
</span>
<span className="log-meta-pair">
<span className="log-meta-key">inbound</span>
<span className="log-meta-val">{peer.tag}</span>
</span>
{peer.email && (
<span className="log-meta-pair">
<span className="log-meta-key">email</span>
<span className="log-meta-val">{peer.email}</span>
</span>
)}
<span className="log-meta-pair">
<span className="log-meta-key"></span>
<span className="log-meta-val">
{`${SizeFormatter.sizeFormat(peer.up ?? 0)} / ${SizeFormatter.sizeFormat(peer.down ?? 0)}`}
</span>
</span>
</div>
</div>
))
) : (
<table className="xraylog-table">
<thead>
<tr>
<th>{t('pages.index.amneziawgHandshake')}</th>
<th>{t('pages.index.amneziawgInterface')}</th>
<th>{t('pages.index.amneziawgInbound')}</th>
<th>Email</th>
<th>{t('pages.index.amneziawgEndpoint')}</th>
<th>{t('pages.clients.amneziaWgAllowedIPs')}</th>
<th> / </th>
</tr>
</thead>
<tbody>
{peers.map((peer, idx) => (
<tr key={idx} className={peer.online ? undefined : 'log-row-offline'}>
<td>
<b>{fullDate(peer.handshake) || '—'}</b>
</td>
<td>{peer.interface}</td>
<td>{peer.tag}</td>
<td>{peer.email}</td>
<td>{peer.endpoint || '—'}</td>
<td>{peer.allowedIPs}</td>
<td>{`${SizeFormatter.sizeFormat(peer.up ?? 0)} / ${SizeFormatter.sizeFormat(peer.down ?? 0)}`}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="awglog-events-title">{t('pages.index.amneziawgEvents')}</div>
<div className={`log-container ${isMobile ? 'log-container-mobile' : ''}`}>
{events.length === 0 ? (
<div className="log-empty">{t('pages.index.amneziawgNoEvents')}</div>
) : (
events.map((line, idx) => (
<div key={idx} className="awglog-event-line">
{line}
</div>
))
)}
</div>
</Modal>
);
}
+6
View File
@@ -37,6 +37,7 @@ const BackupModal = lazy(() => import('./BackupModal'));
const SystemHistoryModal = lazy(() => import('./SystemHistoryModal'));
const XrayMetricsModal = lazy(() => import('./XrayMetricsModal'));
const XrayLogModal = lazy(() => import('./XrayLogModal'));
const AmneziaWGLogModal = lazy(() => import('./AmneziaWGLogModal'));
const VersionModal = lazy(() => import('./VersionModal'));
import './IndexPage.css';
@@ -67,6 +68,7 @@ export default function IndexPage() {
const [sysHistoryOpen, setSysHistoryOpen] = useState(false);
const [xrayMetricsOpen, setXrayMetricsOpen] = useState(false);
const [xrayLogsOpen, setXrayLogsOpen] = useState(false);
const [amneziawgLogsOpen, setAmneziawgLogsOpen] = useState(false);
const [versionOpen, setVersionOpen] = useState(false);
const [configTextOpen, setConfigTextOpen] = useState(false);
const [configText, setConfigText] = useState('');
@@ -202,6 +204,7 @@ export default function IndexPage() {
onRestartXray={restartXray}
onOpenLogs={() => setLogsOpen(true)}
onOpenXrayLogs={() => setXrayLogsOpen(true)}
onOpenAmneziaWGLogs={() => setAmneziawgLogsOpen(true)}
onOpenConfig={openConfig}
onOpenBackup={() => setBackupOpen(true)}
onOpenSystemHistory={() => setSysHistoryOpen(true)}
@@ -328,6 +331,9 @@ export default function IndexPage() {
<LazyMount when={xrayLogsOpen}>
<XrayLogModal open={xrayLogsOpen} onClose={() => setXrayLogsOpen(false)} />
</LazyMount>
<LazyMount when={amneziawgLogsOpen}>
<AmneziaWGLogModal open={amneziawgLogsOpen} onClose={() => setAmneziawgLogsOpen(false)} />
</LazyMount>
<LazyMount when={versionOpen}>
<VersionModal
open={versionOpen}
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Tag, Tooltip } from 'antd';
import {
ApiOutlined,
ArrowUpOutlined,
AreaChartOutlined,
BarsOutlined,
@@ -28,6 +29,7 @@ interface OverviewActionBarProps {
onRestartXray: () => void;
onOpenLogs: () => void;
onOpenXrayLogs: () => void;
onOpenAmneziaWGLogs: () => void;
onOpenConfig: () => void;
onOpenBackup: () => void;
onOpenSystemHistory: () => void;
@@ -61,6 +63,7 @@ export default function OverviewActionBar({
onRestartXray,
onOpenLogs,
onOpenXrayLogs,
onOpenAmneziaWGLogs,
onOpenConfig,
onOpenBackup,
onOpenSystemHistory,
@@ -101,6 +104,16 @@ export default function OverviewActionBar({
},
]
: []),
...(status.amneziawg.configured
? [
{
key: 'amneziawgLogs',
icon: <ApiOutlined />,
text: t('pages.index.amneziawgLogs'),
onClick: onOpenAmneziaWGLogs,
},
]
: []),
{
key: 'config',
icon: <ControlOutlined />,
@@ -29,6 +29,7 @@ import TelegramTab from './TelegramTab';
import EmailTab from './EmailTab';
import SubscriptionGeneralTab from './SubscriptionGeneralTab';
import SubscriptionFormatsTab from './SubscriptionFormatsTab';
import SubscriptionBalancersTab from './SubscriptionBalancersTab';
import './SettingsPage.css';
interface ApiMsg {
@@ -42,6 +43,7 @@ const tabSlugs = [
'email',
'subscription',
'subscription-formats',
'subscription-balancers',
];
function isIp(h: string): boolean {
@@ -219,6 +221,8 @@ export default function SettingsPage() {
return <SubscriptionGeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'subscription-formats':
return <SubscriptionFormatsTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'subscription-balancers':
return <SubscriptionBalancersTab allSetting={allSetting} updateSetting={updateSetting} />;
default:
return <GeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
}
@@ -0,0 +1,172 @@
import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Form, Input, InputNumber, Modal, Select, Switch, message } from 'antd';
import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { FormField, rhfZodValidate } from '@/components/form/rhf';
import SelectAllClearButtons from '@/components/form/SelectAllClearButtons';
import { useInboundOptions } from '@/api/queries/useInboundOptions';
import { formatInboundLabel } from '@/lib/inbounds/label';
import {
SubBalancerFormSchema,
SubBalancerStrategySchema,
type SubBalancer,
type SubBalancerFormValues,
type SubBalancerStrategy,
} from '@/schemas/subBalancer';
// The JSON subscription only builds proxy outbounds for these protocols;
// mtproto has no proxy-outbound case, so it is excluded from balancer members.
const MULTI_CLIENT_PROTOCOLS = new Set([
'shadowsocks',
'vless',
'vmess',
'trojan',
'hysteria',
'wireguard',
]);
const STRATEGY_LABEL_KEYS: Record<SubBalancerStrategy, string> = {
leastLoad: 'pages.settings.subBalancers.strategyLeastLoad',
leastPing: 'pages.settings.subBalancers.strategyLeastPing',
random: 'pages.settings.subBalancers.strategyRandom',
roundRobin: 'pages.settings.subBalancers.strategyRoundRobin',
};
function initialState(balancer: SubBalancer | null): SubBalancerFormValues {
return {
remark: balancer?.remark ?? '',
strategy: balancer?.strategy ?? 'random',
inboundIds: [...(balancer?.inboundIds ?? [])],
sortOrder: balancer?.sortOrder ?? 1,
enabled: balancer?.enabled ?? true,
};
}
interface SubBalancerFormModalProps {
open: boolean;
balancer: SubBalancer | null;
onClose: () => void;
onConfirm: (values: SubBalancerFormValues) => void;
}
export default function SubBalancerFormModal({
open,
balancer,
onClose,
onConfirm,
}: SubBalancerFormModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const methods = useForm<SubBalancerFormValues>({ defaultValues: initialState(balancer) });
const isEdit = balancer != null;
useEffect(() => {
if (open) methods.reset(initialState(balancer));
}, [open, balancer, methods]);
const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' });
const { data: inboundOptionsRaw } = useInboundOptions();
const inboundOptions = useMemo(
() =>
(inboundOptionsRaw ?? [])
.filter((ib) => MULTI_CLIENT_PROTOCOLS.has(ib.protocol || ''))
.filter((ib) => ib.enable || (inboundIds || []).includes(ib.id))
.map((ib) => ({
label: formatInboundLabel(ib.tag, ib.remark),
value: ib.id,
title: formatInboundLabel(ib.tag, ib.remark),
})),
[inboundOptionsRaw, inboundIds],
);
function onFinish(values: SubBalancerFormValues) {
const parsed = SubBalancerFormSchema.safeParse(values);
if (!parsed.success) {
messageApi.error(
t(parsed.error.issues[0]?.message ?? 'pages.settings.subBalancers.errRemarkRequired'),
);
return;
}
onConfirm(parsed.data);
}
const strategies = SubBalancerStrategySchema.options.map((value) => ({
value,
label: t(STRATEGY_LABEL_KEYS[value]),
}));
return (
<Modal
open={open}
title={
isEdit
? `${t('edit')} ${t('pages.settings.subBalancers.title')}`
: `+ ${t('pages.settings.subBalancers.add')}`
}
okText={isEdit ? t('pages.clients.submitEdit') : t('create')}
cancelText={t('close')}
mask={{ closable: false }}
width="640px"
onOk={methods.handleSubmit(onFinish)}
onCancel={onClose}
>
{messageContextHolder}
<FormProvider {...methods}>
<Form layout="vertical">
<FormField
label={t('pages.settings.subBalancers.remark')}
name="remark"
required
rules={{ validate: rhfZodValidate(SubBalancerFormSchema.shape.remark) }}
>
<Input placeholder={t('pages.settings.subBalancers.remarkPlaceholder')} />
</FormField>
<FormField label={t('pages.settings.subBalancers.strategy')} name="strategy" required>
<Select options={strategies} />
</FormField>
<FormField
label={t('pages.settings.subBalancers.sortOrder')}
name="sortOrder"
required
tooltip={t('pages.settings.subBalancers.sortOrderHelp')}
rules={{ validate: rhfZodValidate(SubBalancerFormSchema.shape.sortOrder) }}
>
<InputNumber min={1} precision={0} style={{ width: '100%' }} />
</FormField>
<FormField
label={t('pages.settings.subBalancers.inbounds')}
name="inboundIds"
required
rules={{ validate: rhfZodValidate(SubBalancerFormSchema.shape.inboundIds) }}
>
<Select
mode="multiple"
options={inboundOptions}
maxTagCount="responsive"
listHeight={220}
showSearch={{ optionFilterProp: 'label' }}
/>
</FormField>
<SelectAllClearButtons
options={inboundOptions}
value={inboundIds || []}
onChange={(v) => methods.setValue('inboundIds', v, { shouldDirty: true })}
/>
<FormField
label={t('pages.settings.subBalancers.enabled')}
name="enabled"
valueProp="checked"
>
<Switch />
</FormField>
</Form>
</FormProvider>
</Modal>
);
}
@@ -0,0 +1,359 @@
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Alert,
Button,
Input,
InputNumber,
Popconfirm,
Select,
Space,
Switch,
Table,
Tabs,
Tag,
Tooltip,
} from 'antd';
import {
DeleteOutlined,
DeploymentUnitOutlined,
EditOutlined,
PlusOutlined,
RadarChartOutlined,
} from '@ant-design/icons';
import { useSubBalancersQuery } from '@/api/queries/useSubBalancersQuery';
import { useSubBalancerMutations } from '@/api/queries/useSubBalancerMutations';
import { useInboundOptions } from '@/api/queries/useInboundOptions';
import { formatInboundLabel } from '@/lib/inbounds/label';
import type { AllSetting } from '@/models/setting';
import { onNumber } from '@/utils/onNumber';
import { SettingListItem } from '@/components/ui';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import type { SubBalancer, SubBalancerFormValues } from '@/schemas/subBalancer';
import { PingConfigSchema, type PingConfigObject } from '@/schemas/observatory';
import { DEFAULT_BURST_OBSERVATORY } from '@/pages/xray/balancers/balancer-helpers';
import SubBalancerFormModal from './SubBalancerFormModal';
import { catTabLabel } from './catTabLabel';
import './SubscriptionFormatsTab.css';
const STRATEGY_COLORS: Record<string, string> = {
leastLoad: 'geekblue',
leastPing: 'green',
random: 'orange',
roundRobin: 'purple',
};
// Single source for the burst-observatory ping defaults: the Zod schema and
// DEFAULT_BURST_OBSERVATORY are kept in sync, so the tab just parses through it.
const DEFAULT_PING_CONFIG = PingConfigSchema.parse({ ...DEFAULT_BURST_OBSERVATORY.pingConfig });
function parsePingConfig(raw: string): PingConfigObject {
try {
return PingConfigSchema.parse(raw ? JSON.parse(raw) : {});
} catch {
return DEFAULT_PING_CONFIG;
}
}
interface SubscriptionBalancersTabProps {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
}
export default function SubscriptionBalancersTab({
allSetting,
updateSetting,
}: SubscriptionBalancersTabProps) {
const { t } = useTranslation();
const { isMobile } = useMediaQuery();
const { balancers, loading, fetched, fetchError, refetch } = useSubBalancersQuery();
const { create, update, remove } = useSubBalancerMutations();
const { data: inboundOptionsRaw } = useInboundOptions();
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<SubBalancer | null>(null);
const inboundLabels = useMemo(() => {
const map = new Map<number, string>();
for (const ib of inboundOptionsRaw ?? []) {
map.set(ib.id, formatInboundLabel(ib.tag, ib.remark));
}
return map;
}, [inboundOptionsRaw]);
async function onConfirm(values: SubBalancerFormValues) {
const msg = editing ? await update(editing.id, values) : await create(values);
if (msg?.success) setModalOpen(false);
}
async function toggleEnabled(balancer: SubBalancer) {
await update(balancer.id, {
remark: balancer.remark,
strategy: balancer.strategy,
inboundIds: balancer.inboundIds,
sortOrder: balancer.sortOrder,
enabled: !balancer.enabled,
});
}
const observatoryEnabled = allSetting.subJsonObservatory !== '';
const observatoryObj = useMemo(
() => parsePingConfig(allSetting.subJsonObservatory),
[allSetting.subJsonObservatory],
);
function setObservatoryEnabled(v: boolean) {
updateSetting({ subJsonObservatory: v ? JSON.stringify(DEFAULT_PING_CONFIG) : '' });
}
function setObservatoryField<K extends keyof PingConfigObject>(
key: K,
value: PingConfigObject[K],
) {
const next = { ...observatoryObj, [key]: value };
updateSetting({ subJsonObservatory: JSON.stringify(next) });
}
const columns = [
{
title: t('pages.settings.subBalancers.sortOrder'),
dataIndex: 'sortOrder',
key: 'sortOrder',
width: 80,
align: 'center' as const,
},
{
title: t('pages.settings.subBalancers.remark'),
dataIndex: 'remark',
key: 'remark',
},
{
title: t('pages.settings.subBalancers.strategy'),
dataIndex: 'strategy',
key: 'strategy',
width: 120,
render: (strategy: string) => (
<Tag color={STRATEGY_COLORS[strategy] ?? 'default'}>{strategy}</Tag>
),
},
{
title: t('pages.settings.subBalancers.inbounds'),
key: 'inbounds',
render: (_: unknown, r: SubBalancer) => {
const labels = r.inboundIds.map((id) => inboundLabels.get(id) ?? `#${id}`);
return (
<Tooltip title={labels.join(', ')}>
<span>{t('pages.settings.subBalancers.inboundsCount', { count: labels.length })}</span>
</Tooltip>
);
},
},
{
title: t('pages.settings.subBalancers.enabled'),
dataIndex: 'enabled',
key: 'enabled',
width: 80,
align: 'center' as const,
render: (_: unknown, r: SubBalancer) => (
<Switch size="small" checked={r.enabled} onChange={() => toggleEnabled(r)} />
),
},
{
title: '',
key: 'actions',
width: 96,
render: (_: unknown, r: SubBalancer) => (
<Space>
<Button
aria-label={t('edit')}
size="small"
icon={<EditOutlined />}
title={t('edit')}
onClick={() => {
setEditing(r);
setModalOpen(true);
}}
/>
<Popconfirm
title={t('pages.settings.subBalancers.deleteConfirm')}
okText={t('delete')}
cancelText={t('cancel')}
onConfirm={() => remove(r.id)}
>
<Button aria-label={t('delete')} size="small" danger icon={<DeleteOutlined />} />
</Popconfirm>
</Space>
),
},
];
const balancersTab = (
<div>
<Alert
type="info"
showIcon
style={{ marginBottom: 16 }}
title={t('pages.settings.subBalancers.desc')}
/>
{fetchError && (
<Alert
type="error"
showIcon
style={{ marginBottom: 16 }}
title={fetchError}
action={
<Button size="small" onClick={() => refetch()}>
{t('refresh')}
</Button>
}
/>
)}
<div style={{ marginBottom: 12 }}>
<Button
type="primary"
icon={<PlusOutlined />}
onClick={() => {
setEditing(null);
setModalOpen(true);
}}
>
{t('pages.settings.subBalancers.add')}
</Button>
</div>
<Table
size="small"
dataSource={balancers}
rowKey={(r) => r.id}
pagination={false}
loading={loading && !fetched}
scroll={{ x: true }}
locale={{ emptyText: t('pages.settings.subBalancers.empty') }}
columns={columns}
/>
</div>
);
const observatoryTab = (
<>
<Alert
type="info"
showIcon
style={{ marginBottom: 16 }}
title={t('pages.settings.subBalancers.observatory.note')}
/>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.title')}
description={t('pages.settings.subBalancers.observatory.desc')}
>
<Switch checked={observatoryEnabled} onChange={setObservatoryEnabled} />
</SettingListItem>
{observatoryEnabled && (
<div className="format-settings">
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.destination')}
description={t('pages.settings.subBalancers.observatory.destinationDesc')}
>
<Input
value={observatoryObj.destination}
placeholder="https://www.google.com/generate_204"
onChange={(e) => setObservatoryField('destination', e.target.value)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.connectivity')}
description={t('pages.settings.subBalancers.observatory.connectivityDesc')}
>
<Input
value={observatoryObj.connectivity}
placeholder="http://connectivitycheck.platform.hicloud.com/generate_204"
onChange={(e) => setObservatoryField('connectivity', e.target.value)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.interval')}
description={t('pages.settings.subBalancers.observatory.intervalDesc')}
>
<Input
value={observatoryObj.interval}
placeholder="1m"
onChange={(e) => setObservatoryField('interval', e.target.value)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.timeout')}
description={t('pages.settings.subBalancers.observatory.timeoutDesc')}
>
<Input
value={observatoryObj.timeout}
placeholder="5s"
onChange={(e) => setObservatoryField('timeout', e.target.value)}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.sampling')}
description={t('pages.settings.subBalancers.observatory.samplingDesc')}
>
<InputNumber
value={observatoryObj.sampling}
min={1}
style={{ width: '100%' }}
onChange={onNumber((v) => setObservatoryField('sampling', v))}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.subBalancers.observatory.httpMethod')}
description={t('pages.settings.subBalancers.observatory.httpMethodDesc')}
>
<Select
value={observatoryObj.httpMethod}
style={{ width: '100%' }}
onChange={(v) => setObservatoryField('httpMethod', v)}
options={['HEAD', 'GET'].map((m) => ({ value: m, label: m }))}
/>
</SettingListItem>
</div>
)}
</>
);
return (
<>
<Tabs
defaultActiveKey="balancers"
items={[
{
key: 'balancers',
label: catTabLabel(
<DeploymentUnitOutlined />,
t('pages.settings.subBalancers.tabBalancers'),
isMobile,
),
children: balancersTab,
},
{
key: 'observatory',
label: catTabLabel(
<RadarChartOutlined />,
t('pages.settings.subBalancers.tabObservatory'),
isMobile,
),
children: observatoryTab,
},
]}
/>
<SubBalancerFormModal
open={modalOpen}
balancer={editing}
onClose={() => setModalOpen(false)}
onConfirm={onConfirm}
/>
</>
);
}
+15 -1
View File
@@ -33,7 +33,11 @@ import {
} from '@ant-design/icons';
import { ClipboardManager, IntlUtil, LanguageManager } from '@/utils';
import { isPostQuantumLink, wireguardConfigFromLink } from '@/lib/xray/inbound-link';
import {
amneziawgConfigFromLink,
isPostQuantumLink,
wireguardConfigFromLink,
} from '@/lib/xray/inbound-link';
import { LinkTags, parseLinkParts } from '@/lib/xray/link-label';
import ConfigBlock from '@/components/clients/ConfigBlock';
import { setMessageInstance } from '@/utils/messageBus';
@@ -533,6 +537,7 @@ export default function SubPage() {
const canQr = !isPostQuantumLink(link);
const isWireguardLink =
link.startsWith('wireguard://') || link.startsWith('wg://');
const isAmneziawgLink = link.startsWith('vpn://');
return (
<Fragment key={link}>
<div className="sub-link-row">
@@ -590,6 +595,15 @@ export default function SubPage() {
tagColor="cyan"
/>
)}
{isAmneziawgLink && (
<ConfigBlock
label={t('pages.clients.amneziaWgConfig')}
text={amneziawgConfigFromLink(link)}
fileName={`${rowTitle || 'peer'}.conf`}
qrRemark={rowTitle}
tagColor="purple"
/>
)}
</Fragment>
);
})}
+10 -1
View File
@@ -36,7 +36,7 @@ import {
detectBalancerCycles,
} from './balancers/balancer-loopback';
import { DnsTab } from './dns';
import { WarpModal, NordModal } from './overrides';
import { WarpModal, NordModal, PiaModal } from './overrides';
import './XrayPage.css';
const SECTION_SLUGS = ['basic', 'routing', 'outbound', 'balancer', 'dns', 'advanced'];
@@ -82,6 +82,7 @@ export default function XrayPage() {
const [warpOpen, setWarpOpen] = useState(false);
const [nordOpen, setNordOpen] = useState(false);
const [piaOpen, setPiaOpen] = useState(false);
const [advSettings, setAdvSettings] = useState<AdvKey>('xraySetting');
const location = useLocation();
const navigate = useNavigate();
@@ -264,6 +265,7 @@ export default function XrayPage() {
onTestAll={testAllOutbounds}
onShowWarp={() => setWarpOpen(true)}
onShowNord={() => setNordOpen(true)}
onShowPia={() => setPiaOpen(true)}
onRefreshXrayData={fetchAll}
/>
);
@@ -394,6 +396,13 @@ export default function XrayPage() {
onRemoveOutbound={onRemoveOutboundByIndex}
onRemoveRoutingRules={onRemoveRoutingRules}
/>
<PiaModal
open={piaOpen}
templateSettings={templateSettings}
onClose={() => setPiaOpen(false)}
onAddOutbound={onAddOutbound}
onResetOutbound={onResetOutbound}
/>
</Layout>
</ConfigProvider>
);
@@ -13,7 +13,7 @@ export const DEFAULT_BURST_OBSERVATORY = Object.freeze({
pingConfig: {
destination: 'https://www.google.com/generate_204',
interval: '1m',
connectivity: 'http://connectivitycheck.platform.hicloud.com/generate_204',
connectivity: '',
timeout: '5s',
sampling: 2,
httpMethod: 'HEAD',
@@ -95,6 +95,7 @@ interface OutboundsTabProps {
onTestAll: (mode: string) => void;
onShowWarp: () => void;
onShowNord: () => void;
onShowPia: () => void;
onRefreshXrayData?: () => void;
}
@@ -115,6 +116,7 @@ export default function OutboundsTab({
onTestAll,
onShowWarp,
onShowNord,
onShowPia,
onRefreshXrayData,
}: OutboundsTabProps) {
const { t } = useTranslation();
@@ -550,6 +552,12 @@ export default function OutboundsTab({
items: [
{ key: 'warp', icon: <CloudOutlined />, label: 'WARP', onClick: onShowWarp },
{ key: 'nord', icon: <ApiOutlined />, label: 'NordVPN', onClick: onShowNord },
{
key: 'pia',
icon: <ApiOutlined />,
label: t('pages.xray.pia.menu'),
onClick: onShowPia,
},
{ type: 'divider' },
{
key: 'import',
@@ -0,0 +1,53 @@
.pia-data-table {
margin: 5px 0;
width: 100%;
border-collapse: collapse;
}
.pia-data-table td {
padding: 4px 8px;
word-break: break-all;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
}
.pia-data-table td:first-child {
font-family: inherit;
font-weight: 500;
white-space: nowrap;
width: 130px;
}
.pia-data-table .row-odd {
background: var(--ant-color-fill-tertiary);
}
.pia-already-added {
margin-top: 8px;
color: var(--ant-color-text-secondary);
font-size: 12px;
}
.pia-added-table {
margin: 0;
width: 100%;
border-collapse: collapse;
}
.pia-added-table td {
padding: 6px 0;
vertical-align: middle;
}
.pia-added-table td:first-child {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
word-break: break-all;
padding-right: 8px;
}
.pia-added-table td:last-child {
width: 1%;
white-space: nowrap;
text-align: right;
}
@@ -0,0 +1,468 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Divider, Form, Input, message, Modal, Select } from 'antd';
import { LoginOutlined } from '@ant-design/icons';
import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { HttpUtil } from '@/utils';
import { FormField } from '@/components/form/rhf';
import { countryFlag, countryName } from '../outbounds/outbounds-tab-helpers';
import './PiaModal.css';
interface PiaOutboundRow {
tag?: string;
piaHostname?: string;
}
interface PiaModalProps {
open: boolean;
templateSettings: { outbounds?: PiaOutboundRow[] } | null;
onClose: () => void;
onAddOutbound: (outbound: Record<string, unknown>) => void;
onResetOutbound: (payload: {
index: number;
outbound: Record<string, unknown>;
oldTag?: string;
newTag: string;
}) => void;
}
interface PiaAccount {
username?: string;
accountHint?: string;
}
interface PiaCountry {
code: string;
}
interface PiaRegion {
id: string;
name: string;
}
interface PiaServer {
hostname: string;
ip: string;
regionId: string;
regionName: string;
}
interface PiaKey {
tag: string;
hostname: string;
secretKey: string;
address: string;
publicKey: string;
endpoint: string;
}
interface PiaFormValues {
username: string;
password: string;
countryCode: string | null;
regionId: string | null;
hostname: string | null;
}
const EMPTY: PiaFormValues = {
username: '',
password: '',
countryCode: null,
regionId: null,
hostname: null,
};
function piaHostnameOf(outbound: PiaOutboundRow): string {
if (typeof outbound.piaHostname === 'string' && outbound.piaHostname.trim()) {
return outbound.piaHostname.trim();
}
return '';
}
function piaTagPart(s: string, stripDomain: boolean): string {
s = s.trim().toLowerCase();
if (stripDomain) {
const i = s.indexOf('.');
if (i > 0) s = s.slice(0, i);
}
return s.replaceAll('_', '-');
}
function piaOutboundTag(regionId: string, hostname: string): string {
const region = piaTagPart(regionId, false);
const server = piaTagPart(hostname, true);
if (!region) return `pia-${server}`;
return `pia-${region}-${server}`;
}
function buildPiaOutbound(key: PiaKey): Record<string, unknown> {
return {
tag: key.tag || `pia-${key.hostname}`,
piaHostname: key.hostname,
protocol: 'wireguard',
settings: {
secretKey: key.secretKey,
address: [key.address],
mtu: 1420,
noKernelTun: true,
peers: [
{
publicKey: key.publicKey,
endpoint: key.endpoint,
allowedIPs: ['0.0.0.0/0'],
keepAlive: 25,
},
],
},
};
}
export default function PiaModal({
open,
templateSettings,
onClose,
onAddOutbound,
onResetOutbound,
}: PiaModalProps) {
const { t, i18n } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const [loading, setLoading] = useState(false);
const [piaData, setPiaData] = useState<PiaAccount | null>(null);
const [countries, setCountries] = useState<PiaCountry[]>([]);
const [regions, setRegions] = useState<PiaRegion[]>([]);
const [servers, setServers] = useState<PiaServer[]>([]);
const methods = useForm<PiaFormValues>({ defaultValues: EMPTY });
const regionId = useWatch({ control: methods.control, name: 'regionId' });
const hostname = useWatch({ control: methods.control, name: 'hostname' });
const locale = i18n.resolvedLanguage || i18n.language;
const piaRows = useMemo(() => {
const list = templateSettings?.outbounds;
if (!list) return [];
return list.flatMap((outbound, index) => {
if (!outbound?.tag?.startsWith?.('pia-')) return [];
return [{ index, tag: outbound.tag, hostname: piaHostnameOf(outbound) }];
});
}, [templateSettings?.outbounds]);
const addedHostnames = useMemo(
() => new Set(piaRows.map((row) => row.hostname).filter(Boolean)),
[piaRows],
);
const addedTags = useMemo(
() => new Set(piaRows.map((row) => row.tag).filter(Boolean)),
[piaRows],
);
const filteredServers = useMemo(() => {
if (!regionId) return servers;
return servers.filter((s) => s.regionId === regionId);
}, [regionId, servers]);
const selectedServer = filteredServers.find((s) => s.hostname === hostname);
const selectedTag = selectedServer
? piaOutboundTag(selectedServer.regionId, selectedServer.hostname)
: '';
const selectedAlreadyAdded = Boolean(
(hostname && addedHostnames.has(hostname)) || (selectedTag && addedTags.has(selectedTag)),
);
useEffect(() => {
methods.setValue('hostname', filteredServers.length > 0 ? filteredServers[0].hostname : null);
}, [filteredServers, methods]);
const fetchCountries = useCallback(async () => {
const msg = await HttpUtil.post<PiaCountry[]>('/panel/api/xray/pia/countries');
if (msg?.success && Array.isArray(msg.obj)) setCountries(msg.obj);
}, []);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const msg = await HttpUtil.post<PiaAccount | null>('/panel/api/xray/pia/data');
if (msg?.success) {
const next = msg.obj ?? null;
setPiaData(next);
if (next) await fetchCountries();
}
} finally {
setLoading(false);
}
}, [fetchCountries]);
useEffect(() => {
if (!open) return;
let cancelled = false;
void (async () => {
await fetchData();
if (cancelled) return;
})();
return () => {
cancelled = true;
};
}, [open, fetchData]);
async function login() {
setLoading(true);
try {
const msg = await HttpUtil.post<PiaAccount>('/panel/api/xray/pia/reg', {
username: methods.getValues('username'),
password: methods.getValues('password'),
});
if (msg?.success && msg.obj) {
setPiaData(msg.obj);
methods.setValue('password', '');
await fetchCountries();
}
} finally {
setLoading(false);
}
}
async function logout() {
setLoading(true);
try {
const msg = await HttpUtil.post('/panel/api/xray/pia/del');
if (msg?.success) {
setPiaData(null);
methods.reset(EMPTY);
setCountries([]);
setRegions([]);
setServers([]);
}
} finally {
setLoading(false);
}
}
async function fetchServers(newCountryCode: string) {
setLoading(true);
setServers([]);
setRegions([]);
methods.setValue('hostname', null);
methods.setValue('regionId', null);
try {
const msg = await HttpUtil.post<{ regions?: PiaRegion[]; servers?: PiaServer[] }>(
'/panel/api/xray/pia/servers',
{ countryCode: newCountryCode },
);
if (!msg?.success || !msg.obj) return;
const nextRegions = msg.obj.regions || [];
const nextServers = msg.obj.servers || [];
setRegions(nextRegions);
setServers(nextServers);
if (nextServers.length === 0) messageApi.warning(t('pages.xray.pia.noServers'));
} finally {
setLoading(false);
}
}
async function provisionOutbound(
selectedHostname: string,
): Promise<Record<string, unknown> | null> {
if (!selectedHostname) return null;
const msg = await HttpUtil.post<PiaKey>('/panel/api/xray/pia/addKey', {
hostname: selectedHostname,
});
if (!msg?.success) return null;
if (!msg.obj?.secretKey || !msg.obj.publicKey || !msg.obj.endpoint || !msg.obj.address) {
messageApi.error(t('pages.xray.pia.provisionFailed'));
return null;
}
return buildPiaOutbound(msg.obj);
}
async function addOutbound() {
const selected = methods.getValues('hostname');
if (!selected || selectedAlreadyAdded) return;
setLoading(true);
try {
const ob = await provisionOutbound(selected);
if (!ob) return;
const tag = typeof ob.tag === 'string' ? ob.tag : '';
if (tag && templateSettings?.outbounds?.some((outbound) => outbound?.tag === tag)) return;
onAddOutbound(ob);
messageApi.success(t('pages.xray.pia.outboundAdded'));
} finally {
setLoading(false);
}
}
async function resetOutbound(index: number, selectedHostname: string) {
if (!selectedHostname) return;
setLoading(true);
try {
const ob = await provisionOutbound(selectedHostname);
if (!ob) return;
const oldTag = templateSettings?.outbounds?.[index]?.tag;
onResetOutbound({
index,
outbound: ob,
oldTag,
newTag: ob.tag as string,
});
messageApi.success(t('pages.xray.pia.outboundUpdated'));
} finally {
setLoading(false);
}
}
return (
<>
{messageContextHolder}
<Modal open={open} title="Private Internet Access WireGuard" footer={null} onCancel={onClose}>
<FormProvider {...methods}>
{piaData == null ? (
<Form
colon={false}
labelCol={{ md: { span: 6 } }}
wrapperCol={{ md: { span: 18 } }}
className="mt-20"
>
<FormField name="username" label={t('pages.xray.pia.username')}>
<Input placeholder={t('pages.xray.pia.username')} autoComplete="username" />
</FormField>
<FormField name="password" label={t('pages.xray.pia.password')}>
<Input.Password
placeholder={t('pages.xray.pia.password')}
autoComplete="current-password"
/>
</FormField>
<Button
type="primary"
className="mt-10"
loading={loading}
icon={<LoginOutlined />}
onClick={() => void login()}
>
{t('login')}
</Button>
</Form>
) : (
<>
<table className="pia-data-table">
<tbody>
<tr className="row-odd">
<td>{t('pages.xray.pia.account')}</td>
<td>{piaData.accountHint || piaData.username}</td>
</tr>
</tbody>
</table>
<Button
loading={loading}
type="primary"
danger
className="mt-8"
onClick={() => void logout()}
>
{t('logout')}
</Button>
<Divider className="zero-margin">{t('pages.xray.warp.settings')}</Divider>
<Form
colon={false}
labelCol={{ md: { span: 6 } }}
wrapperCol={{ md: { span: 18 } }}
className="mt-10"
>
<FormField
name="countryCode"
label={t('pages.xray.outbound.country')}
transform={{ input: (v) => v ?? undefined }}
onAfterChange={(v) => void fetchServers(v as string)}
>
<Select
data-testid="pia-country-select"
showSearch={{ optionFilterProp: 'label' }}
options={countries.map((c) => {
const name = countryName(c.code, locale) || c.code;
const flag = countryFlag(c.code);
return {
value: c.code,
label: `${flag ? `${flag} ` : ''}${name} (${c.code})`,
};
})}
/>
</FormField>
{regions.length > 0 && (
<FormField name="regionId" label={t('pages.xray.pia.region')}>
<Select
data-testid="pia-region-select"
showSearch={{ optionFilterProp: 'label' }}
options={[
{ value: null, label: t('pages.xray.pia.allRegions') },
...regions.map((r) => ({ value: r.id, label: r.name })),
]}
/>
</FormField>
)}
{filteredServers.length > 0 && (
<FormField name="hostname" label={t('pages.xray.outbound.server')}>
<Select
data-testid="pia-server-select"
showSearch={{ optionFilterProp: 'label' }}
options={filteredServers.map((s) => ({
value: s.hostname,
label: `${s.regionName} ${s.hostname} ${s.ip}`,
}))}
/>
</FormField>
)}
</Form>
<Button
type="primary"
className="mt-10"
disabled={!hostname || selectedAlreadyAdded}
loading={loading}
onClick={() => void addOutbound()}
>
{t('pages.xray.warp.addOutbound')}
</Button>
{selectedAlreadyAdded && (
<div className="pia-already-added">
{t('pages.xray.pia.alreadyAdded', { reset: t('reset') })}
</div>
)}
{piaRows.length > 0 && (
<>
<Divider className="my-10">{t('pages.xray.pia.addedServers')}</Divider>
<table className="pia-added-table" data-testid="pia-added-table">
<tbody>
{piaRows.map((row) => (
<tr key={`${row.index}-${row.tag}`}>
<td>{row.tag}</td>
<td>
<Button
type="primary"
danger
size="small"
loading={loading}
disabled={!row.tag}
data-testid={`pia-reset-${row.index}`}
onClick={() =>
void resetOutbound(row.index, row.hostname || row.tag || '')
}
>
{t('reset')}
</Button>
</td>
</tr>
))}
</tbody>
</table>
</>
)}
</>
)}
</FormProvider>
</Modal>
</>
);
}
@@ -1,2 +1,3 @@
export { default as WarpModal } from './WarpModal';
export { default as NordModal } from './NordModal';
export { default as PiaModal } from './PiaModal';
@@ -6,6 +6,7 @@ import { FormProvider, useForm, useWatch } from 'react-hook-form';
import { InputAddon } from '@/components/ui';
import { GeoTokenInput } from '@/components/geodata';
import { FormField } from '@/components/form/rhf';
import { useClientOptions } from '@/api/queries/useClientOptions';
import { useInboundOptions } from '@/api/queries/useInboundOptions';
import { RuleFormSchema, type RuleFormValues } from '@/schemas/xray';
import { buildRemarkByTag, formatInboundTag, isApiRule } from './helpers';
@@ -82,6 +83,21 @@ export default function RuleFormModal({
const { data: inboundOptions } = useInboundOptions();
const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]);
const {
data: clientEmails = [],
isFetching: clientsLoading,
isError: clientsError,
} = useClientOptions(open);
const user = useWatch({ control: methods.control, name: 'user' }) ?? '';
const selectedUsers = useMemo(() => csv(user), [user]);
const userOptions = useMemo(
() =>
[...new Set([...clientEmails, ...selectedUsers])].map((email) => ({
value: email,
label: email,
})),
[clientEmails, selectedUsers],
);
useEffect(() => {
if (!open) return;
@@ -287,8 +303,27 @@ export default function RuleFormModal({
{t('pages.xray.ruleForm.user')} <QuestionCircleOutlined aria-hidden="true" />
</Tooltip>
}
transform={{
input: (value) => csv(typeof value === 'string' ? value : ''),
output: (value) => (Array.isArray(value) ? value.join(',') : ''),
}}
>
<Input placeholder="email address" />
<Select
mode="tags"
tokenSeparators={[',']}
allowClear
loading={clientsLoading}
placeholder={t('pages.xray.ruleForm.userPlaceholder')}
showSearch={{ optionFilterProp: 'label' }}
notFoundContent={
clientsLoading
? t('loading')
: clientsError
? t('pages.xray.ruleForm.userLoadError')
: t('pages.xray.ruleForm.userEmpty')
}
options={userOptions}
/>
</FormField>
<FormField
+1 -1
View File
@@ -7,7 +7,7 @@ import { NetworkSettingsSchema, StreamExtrasSchema } from '@/schemas/protocols/s
// Top-level inbound shape on the wire. Composes:
// - Per-protocol settings via the InboundSettingsSchema discriminated
// union (10 protocols, tagged-wrapper {protocol, settings}).
// union (11 protocols, tagged-wrapper {protocol, settings}).
// - StreamSettings as an intersection of the network DU (6 branches),
// security DU (3 branches), and the orthogonal extras (finalmask,
// sockopt, externalProxy). Zod 4 supports DU intersection — each
+50
View File
@@ -52,6 +52,7 @@ export const ClientRecordSchema = z
allowedIPs: z.string().optional(),
preSharedKey: z.string().optional(),
keepAlive: z.number().optional(),
forwardedPorts: z.string().optional(),
secret: z.string().optional(),
adTag: z.string().optional(),
createdAt: z.number().optional(),
@@ -59,6 +60,47 @@ export const ClientRecordSchema = z
})
.loose();
// AmneziaWG's server block, used by the clients page to render a
// downloadable per-client .conf without a second round trip. Unlike
// WireGuard's flattened wgPublicKey/wgMtu/wgDns below, this stays a nested
// object — AmneziaWG has many more fields (the obfuscation parameter set) and
// buildAmneziaWGClientConfig (pages/clients/amneziawgConfig.ts) already
// expects this exact nested shape. Mirrors the backend's
// InboundOption.AwgServer (internal/web/service/inbound.go).
export const AwgServerOptionSchema = z
.object({
publicKey: z.string().optional(),
mtu: z.number().optional(),
primaryDns: z.string().optional(),
secondaryDns: z.string().optional(),
jc: z.number().optional(),
jmin: z.number().optional(),
jmax: z.number().optional(),
s1: z.number().optional(),
s2: z.number().optional(),
s3: z.number().optional(),
s4: z.number().optional(),
h1: z.string().optional(),
h2: z.string().optional(),
h3: z.string().optional(),
h4: z.string().optional(),
i1: z.string().optional(),
i2: z.string().optional(),
i3: z.string().optional(),
i4: z.string().optional(),
i5: z.string().optional(),
headerProtectionKey: z.string().optional(),
contentPaddingAddition: z.string().optional(),
rekeyAfterTime: z.string().optional(),
rekeyTimeout: z.string().optional(),
rejectAfterTime: z.string().optional(),
keepaliveTimeout: z.string().optional(),
maxHandshakeAttempts: z.string().optional(),
randomTrailers: z.boolean().optional(),
disableCookies: z.boolean().optional(),
})
.loose();
export const InboundOptionSchema = z
.object({
id: z.number(),
@@ -71,6 +113,7 @@ export const InboundOptionSchema = z
wgPublicKey: z.string().optional(),
wgMtu: z.number().optional(),
wgDns: z.string().optional(),
awgServer: AwgServerOptionSchema.nullable().optional(),
mtprotoDomain: z.string().optional(),
// Hosting node id; absent/null for this panel's own inbounds (#4997).
nodeId: z.number().nullable().optional(),
@@ -137,10 +180,17 @@ export const ExternalLinkListSchema = z
.nullable()
.transform((v) => v ?? []);
// tunnelAllowedIPs carries the real, per-inbound AllowedIPs value (keyed by
// inbound id) for every WireGuard/AmneziaWG inbound this client is attached
// to. ClientRecord's own allowedIPs is a single string and cannot represent
// two different addresses when one identity holds both a WireGuard and an
// AmneziaWG attachment at once -- this is what lets the edit form show each
// protocol's real, distinct address instead of one ambiguous shared field.
export const ClientHydrateSchema = z.object({
client: ClientRecordSchema,
inboundIds: nullableNumberArray,
externalLinks: ExternalLinkListSchema.optional(),
tunnelAllowedIPs: z.record(z.number().int(), z.string()).optional(),
});
export const BulkAdjustResultSchema = z.object({
+1 -1
View File
@@ -16,7 +16,7 @@ export type ObservatoryHttpMethod = z.infer<typeof ObservatoryHttpMethodSchema>;
export const PingConfigSchema = z
.object({
destination: z.string().default('https://www.google.com/generate_204'),
connectivity: z.string().default('http://connectivitycheck.platform.hicloud.com/generate_204'),
connectivity: z.string().default(''),
interval: z.string().default('1m'),
timeout: z.string().default('5s'),
sampling: z.number().int().min(1).default(2),

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