Compare commits

...

118 Commits

Author SHA1 Message Date
Zane 02002dc1c3 feat(routing): add client picker to user rules (#6271)
* feat(routing): add client picker to user rules

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

* feat(routing): polish user picker states

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

* fix(routing): keep custom user identifiers

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

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

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

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

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

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

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

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

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

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

Fixes #6283

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

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

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

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

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

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

Closes #6276

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

Three claims in the new description did not hold:

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

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

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

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

Addresses MHSanaei/3x-ui#6245.

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

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

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

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

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

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

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

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

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

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

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

* chore: retrigger CI

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore(docs): replace Prettier with oxfmt

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

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

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

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

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

* style(frontend): adopt oxfmt and format src

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

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

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

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

* ci: enforce formatting in CI and make verify

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

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

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

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

* ci: trigger CI on Makefile changes

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

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

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

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

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

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

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

Addresses the review on #6262.

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

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

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

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

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

* Harden remote routing refresh

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

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

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

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

---------

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

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

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

* chore(docs): remove development planning notes

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

* Document external link enable API fields

* Extend external client link metadata

* Fix external subscription cache status updates

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

Review follow-up on the REALITY target check.

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

* chore: drop the accidentally committed dist build stub

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

---------

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

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

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

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

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

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

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

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

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

* chore: drop the accidentally committed dist build stub

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

* chore: drop the accidentally committed dist build stub

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

* chore: drop the accidentally committed dist build stub

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

---------

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

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

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

* chore: drop the accidentally committed dist build stub

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

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

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

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

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

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

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

* chore: drop the accidentally committed dist build stub

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

---------

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

---------

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

* Fix inbound form tab error navigation

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

---------

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

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

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

Closes part of #5689.

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

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

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

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

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

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

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

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

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

* fix(runtime): propagate disableFlow to nodes

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

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

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

* fix(nodes): scope sub sort index updates

---------

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

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

* fix(mtls): reject malformed certificate bundle layout

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

---------

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

* fix(nodes): keep bearer tokens encrypted throughout

---------

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

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

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

---------

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

* security(api): make scoped token lifecycle enforceable

---------

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

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

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

* Update sub_fetch_test.go

---------

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

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

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

* test(sub): exercise production fragment encoding

---------

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

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

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

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

---------

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

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

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

* test(database): cover fail2ban reset safeguards

---------

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

* test(clients): guard bulk pushes behind commit

* fix(clients): fully delete remote bulk clients

---------

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

* fix(migrations): propagate transactional failures

---------

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

* fix(mtls): validate and serialize credential persistence

---------

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

* fix(nodes): preserve ambiguous and adopted aliases

---------

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

* fix(sub): preserve configured remark whitespace

---------

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

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

---------

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

* test(outbounds): cover update allocation failure

---------

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

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

---------

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

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

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

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

Review feedback on PR #6169:

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

---------

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-08-12 16:57:37 +02:00
Chen, Ting-An 69a8237581 fix(i18n): localize Chinese Xray labels (#6202)
* fix(i18n): localize Traditional Chinese Xray labels

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

* fix(i18n): localize Simplified Chinese Xray labels

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

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

---------

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


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

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

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

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

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


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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-31 18:30:43 +02:00
Isuru Sampath 31c1eed5dc fix dead code, typo, and minor bugs in main.go, process.go and index.go (#6167)
Fixes several small issues found during code review:
- fix(xray): return explicit nil instead of stale err in getLogPath
- fix(xray): remove duplicate doc comment on GetErrorLogPath
- refactor: remove unreachable return after log.Fatalf (×4)
- fix(cli): add missing newline to listen IP success message
- fix(cli): typo "form" → "from" in migrate help text
- refactor: simplify var+assign to short declaration for server/subServer
- fix(controller): return error from getTwoFactorEnable instead of swallowing it
2026-07-31 18:27:46 +02:00
PathGao 264f61eb90 Merge pull request #6161 from PathGao/feat-sidebar-pinning
feat(ui): let users pin the sidebar
2026-07-30 23:37:47 +08:00
PathGao ac584cfc90 fix(ui): reserve space for pinned sidebar
Keep page content accessible when the desktop sidebar remains expanded and cover the complete pin lifecycle.
2026-07-30 14:52:38 +08:00
PathGao 91c5d7b19f style(ui): preserve sidebar header spacing
Keep the original title alignment while fitting the pin with the existing header actions.
2026-07-30 14:48:03 +08:00
PathGao b2fe233108 fix(ui): align sidebar pin controls
Keep the pin with the expanded header actions and center the collapsed version link with the navigation rail.
2026-07-30 14:46:43 +08:00
PathGao 5373786faa feat(ui): let users pin the sidebar
Restore a persistent expanded-sidebar choice while preserving the compact hover rail as the default.
2026-07-30 14:39:55 +08:00
727 changed files with 52494 additions and 19849 deletions
+5 -2
View File
@@ -1,7 +1,7 @@
name: Bug report
description: Report something that is broken or behaving unexpectedly
title: "[Bug]: "
labels: ["bug", "needs triage"]
labels: ["bug"]
body:
- type: markdown
@@ -64,7 +64,10 @@ body:
id: screenshots
attributes:
label: Screenshots
description: Drag images directly into this field. Redact any sensitive data.
description: |
Drag images directly into this field. Redact any sensitive data.
Images cannot be searched or machine-read — always paste the exact
error text or log lines as text in the fields above as well.
validations:
required: false
+1 -1
View File
@@ -1,7 +1,7 @@
name: Feature request
description: Suggest an idea or improvement for 3x-ui
title: "[Feature]: "
labels: ["enhancement", "needs triage"]
labels: ["enhancement"]
body:
- type: markdown
+4 -1
View File
@@ -73,7 +73,10 @@ body:
id: screenshots
attributes:
label: Screenshots or config snippets
description: Drag images or paste relevant config. Redact tokens, real domains, client UUIDs.
description: |
Drag images or paste relevant config. Redact tokens, real domains,
client UUIDs. Prefer pasted text over screenshots — images cannot
be searched or machine-read.
validations:
required: false
+181
View File
@@ -0,0 +1,181 @@
# Repository context for the Claude bot
Shared briefing for the jobs in `.github/workflows/claude-bot.yml`. It exists so
these facts live in ONE place next to the code instead of being restated in each
prompt, where they went stale silently. (Pull-request review is separate: its
code-review skill is briefed with `CLAUDE.md` and `REVIEW.md`, not this.)
`CLAUDE.md`, `frontend/CLAUDE.md` and `docs/architecture.md` outrank this file.
Where they disagree with it, they win and this file is the thing to fix.
`docs/architecture.md` carries a "Symptom -> File" index and the cron-job table,
which answer "which file owns X" in one hop; grepping blind wastes turns on a
question it already answers.
## Stack
3x-ui is an open-source web control panel for managing Xray-core servers.
- Backend: Go 1.26, module `github.com/mhsanaei/3x-ui/v3`, Gin and GORM.
- It runs Xray-core as a managed child process (`internal/xray/process.go`) and
imports `github.com/xtls/xray-core` for config types and the gRPC
stats/handler/router API. The release the panel BUNDLES is pinned in
`DockerInit.sh`; the version it COMPILES against is pinned in `go.mod`, and
the two are not always the same.
- MTProto inbounds run a SECOND managed child, the `mtg-multi` binary (a
multi-secret mtg fork, panel-side code in `internal/mtproto/`), one process
per inbound. Client, ad-tag and quota/expiry edits are hot-applied through the
fork's management API (`PUT /secrets`) so connections survive, with a process
restart as the fallback on older binaries.
- Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux, the executable
directory on Windows) or PostgreSQL (`XUI_DB_TYPE` / `XUI_DB_DSN`). The SQLite
driver is CGo, so `CGO_ENABLED=0` builds fail.
- Frontend: React 19 + Ant Design 6 + Vite 8 + TypeScript in `frontend/`, built
into `internal/web/dist/` (gitignored) and embedded with `embed.FS`.
## Where things live
| area | path |
| --- | --- |
| entry point + `x-ui` CLI | `main.go` |
| env parsing | `internal/config/` |
| schema, migrations | `internal/database/`, `internal/database/model/` |
| Xray child process + config | `internal/xray/` |
| MTProto inbounds | `internal/mtproto/` |
| subscription server | `internal/sub/` |
| HTTP handlers | `internal/web/controller/` |
| business logic | `internal/web/service/` |
| cron jobs (schedules in `web.go startTask()`) | `internal/web/job/` |
| master/sub-node over mTLS | `internal/web/runtime/` |
| i18n | `internal/web/locale/`, `internal/web/translation/` |
| UI source | `frontend/src/` |
| install / upgrade | `install.sh`, `x-ui.sh`, `DockerInit.sh` |
## Hard rules a change must respect
- **Dispatch through `runtime.Runtime`.** Every state-changing inbound or client
operation goes through the interface in `internal/web/runtime/`, never
straight to `internal/xray/api.go`. A direct call passes every local test and
silently breaks every multi-node deployment; it is invisible in a single-box
reading of a diff.
- **Layering.** Controllers are thin — bind, validate, respond — with no GORM
queries, no Xray calls and no business rules. `internal/util/*` is leaf-only
and must not import service, controller or database. `internal/web/dist/` and
`frontend/src/generated/` are generated; a hand-edit is a violation.
- **Comments in committed Go/TS/TSX: 2 lines MAX per block**, spent on the *why*
a name cannot hold — an invariant, an issue number, a non-obvious constraint.
Exempt, never flag: `//go:build`, `//go:generate`, `//nolint:`,
`// Code generated ... DO NOT EDIT.`. HTML `<!-- -->` is fine.
- **The route contract chain**, which breaks in four distinct places:
1. a new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry
in `frontend/src/pages/api-docs/endpoints.ts` — pinned BOTH ways by
`TestRouteRegistryContract` in `internal/web/routes_contract_test.go`, so a
renamed or removed route that leaves a stale entry fails too;
2. generated artefacts must be regenerated with `make gen`, or CI's `codegen`
job fails on a dirty `frontend/src/generated` or
`frontend/public/openapi.json`;
3. a NEW struct crossing the API boundary must be added to the `StructAllow`
allowlist in `tools/openapigen/main.go`, or it is SILENTLY dropped from the
schemas and `frontend/scripts/build-openapi.mjs` then fails — a guaranteed
CI break, not a style nit;
4. the step NOTHING checks — `frontend/public/openapi.json` must be copied to
`docs/public/openapi.json` and the MDX regenerated with
`cd docs && pnpm gen:api`, because `docs-ci.yml` fires only on `docs/**`.
Step 4 is the one that reaches production wrong.
- **i18n.** A new English key goes in EVERY locale JSON in
`internal/web/translation/` (13 files) AND must be referenced from
`frontend/src` or Go in the SAME change.
`frontend/src/test/i18n-dead-keys.test.ts` fails on a missing locale file and
on an orphan key alike.
- **Migrations.** Schema changes are GORM `AutoMigrate` PLUS hand-written
migrations in `internal/database/db.go`. There are no migration files and no
down-migrations, and everything has to work on SQLite AND PostgreSQL.
- **Tests.** Stdlib `testing` only (no testify), table-driven with `t.Run`
subtests and `t.Helper()` on helpers. An assertion must pin the exact value,
typed error or emitted string — `err != nil` and `len(x) > 0` are findings,
not nits. Prefer real dependencies: a throwaway DB via
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` with `t.Cleanup`, and
`httptest` for HTTP. `internal/sub`'s `initSubDB(t)` is the template.
A test must FAIL without its fix; one that passes either way certifies
nothing and then gets cited as proof the fix works.
## The three link implementations
Link and subscription generation is implemented three times, independently:
| language | path | what it feeds |
| --- | --- | --- |
| Go | `internal/util/link/`, `internal/sub/` | what the panel serves |
| TS | `frontend/src/lib/xray/` | what the panel UI shows |
| TS | `docs/lib/xray/` | what the docs site shows |
A change to share-link or subscription output that touches one and not the
others is how they drift apart.
## Downstream programs that must accept what the panel emits
- **XTLS/Xray-core** — the Xray config the panel generates, and the VLESS/VMess
transport and security fields.
- **MetaCubeX/mihomo** — consumes the Clash YAML from `internal/sub/`.
- **SagerNet/sing-box** — parses the share links the panel emits.
- **mhsanaei/mtg-multi** — the MTProto sidecar whose TOML (`[secrets]`,
`[secret-ad-tags]`, `[secret-limits]`) and management API
(`PUT /secrets`, `POST /secrets/{name}/reset-quota`) `internal/mtproto/`
writes and calls.
## What CI runs
`.github/workflows/ci.yml`, on every pull request touching Go or frontend code.
It is paths-filtered, so a docs-only or workflow-only change produces no run.
| job | what it proves |
| --- | --- |
| `go-test` | `go test -shuffle=on -count=1` over every package except `frontend/node_modules` |
| `race` | the same set under `-race -shuffle=on` |
| `postgres-durable-first` | live PostgreSQL 16: the `PostgresCommitFailure` tests plus `TestHostAutoMigrateCreatesColumns_Postgres` and `TestMigrate_Postgres`. Both steps COUNT passes rather than assert on SKIP, so a renamed or deleted test fails the job |
| `govulncheck` | known vulnerabilities |
| `golangci` | `golangci-lint` |
| `fuzz-smoke` | 30s each on `FuzzParseLink` and `FuzzDecodeCertPin` |
| `codegen` | `npm run gen` then `git diff --exit-code` on the generated files |
| `frontend` | MSW worker drift, lint, format:check, typecheck, `npm test` (Vitest + headless-Chromium Storybook), build, build-storybook, `npm audit` |
**What CI does NOT prove.** These test families `t.Skip` unless an environment
variable is set, and CI sets only the PostgreSQL ones above:
| gate | covers |
| --- | --- |
| `XUI_TEST_PG_DSN` | PostgreSQL-specific paths |
| `XUI_DB_TYPE` + `XUI_DB_DSN` | dialect-dependent behaviour |
| `XRAY_E2E_BINARY` | the Xray gRPC end-to-end tests in `internal/xray/` |
| `XUI_SCALE_TEST` | scale tests in `internal/sub/`, `internal/web/job/`, `internal/web/service/` |
Mutation testing (`mutation.yml`) runs nightly and never on a pull request, so a
test that cannot fail is invisible to CI. `make verify` is the local gate.
## Support facts reporters get wrong
- Linux install: `bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)`
- Install generates a RANDOM username, password and web base path — never
admin/admin. The `x-ui` menu on the server shows or resets them.
- The installer service environment file is DISTRO-DEPENDENT:
`/etc/default/x-ui` (Debian/Ubuntu), `/etc/conf.d/x-ui` (Arch),
`/etc/sysconfig/x-ui` (RHEL/Fedora). Naming the wrong one means the reporter's
edit is silently never read by systemd — a common cause of "I set the variable
and nothing happened".
- Windows is supported. There the database sits next to the executable, not in
`/etc` — never quote the Linux path to a Windows user.
- SQLite to PostgreSQL: `x-ui migrate-db --dsn "postgres://..."`, then set
`XUI_DB_TYPE`/`XUI_DB_DSN` in that file and `systemctl restart x-ui`. The
source SQLite file is left in place.
- Docker image `ghcr.io/mhsanaei/3x-ui`; PostgreSQL profile
`docker compose --profile postgres up -d`. Fail2ban IP-limit enforcement needs
`NET_ADMIN` + `NET_RAW` (compose grants them; a bare `docker run` must add
`--cap-add=NET_ADMIN --cap-add=NET_RAW`).
- Never state that a `XUI_*` variable does not exist without grepping
`internal/config/` and `internal/tunnelmonitor/` first. The
`XUI_TUNNEL_HEALTH_*` family is the usual answer to "the panel restarts Xray
every few minutes".
- Security per inbound is none / tls / reality. XTLS is a VLESS *flow*
(`xtls-rprx-vision`), not a security setting — never tell anyone to pick XTLS
in the security dropdown.
- Never hardcode a version. For "is this already fixed" use
`gh release list -L 10`, `gh search commits`, and `git log -S`.
+31 -3
View File
@@ -8,6 +8,8 @@ on:
- "go.sum"
- "frontend/**"
- ".nvmrc"
- "Makefile"
- ".github/workflows/ci.yml"
push:
branches:
- main
@@ -17,6 +19,8 @@ on:
- "go.sum"
- "frontend/**"
- ".nvmrc"
- "Makefile"
- ".github/workflows/ci.yml"
permissions:
contents: read
@@ -53,6 +57,9 @@ jobs:
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
XUI_DB_TYPE: postgres
XUI_DB_DSN: "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=xui_durable sslmode=disable"
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
@@ -64,9 +71,24 @@ jobs:
- name: PostgreSQL durable-first tests
run: |
set -o pipefail
XUI_DB_TYPE=postgres XUI_DB_DSN="host=127.0.0.1 port=5432 user=postgres password=postgres dbname=xui_durable sslmode=disable" \
go test ./internal/web/service -run 'PostgresCommitFailure' -count=1 -v | tee /tmp/postgres-durable-first.log
if grep -q -- '--- SKIP' /tmp/postgres-durable-first.log; then
go test ./internal/web/service -run 'PostgresCommitFailure' -count=1 -v | tee /tmp/postgres-durable-first.log
# Count passes rather than assert no SKIP: a renamed or deleted test
# prints "no tests to run" and exits 0, leaving the step green for nothing.
passed=$(grep -c -- '--- PASS' /tmp/postgres-durable-first.log || true)
if [ "$passed" -lt 1 ]; then
echo "expected at least 1 passing durable-first test, got $passed" >&2
exit 1
fi
- name: PostgreSQL schema and migration tests
run: |
set -o pipefail
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log
# Both must pass. Counting, not SKIP-matching: renaming either test would
# otherwise leave this step green while testing nothing.
passed=$(grep -c -- '--- PASS' /tmp/postgres-schema.log || true)
if [ "$passed" -lt 2 ]; then
echo "expected 2 passing PostgreSQL schema tests, got $passed" >&2
exit 1
fi
@@ -162,9 +184,15 @@ jobs:
- name: Install
run: npm ci
working-directory: frontend
- name: Verify generated MSW worker is current
run: git diff --exit-code -- public/mockServiceWorker.js package-lock.json
working-directory: frontend
- name: Lint
run: npm run lint
working-directory: frontend
- name: Format check
run: npm run format:check
working-directory: frontend
- name: Typecheck
run: npm run typecheck
working-directory: frontend
File diff suppressed because it is too large Load Diff
+2
View File
@@ -55,6 +55,8 @@ jobs:
with:
context: .
push: true
provenance: mode=max
sbom: true
platforms: linux/amd64,linux/arm64/v8,linux/arm/v7,linux/arm/v6,linux/386
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+3
View File
@@ -42,6 +42,9 @@ jobs:
- name: Lint
run: pnpm lint
- name: Format check
run: pnpm format:check
- name: Test
run: pnpm test
+3 -2
View File
@@ -109,7 +109,7 @@ jobs:
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA::8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release -v main.go
go build -buildvcs=true -ldflags "$LDFLAGS" -o xui-release -v .
file xui-release
ldd xui-release || echo "Static binary confirmed"
@@ -247,6 +247,7 @@ jobs:
msystem: MINGW64
update: true
install: >-
git
mingw-w64-x86_64-gcc
mingw-w64-x86_64-sqlite3
mingw-w64-x86_64-pkg-config
@@ -270,7 +271,7 @@ jobs:
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA:0:8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release.exe -v main.go
go build -buildvcs=true -ldflags "$LDFLAGS" -o xui-release.exe -v .
- name: Copy and download resources
shell: pwsh
-3
View File
@@ -19,9 +19,6 @@ backup/
bin/
x-ui/
dist/
!internal/web/dist/
internal/web/dist/*
!internal/web/dist/.gitkeep
release/
node_modules/
+1 -1
View File
@@ -32,7 +32,7 @@ linters:
# golang.org/x/tools/go/packages is a generator change, out of scope here.
- linters:
- staticcheck
text: "SA1019: parser.ParseDir"
text: 'SA1019: (go/)?parser\.ParseDir'
# ST1005 (capitalized error strings) conflicts with intentional
# user-facing error copy that tests assert verbatim.
- linters:
+12 -3
View File
@@ -29,10 +29,19 @@
"XUI_LOG_FOLDER": "x-ui",
"XUI_BIN_FOLDER": "x-ui",
"XUI_DB_TYPE": "postgres",
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable",
"PATH": "C:\\Program Files\\PostgreSQL\\18\\bin;${env:PATH}"
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable"
},
"windows": {
"env": {
"XUI_DEBUG": "true",
"XUI_LOG_FOLDER": "x-ui",
"XUI_BIN_FOLDER": "x-ui",
"XUI_DB_TYPE": "postgres",
"XUI_DB_DSN": "postgres://xui:xuipass@127.0.0.1:5432/xui?sslmode=disable",
"PATH": "C:\\Program Files\\PostgreSQL\\18\\bin;${env:PATH}"
}
},
"console": "integratedTerminal"
},
}
]
}
+9 -1
View File
@@ -8,9 +8,17 @@
"args": [
"build",
"-o",
"bin/3x-ui.exe",
"bin/3x-ui",
"./main.go"
],
"windows": {
"args": [
"build",
"-o",
"bin/3x-ui.exe",
"./main.go"
]
},
"options": {
"cwd": "${workspaceFolder}"
},
+74 -23
View File
@@ -12,8 +12,10 @@ file locations when it can answer in one hop.
Runs Xray-core as a managed child process (`internal/xray/process.go`) and
imports `github.com/xtls/xray-core` for config types + gRPC stats/handler/router
API. MTProto inbounds run a second managed child — the `mtg-multi` binary
(`github.com/mhsanaei/mtg-multi`, a multi-secret fork built from source;
`internal/mtproto/`) — outside Xray, one process per inbound serving each
(a multi-secret mtg fork — NOT a Go dependency; its prebuilt release binary is
fetched at image/release build time by `DockerInit.sh` + `release.yml`,
panel-side code in `internal/mtproto/`) — outside Xray, one process per inbound
serving each
client's FakeTLS secret via the fork's `[secrets]` section (plus per-client
ad-tags via `[secret-ad-tags]` and per-client data quota / expiry via
`[secret-limits]`, mapped from the client's `totalGB`/`expiryTime`). Client,
@@ -32,11 +34,14 @@ file locations when it can answer in one hop.
- `main.go` — entry point + `x-ui` CLI (run, migrate, migrate-db, setting, cert).
- `internal/config/` — env parsing (XUI_DEBUG, XUI_LOG_LEVEL, XUI_LOG_FOLDER,
XUI_BIN_FOLDER, XUI_SKIP_HSTS, XUI_PORT, XUI_DB_*).
- `internal/database/` + `internal/database/model/` — GORM schema (Inbound,
Client, Setting, User), inbound Protocol enum, AutoMigrate + hand-written
migrations in `db.go`.
- `internal/database/` + `internal/database/model/` — GORM schema (~24 models;
Inbound, Client, Setting, User are the core), inbound Protocol enum,
AutoMigrate + hand-written migrations in `db.go`.
- `internal/xray/` — Xray child-process lifecycle, config generation, gRPC API.
- `internal/xray/geodata/` — streaming geosite/geoip `.dat` reader (cached
category index + paged entries) and `geosite:`/`geoip:`/`ext:` token parsing.
- `internal/mtproto/` — MTProto inbounds via the bundled `mtg-multi` binary.
- `internal/pia/` — PIA WireGuard protocol client (auth, signed server list, `/addKey`).
- `internal/sub/` — subscription server (raw / JSON / Clash).
- `internal/eventbus/` — in-process pub/sub (outbound/node health, xray.crash,
cpu.high, memory.high, login.attempt).
@@ -46,7 +51,8 @@ file locations when it can answer in one hop.
- `controller/` — panel + REST API handlers; OpenAPI at /panel/api/openapi.json.
- `service/` — business logic (InboundService, SettingService, XrayService,
node sync); subpackages tgbot/, email/, outbound/, panel/, integration/.
- `job/` — cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP).
- `job/` 17 cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP,
CPU/memory watchdogs, …); full table in `docs/architecture.md` §5.4.
- `middleware/`, `entity/`, `global/`, `session/` (CSRF), `network/`,
`runtime/` (master/sub-node over mTLS), `websocket/`.
- `locale/` + `translation/` — i18n, 13 embedded locale JSON files.
@@ -55,26 +61,49 @@ file locations when it can answer in one hop.
into `frontend/src/generated/` from Go structs. The OpenAPI doc itself
(`frontend/public/openapi.json`) is assembled from those + `endpoints.ts` by
`frontend/scripts/build-openapi.mjs`.
- `docs/` — separate Next.js/Fumadocs site (pnpm, own CI in `docs-ci.yml`,
outside `make verify`). Holds a THIRD independent implementation of
link/subscription generation in `docs/lib/xray/` — check it whenever
share-link or install-command output changes.
## Hard rules (non-negotiable)
- NO `//` line comments in committed Go/TS. Names carry meaning; rename instead
of annotating. Exempt: `//go:build`, `//go:generate`, and other directives.
- Fix size must match bug size. Find the root cause, then make the SMALLEST
change that removes it — a one-line guard beats a new subsystem. A small bug
does not earn new columns, jobs, abstractions, config knobs or helper layers.
If a fix genuinely needs new architecture, say so and get agreement first;
never ship it unasked next to the fix.
- Comments in committed Go/TS: 2 lines MAX per comment block. Make the name
carry the meaning first and rename rather than annotate; spend the 2 lines on
the *why* a name cannot hold — an invariant, an issue number, a non-obvious
constraint. Exempt: `//go:build`, `//go:generate`, and other directives.
HTML `<!-- -->` is fine. (A linter cannot enforce this — you must.)
- New `g.POST`/`g.GET` in `internal/web/controller/` REQUIRES a matching entry
in `frontend/src/pages/api-docs/endpoints.ts`, then `make gen` (or
`cd frontend && npm run gen`). It is a hand-maintained registry — nothing checks
it against the Go routes, so an omitted route silently vanishes from the docs.
`cd frontend && npm run gen`). Hand-maintained but pinned both ways by
`TestRouteRegistryContract` (`internal/web/routes_contract_test.go`): a missing
OR stale entry fails `make test-go`. Scope: `/panel/api/*` + a few session
routes; sub-server routes are exempt.
- Response examples come from Go struct `example:` tags via `tools/openapigen`
never hand-write them. A new struct must be added to openapigen's `StructAllow`
allowlist (`tools/openapigen/main.go`) or it is silently omitted from
schemas/examples (and `build-openapi.mjs` then fails on the missing schema).
- A new English i18n key must be added to EVERY locale JSON in
`internal/web/translation/` (13 files). Missing keys fall back to en-US (or
render the raw key if absent there too); nothing fails the build, so they are
easy to miss.
- A new or renamed endpoint has a FOURTH step nothing checks: copy
`frontend/public/openapi.json` `docs/public/openapi.json`, then
`cd docs && pnpm gen:api` to refresh the MDX under
`docs/content/docs/en/reference/api/`. `docs-ci.yml` fires only on `docs/**`.
- A new English i18n key goes in EVERY locale JSON in `internal/web/translation/`
(13 files) AND must be referenced from `frontend/src` or Go in the SAME commit —
`frontend/src/test/i18n-dead-keys.test.ts` fails both ways. It is a frontend
test, so run `npm test`, not just `make test-go`. At runtime the frontend falls
back to en-US; Go (`internal/web/locale/`) returns "" for an unknown key.
- DB / model changes require a migration in `internal/database/db.go`.
- Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `docs`,
`style`): `<area>: short imperative summary`, then a body explaining the why.
- Every state-changing inbound/client op dispatches through `runtime.Runtime`
(`internal/web/runtime/`) — never straight to `internal/xray/api.go`, never from
a controller or cron job. A direct call passes every local test and silently
breaks every multi-node deployment. Other layering rules: `docs/architecture.md` §8.
- Conventional commits: `type(area): short imperative summary`, then a body
explaining the why. Types in use: `fix`, `feat`, `chore`, `refactor`, `perf`,
`docs`, `style`.
## Go conventions
- Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests,
@@ -83,13 +112,26 @@ file locations when it can answer in one hop.
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` +
`t.Cleanup(func() { _ = database.CloseDB() })`; `httptest` for HTTP.
`internal/sub`'s `initSubDB(t)` is the template.
- A test must fail without its fix. Write it, revert the fix, watch it go red,
restore. A test that passes either way is worse than no test: it certifies
nothing and then gets cited as proof the fix works.
- Test what can actually break. No test for a getter, a constant, a rename, a
pure map lookup, or inputs the function can never receive. One real test that
drives the bug through the actual code path beats five that restate the code.
- Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`.
- Postgres, xray-gRPC-e2e and scale tests `t.Skip` unless `XUI_TEST_PG_DSN`,
`XUI_DB_TYPE`+`XUI_DB_DSN`, `XRAY_E2E_BINARY` or `XUI_SCALE_TEST` is set — a
green `go test ./...` does not mean those paths ran.
## Frontend conventions (summary; full version in frontend/CLAUDE.md)
- Ant Design 6 only — no Tailwind/shadcn. Targeted tweaks, not rewrites.
- TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in
- TS strict; oxlint's `typescript/no-explicit-any` is an error. Zod schemas in
`src/schemas/` are the source of truth; infer types with `z.infer`, never
hand-write. Do not edit `src/generated/`.
- Node 24 (`.nvmrc`) — `make gen` imports `.ts` directly and needs its type
stripping; Node 22 dies with `ERR_UNKNOWN_FILE_EXTENSION`. `npm test` includes
a headless-Chromium Storybook project, so run
`npx playwright install --with-deps chromium` once or `make verify` fails.
- Editing `frontend/src` does NOT change what users see until the Vite build is
regenerated into `internal/web/dist/`. In `XUI_DEBUG=true`, HTML is served from
the frozen embedded FS but JS/CSS off disk — after `npm run build` you MUST
@@ -99,15 +141,24 @@ file locations when it can answer in one hop.
output changes, never to make a red test green.
## Build, test, verify
Run `make help` for all targets. The full local gate that mirrors CI:
A fresh clone has no `internal/web/dist/`, so a bare `go build ./...` dies with
`pattern all:dist: no matching files found` while ~35 other packages pass — it
reads as a broken repo, not a missing step. Run `make dist-stub` once; every
`make` Go target already depends on it, which is why `make test-go` beats
`go test ./...`. Run `make help` for all targets. The local gate:
make verify
make verify # gen-check + lint + format-check + typecheck + test + build
# + build-storybook
That is the *fast* gate, not all of CI. `ci.yml` also runs `make race`,
`make vulncheck`, a live-Postgres job (where a SKIP counts as a failure) and a
30s fuzz smoke on `FuzzParseLink`/`FuzzDecodeCertPin` — run those locally when
you touch DB/dialect or parser code.
Common targets: `make gen` (regenerate Zod/OpenAPI), `make lint` (Go + frontend),
`make test` (Go `-shuffle=on` + frontend), `make race`, `make build`. See `Makefile`.
## Definition of done (before opening a PR)
1. `make gen` and confirm `git diff` on `frontend/src/generated` +
`frontend/public/openapi.json` is clean.
2. `make verify` passes.
3. Diff is focused; refactors are separate from feature work.
1. `make verify` passes — its `gen-check` already runs `make gen` and fails on a
dirty `frontend/src/generated` / `frontend/public/openapi.json`.
2. Diff is focused; refactors are separate from feature work.
+6 -5
View File
@@ -184,9 +184,9 @@ Only a genuinely **standalone bundle** (like `login` or `subpage`, reachable wit
- **TypeScript strict mode** — all new code in `.ts` / `.tsx`. Run `npm run typecheck` (`tsc --noEmit`) before pushing. The path alias `@/*` resolves to `src/*`.
- **Ant Design 6** is the only UI kit — no Tailwind, no shadcn. A previous attempt to migrate was rolled back. Small, targeted UX tweaks beat sweeping rewrites; raise broader visual changes for discussion before implementing.
- **Function components + hooks** everywhere. No class components.
- **No `//` line comments** in committed JS/TS/Vue/Go. HTML `<!-- ... -->` is fine for template structure. Names should carry the meaning; rename rather than annotate. Comments are reserved for the *why*, and only when the reason is surprising.
- **Comments in committed Go/TS/TSX: 2 lines MAX per comment block**, spent on the *why* a name cannot hold — an invariant, an issue number, a non-obvious constraint. Names should carry the meaning; rename rather than annotate. Compiler and tool directives (`//go:build`, `//go:generate`, `//nolint:`) are exempt, and HTML `<!-- ... -->` is fine for template structure.
- **Persian and Arabic users are first-class.** When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows. (Full RTL layout is not currently wired through AntD `ConfigProvider direction` — only the Jalali date picker is RTL-aware — so treat RTL as an open area, not a solved one.)
- **Schemas over `any`.** New config shapes go in `src/schemas/`; `@typescript-eslint/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
- **Schemas over `any`.** New config shapes go in `src/schemas/`; oxlint's `typescript/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
- **Document new endpoints.** Every new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry in `src/pages/api-docs/endpoints.ts` — it drives both the in-panel API docs and the generated OpenAPI/Zod (`npm run gen:api` / `gen:zod`).
- **Do not break link generation.** Share-link logic lives in `src/lib/xray/` (`inbound-link.ts`, `outbound-link-parser.ts`, …) and is round-tripped by the golden fixture suite — run `npm run test` after any change to URL generation, defaults, or TLS/Reality handling, and regenerate snapshots (`npx vitest run -u`) only for intentional changes. Two runtime paths consume it: the **inbounds page** and the **clients page** subscription links (`/panel/api/clients/subLinks/:subId` → backend `GetSubs`); exercise both.
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — read the live version there rather than trusting a number quoted here — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
@@ -200,7 +200,8 @@ frontend/
├── login.html — login + 2FA entry
├── subpage.html — public subscription viewer entry
├── tsconfig.json — strict, jsx: "react-jsx", paths "@/*" → "src/*"
├── eslint.config.jsESLint flat config (@eslint/js + typescript-eslint + react-hooks)
├── .oxlintrc.json oxlint config (typescript + react-hooks + jsx-a11y)
├── tools/oxlint/ — input-number-guard.mjs (#6121/#6127 guard as a JS plugin)
├── vite.config.js
├── vitest.config.ts
├── scripts/ — build-openapi.mjs (endpoints.ts → openapi.json)
@@ -279,7 +280,7 @@ CI runs this for you nightly (and on demand) via `.github/workflows/mutation.yml
### CI
`.github/workflows/ci.yml` runs per PR: `go-test` (with `-shuffle -count=1`), a `race` job (`-race -shuffle -count=1`), a `fuzz-smoke` job on the critical parsers, and the frontend `typecheck`/`lint`/`test`/`build`/`build-storybook`. Snapshots are regression guards — regenerate them (`npx vitest run -u`) only for intentional output changes, never to make a red test green.
`.github/workflows/ci.yml` runs per PR: `go-test` (with `-shuffle -count=1`), a `race` job (`-race -shuffle -count=1`), a `fuzz-smoke` job on the critical parsers, and the frontend `typecheck`/`lint`/`format:check`/`test`/`build`/`build-storybook`. Snapshots are regression guards — regenerate them (`npx vitest run -u`) only for intentional output changes, never to make a red test green.
## Sending a pull request
@@ -288,7 +289,7 @@ CI runs this for you nightly (and on demand) via `.github/workflows/mutation.yml
3. Run the relevant checks before pushing:
- `go build ./...`
- `go test ./...` (when Go code changed)
- `cd frontend && npm run typecheck && npm run lint && npm run test && npm run build && npm run build-storybook` (when the frontend changed; CI runs this same set on every PR via `.github/workflows/ci.yml`)
- `cd frontend && npm run typecheck && npm run lint && npm run format:check && npm run test && npm run build && npm run build-storybook` (when the frontend changed; CI runs this same set on every PR via `.github/workflows/ci.yml`)
4. Commit messages follow the existing pattern in `git log` — `<area>: short imperative summary`, then a body explaining the *why*. Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `style`, `docs`) are encouraged.
5. Open the PR against `main` with a brief description of what changed and how to test it.
+12 -4
View File
@@ -31,16 +31,24 @@ lint-go: dist-stub ## golangci-lint on Go sources
golangci-lint run
.PHONY: lint-fe
lint-fe: ## ESLint on frontend sources
lint-fe: ## oxlint on frontend sources
cd $(FRONTEND) && npm run lint
.PHONY: lint
lint: lint-go lint-fe ## All linters
.PHONY: format-check
format-check: ## oxfmt in check mode on frontend sources
cd $(FRONTEND) && npm run format:check
.PHONY: typecheck
typecheck: ## tsc --noEmit
cd $(FRONTEND) && npm run typecheck
.PHONY: msw-worker-check
msw-worker-check: ## Verify the tracked worker matches the installed MSW runtime
cmp $(FRONTEND)/public/mockServiceWorker.js $(FRONTEND)/node_modules/msw/lib/mockServiceWorker.js
.PHONY: test-go
test-go: dist-stub ## Go tests (shuffle, no cache)
go test -shuffle=on -count=1 $(GO_PKGS)
@@ -72,8 +80,8 @@ build: build-fe ## Build the frontend then the Go binary
build-storybook: ## Build the static Storybook (compile-checks all stories)
cd $(FRONTEND) && npm run build-storybook
# The PR gate. Matches ci.yml: codegen freshness, both linters, typecheck,
# both test suites, a full build, and the Storybook compile-check.
# The PR gate. Matches ci.yml: codegen freshness, both linters, the formatter,
# typecheck, both test suites, a full build, and the Storybook compile-check.
.PHONY: verify
verify: gen-check lint typecheck test build build-storybook ## Full local gate (mirrors CI)
verify: gen-check lint format-check typecheck msw-worker-check test build build-storybook ## Full local gate (mirrors CI)
@echo "verify: OK"
+147
View File
@@ -0,0 +1,147 @@
# Review instructions
3x-ui is a Go (Gin + GORM) web panel that generates configuration, share links
and subscriptions for other programs — Xray-core, mihomo, sing-box, mtg-multi —
and is deployed by operators who upgrade in place. Judge findings by what
breaks for those consumers and operators, not by style.
## Severity
Mark every finding with exactly one of these, at the start of the finding:
| Marker | Severity | Use it for |
| --- | --- | --- |
| 🔴 | Important | A defect this pull request introduces or makes worse, in one of the classes under "What Important means here". Worth fixing before it merges. |
| 🟡 | Nit | Style, naming, refactoring, and an ordinary `CLAUDE.md` violation the change introduces — a source comment block over two lines, a fix larger than the bug it removes, a test `CLAUDE.md` rejects outright. |
| 🟣 | Pre-existing | A real bug you hit while reading that this pull request neither introduced nor made worse. |
Not every `CLAUDE.md` rule is a nit. The three listed below — the dispatch
rule, the migration rule, the endpoint chain — are Important, because each one
passes every local test and breaks a real deployment.
Severity follows what this pull request did, not how alarming the defect looks
on its own. One the change worsens is 🔴 for the regression it added, not for
the whole defect; one it merely brought into view is 🟣.
Checking what this panel emits means reading far more code than the diff
changes, so pre-existing bugs surface on every review. One already on the base
branch stays 🟣 however bad it is: this pull request did not cause it, so it
cannot be a reason to hold this pull request. Say in one clause that it
predates the change. The exception is a live security hole on an exposed
surface — still 🟣, but open the summary with it.
## What Important means here
- Security on the exposed surfaces: `internal/web/controller/`, session and
middleware code, the PUBLIC `internal/sub/` subscription server, and Xray
config generation in `internal/xray/`.
- A state-changing inbound or client operation that bypasses `runtime.Runtime`
(`internal/web/runtime/`) and calls `internal/xray/api.go` directly, or
dispatches from a controller or cron job. It passes every local test and
silently breaks every multi-node deployment.
- A schema or model change without a matching hand-written migration in
`internal/database/db.go`, one that behaves differently on SQLite and
PostgreSQL, or one that loses or overwrites operator data on upgrade or
rollback. There are no migration files and no down-migrations.
- A change to what the panel emits on the wire — Xray config JSON, share
links, subscription/Clash YAML, mtg-multi TOML — that a downstream client
would reject or read differently, or that makes the three independent link
implementations (Go `internal/util/link/` + `internal/sub/`, TS
`frontend/src/lib/xray/`, TS `docs/lib/xray/`) diverge from one another.
- Any edit to `.github/workflows/`: this repository runs workflows with
secrets against a public fork stream. Untrusted expression interpolation
into `run:` blocks, broadened permissions, weakened guards, or a job that
executes pull-request code.
## Always check
- A new `g.POST`/`g.GET` in `internal/web/controller/` needs the whole chain:
an entry in `frontend/src/pages/api-docs/endpoints.ts`, regenerated
artefacts (`make gen`), any new API-boundary struct added to `StructAllow`
in `tools/openapigen/main.go`, and `frontend/public/openapi.json` copied to
`docs/public/openapi.json` with the docs MDX regenerated
(`cd docs && pnpm gen:api`). CI checks the first three; the docs copy is
checked by nothing — a missed copy is Important, not a nit.
- A bug fix carries a test that would fail without the fix. A test that cannot
tell the broken behaviour from the fixed one passes before and after, so it
certifies nothing and is itself the finding — asserting only `err != nil` or
`len(x) > 0`, or going green by regenerating golden fixtures or Vitest
snapshots.
- No second way to do a thing already decided: Go tests are stdlib `testing`
(never testify), the panel is Ant Design (never Tailwind or shadcn). Neither
golangci-lint nor oxlint forbids the import, so it passes CI clean.
## Do not report
- Anything CI already enforces: golangci-lint and gofumpt, oxlint, format
and typecheck, govulncheck, and `npm audit --omit=dev --audit-level=high`.
A dev-dependency advisory is out of scope on purpose: it ships to nobody.
- The contents of generated files (`frontend/src/generated/`,
`frontend/public/openapi.json`, `docs/public/openapi.json`) or lock files.
Those files being STALE after a source change is reportable; their style
is not.
- Missing tests for getters, constants, renames or pure map lookups —
`CLAUDE.md` rejects such tests outright.
- A missing or unreferenced i18n key.
`frontend/src/test/i18n-dead-keys.test.ts` pins the 13 locale files in
`internal/web/translation/` in both directions, so the `frontend` job is
already red. Report the failing check, not the key.
## A higher bar, not silence
Everything named under "What Important means here" gets full scrutiny. Two
areas do not — they earn review, but report there only what you are
near-certain about and that actually breaks something:
- `docs/` — the standalone Fumadocs site, with its own CI and its own
dependency tree. `docs/lib/xray/` is the exception and gets full scrutiny:
it is the third link implementation.
- `internal/web/translation/` — the key set is CI's job and the wording of a
translation is nobody's here.
## Verification bar
- A claim about behaviour needs a `file:line` citation from this repository,
not an inference from a name.
- A claim that a downstream client rejects or requires a wire-format detail —
a config key, JSON tag, URI query parameter, YAML or TOML key, an encoding
or hash choice — must name the upstream symbol that decides it (repository,
file, identifier). If you cannot verify it, keep the finding but say
explicitly that it is unverified instead of asserting it.
- "CI passed" is a claim too, and needs the same evidence: say it only of a
run you actually read. A green one proves less here than it looks — only
`postgres-durable-first` runs against PostgreSQL, `go-test` and `race` are
SQLite, and `XRAY_E2E_BINARY` and `XUI_SCALE_TEST` are set by no job, so
those tests have never run in CI at all. Where a change touches dialect,
migration or Xray gRPC code that no job exercised, say it is unverified
rather than repeating a green tick as proof.
## Cap the volume
🔴 findings are never capped. Report every one.
Report at most five 🟡 nits and at most three 🟣 pre-existing bugs. Past that,
say "plus N similar" in the summary instead of posting them.
A cap decides WHICH ones survive, so choose rather than truncate: the same nit
repeated across files is ONE finding with a count, not five slots; a nit in
code this pull request wrote outranks one in code it only moved; and a nit
nobody would act on does not deserve a slot at all.
After the first review of a pull request, report 🔴 findings only: a one-line
fix must not reach round seven on style.
## What the comment must show
Open with a one-line tally — `2 🔴 / 4 🟡 / 1 🟣` — so the author sees the
shape of the review before the detail. When nothing is 🔴, lead with
`No blocking issues` and put the tally after it.
The posted comment is the only part of a review anyone sees, so a bare "no
issues found" is a receipt, not a review: nothing in it says whether the diff
was read or the run died early. Every comment therefore ends with a short
coverage list — one line per area actually checked, naming what was examined
and what it turned out to be, plus the head SHA and the size of the diff it
covers. Say which claims could not be verified and why, including a check
this environment blocked. Keep that coverage list under ten lines; it is
evidence, not a retelling of the pull request.
+22
View File
@@ -0,0 +1,22 @@
# Security Policy
## Reporting a vulnerability
Do not open a public issue for anything you believe is exploitable — an
authentication bypass, remote code execution, injection, secret or
credential exposure, privilege escalation. A public report gives attackers
a head start against every 3x-ui deployment.
Instead, use GitHub's private vulnerability reporting: open this
repository's **Security** tab and click **Report a vulnerability**. Include
the affected 3x-ui version, reproduction steps, and the impact you see.
You will receive replies in the advisory thread.
There is no bug-bounty program. Fixes ship in the next release, and the
advisory is published after a fixed version is available.
## Supported versions
Only the latest release receives security fixes. Update with the install
script or your package channel and confirm the problem still exists before
reporting.
+198
View File
@@ -0,0 +1,198 @@
package main
// The Claude bot prompts in .github/workflows/claude-bot.yml no longer restate
// repository facts; they read .github/claude/repo-context.md instead. A stale
// claim in that file is invisible until it produces a wrong review, so every
// claim a machine can check is pinned here.
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
const (
botContextPath = ".github/claude/repo-context.md"
reviewPath = "REVIEW.md"
ciWorkflowPath = ".github/workflows/ci.yml"
)
func readRepoFile(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(b)
}
// section returns the text between two markers, so a table is matched only
// inside the heading that owns it.
func section(t *testing.T, doc, from, to string) string {
t.Helper()
i := strings.Index(doc, from)
if i < 0 {
t.Fatalf("%s no longer contains the heading %q", botContextPath, from)
}
rest := doc[i+len(from):]
if j := strings.Index(rest, to); j >= 0 {
return rest[:j]
}
return rest
}
func TestBotContextLocaleFileCount(t *testing.T) {
doc := readRepoFile(t, botContextPath)
m := regexp.MustCompile("`internal/web/translation/` \\((\\d+) files\\)").FindStringSubmatch(doc)
if m == nil {
t.Fatalf("%s no longer states the locale file count as \"`internal/web/translation/` (N files)\"", botContextPath)
}
files, err := filepath.Glob("internal/web/translation/*.json")
if err != nil {
t.Fatalf("glob locales: %v", err)
}
if got := len(files); m[1] != itoa(got) {
t.Errorf("%s claims %s locale files, internal/web/translation/ holds %d; update the claim and every prompt that relies on it", botContextPath, m[1], got)
}
}
func itoa(n int) string {
if n == 0 {
return "0"
}
var b []byte
for n > 0 {
b = append([]byte{byte('0' + n%10)}, b...)
n /= 10
}
return string(b)
}
func TestBotContextNamesRealCIJobs(t *testing.T) {
doc := readRepoFile(t, botContextPath)
ci := readRepoFile(t, ciWorkflowPath)
table := section(t, doc, "## What CI runs", "**What CI does NOT prove.**")
rows := regexp.MustCompile("(?m)^\\| `([a-z0-9-]+)` \\|").FindAllStringSubmatch(table, -1)
if len(rows) < 5 {
t.Fatalf("expected the CI table in %s to list at least 5 jobs, found %d", botContextPath, len(rows))
}
for _, r := range rows {
t.Run(r[1], func(t *testing.T) {
if !strings.Contains(ci, "\n "+r[1]+":\n") {
t.Errorf("%s describes a CI job %q that %s does not define", botContextPath, r[1], ciWorkflowPath)
}
})
}
}
func TestBotContextNamesRealPaths(t *testing.T) {
// REVIEW.md briefs the review job the way repo-context.md briefs the
// issue bot, so both get their paths pinned.
// internal/web/dist and frontend/node_modules are build output: absent from a
// fresh clone, created by `make dist-stub` and `npm ci`.
generated := map[string]bool{
"internal/web/dist/": true,
"frontend/node_modules": true,
"frontend/src/generated/": true,
}
seen := map[string]bool{}
counts := map[string]int{}
for _, src := range []string{botContextPath, reviewPath} {
for _, m := range regexp.MustCompile("`([^`]+)`").FindAllStringSubmatch(readRepoFile(t, src), -1) {
p := m[1]
if !regexp.MustCompile(`^(internal|frontend|docs|tools|\.github)/`).MatchString(p) ||
strings.ContainsAny(p, "*{ ") || generated[p] || seen[p] {
continue
}
seen[p] = true
counts[src]++
t.Run(p, func(t *testing.T) {
if _, err := os.Stat(strings.TrimSuffix(p, "/")); err != nil {
t.Errorf("%s names %q, which does not exist; the bot prompts trust this file", src, p)
}
})
}
}
if counts[botContextPath] < 20 {
t.Errorf("expected the bot context to name at least 20 repository paths, found %d - has the file been gutted?", counts[botContextPath])
}
}
func TestBotContextSkipGatesExist(t *testing.T) {
doc := readRepoFile(t, botContextPath)
table := section(t, doc, "**What CI does NOT prove.**", "Mutation testing")
// [A-Z0-9_] and not [A-Z_]: XRAY_E2E_BINARY carries a digit, and excluding it
// silently dropped that gate from the check instead of failing.
gates := regexp.MustCompile("`((?:XUI|XRAY)_[A-Z0-9_]+)`").FindAllStringSubmatch(table, -1)
if len(gates) < 5 {
t.Fatalf("expected at least 5 skip-gate variables in %s, found %d", botContextPath, len(gates))
}
var sources []string
err := filepath.WalkDir("internal", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && strings.HasSuffix(path, ".go") {
sources = append(sources, path)
}
return nil
})
if err != nil {
t.Fatalf("walk internal: %v", err)
}
for _, g := range gates {
t.Run(g[1], func(t *testing.T) {
for _, f := range sources {
if strings.Contains(readRepoFile(t, f), g[1]) {
return
}
}
t.Errorf("%s lists %s as a test skip gate, but no .go file under internal/ reads it", botContextPath, g[1])
})
}
}
// REVIEW.md tells the reviewer which CI job proves what, and which skip gates
// mean a green run proved nothing. Both go stale silently on a rename.
func TestReviewNamesRealCIJobsAndGates(t *testing.T) {
doc := readRepoFile(t, reviewPath)
ci := readRepoFile(t, ciWorkflowPath)
// Hyphenated only: a single-word job name is indistinguishable from prose.
jobs := regexp.MustCompile("`([a-z0-9]+(?:-[a-z0-9]+)+)`").FindAllStringSubmatch(doc, -1)
if len(jobs) < 2 {
t.Fatalf("expected %s to name at least 2 CI jobs in backticks, found %d", reviewPath, len(jobs))
}
for _, j := range jobs {
t.Run(j[1], func(t *testing.T) {
if !strings.Contains(ci, "\n "+j[1]+":\n") {
t.Errorf("%s names a CI job %q that %s does not define", reviewPath, j[1], ciWorkflowPath)
}
})
}
for _, g := range regexp.MustCompile("`((?:XUI|XRAY)_[A-Z0-9_]+)`").FindAllStringSubmatch(doc, -1) {
t.Run(g[1], func(t *testing.T) {
if strings.Contains(ci, g[1]) {
t.Errorf("%s claims %s is never set in CI, but %s sets it", reviewPath, g[1], ciWorkflowPath)
}
})
}
}
// The i18n rule is the one REVIEW.md states as a number, so it is the one that
// goes wrong silently when a locale is added.
func TestReviewLocaleFileCount(t *testing.T) {
doc := readRepoFile(t, reviewPath)
m := regexp.MustCompile(`(\d+) locale files`).FindStringSubmatch(doc)
if m == nil {
t.Fatalf("%s no longer states the i18n rule as \"N locale files\"", reviewPath)
}
files, err := filepath.Glob("internal/web/translation/*.json")
if err != nil {
t.Fatalf("glob locales: %v", err)
}
if got := len(files); m[1] != itoa(got) {
t.Errorf("%s tells the reviewer to expect %s locale files, internal/web/translation/ holds %d", reviewPath, m[1], got)
}
}
+18
View File
@@ -87,6 +87,24 @@ docker run --rm \
*) echo "FAIL: panel did not serve (status ${code:-none})"; tail -n 30 /tmp/xui.log; exit 1 ;;
esac
echo "--- verifying a second install preserves custom bin/ files ---"
echo "custom-sentinel" > /usr/local/x-ui/bin/geoip_custom.dat
geoip_sum_before=$(sha256sum /usr/local/x-ui/bin/geoip.dat | cut -d" " -f1)
if [ -n "${XUI_SMOKE_VERSION:-}" ]; then
cat /root/install.sh | bash -s -- "$XUI_SMOKE_VERSION"
else
cat /root/install.sh | bash
fi
test -f /usr/local/x-ui/bin/geoip_custom.dat \
|| { echo "FAIL: custom bin/ file did not survive a second install"; exit 1; }
[ "$(cat /usr/local/x-ui/bin/geoip_custom.dat)" = "custom-sentinel" ] \
|| { echo "FAIL: custom bin/ file content changed across a second install"; exit 1; }
geoip_sum_after=$(sha256sum /usr/local/x-ui/bin/geoip.dat | cut -d" " -f1)
[ "$geoip_sum_after" = "$geoip_sum_before" ] \
|| { echo "FAIL: bundled geoip.dat changed across a same-version reinstall"; exit 1; }
echo "SMOKE_PASS: user=$XUI_USERNAME port=$XUI_PANEL_PORT path=$XUI_WEB_BASE_PATH"
'
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"ignorePatterns": [
"node_modules",
".next",
".source",
"out",
"pnpm-lock.yaml",
"public/openapi.json",
// Reflowing MDX prose merges headings into paragraphs and collapses lists
// inside JSX components (Steps/Callout). Author MDX by hand.
"content/**/*.mdx",
// Generated API reference pages (fumadocs-openapi output).
"content/docs/**/reference/api"
]
}
+42
View File
@@ -0,0 +1,42 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
".next/**",
".source/**",
"out/**",
"node_modules/**",
"next-env.d.ts",
"content/docs/**/reference/api/**"
],
"plugins": ["typescript", "react", "nextjs", "jsx-a11y", "import"],
"categories": {
"correctness": "error"
},
"env": {
"browser": true,
"node": true,
"es2022": true
},
"rules": {
"no-var": "error",
"prefer-const": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"typescript/no-explicit-any": "error",
"typescript/no-unused-vars": "warn",
"typescript/ban-ts-comment": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-namespace": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-unused-expressions": "warn",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/triple-slash-reference": "error",
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"import/no-anonymous-default-export": "warn",
"jsx-a11y/prefer-tag-over-role": "off"
}
}
-10
View File
@@ -1,10 +0,0 @@
node_modules
.next
.source
out
pnpm-lock.yaml
public/openapi.json
# Don't let Prettier reflow MDX prose — it merges headings into paragraphs and
# collapses lists inside JSX components (Steps/Callout). Author MDX by hand.
content/**/*.mdx
content/docs/**/reference/api
-7
View File
@@ -1,7 +0,0 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2
}
+3 -3
View File
@@ -20,12 +20,12 @@ pnpm dev # http://localhost:3000
| `pnpm build` | Production build |
| `pnpm start` | Serve the production build |
| `pnpm typecheck` | Generate MDX/route types and run `tsc --noEmit` |
| `pnpm lint` | ESLint (flat config) |
| `pnpm format` | Format with Prettier |
| `pnpm lint` | oxlint (`.oxlintrc.json`) |
| `pnpm format` | Format with oxfmt (`.oxfmtrc.json`) |
| `pnpm test` | Run unit tests (Vitest) for `lib/xray/*` pure logic |
| `pnpm gen:api` | Generate the API reference from `public/openapi.json` |
Before opening a pull request, please run `pnpm typecheck`, `pnpm lint`, and
Before opening a pull request, please run `pnpm typecheck`, `pnpm lint`, `pnpm format:check`, and
`pnpm test` — these are the same checks that CI runs on every PR.
## License
+16 -16
View File
@@ -63,15 +63,15 @@ ever leaves your browser**:
## Tech stack
| Layer | Technology |
| ---------- | ---------------------------------------------------------- |
| Framework | [Next.js 16](https://nextjs.org) (App Router) · React 19 |
| Docs | [Fumadocs](https://fumadocs.dev) (`-ui` / `-core` / `-mdx`) |
| Styling | [Tailwind CSS v4](https://tailwindcss.com) |
| Search | [Orama](https://orama.com) static index |
| Language | TypeScript (strict) |
| Tests | [Vitest](https://vitest.dev) for the pure `lib/xray` logic |
| Tooling | pnpm · ESLint 9 · Prettier |
| Layer | Technology |
| --------- | ----------------------------------------------------------- |
| Framework | [Next.js 16](https://nextjs.org) (App Router) · React 19 |
| Docs | [Fumadocs](https://fumadocs.dev) (`-ui` / `-core` / `-mdx`) |
| Styling | [Tailwind CSS v4](https://tailwindcss.com) |
| Search | [Orama](https://orama.com) static index |
| Language | TypeScript (strict) |
| Tests | [Vitest](https://vitest.dev) for the pure `lib/xray` logic |
| Tooling | pnpm · oxlint · oxfmt |
## Quick start
@@ -86,13 +86,13 @@ pnpm dev # http://localhost:3000
Useful scripts:
| Script | Description |
| ---------------- | -------------------------------------------- |
| `pnpm dev` | Start the dev server |
| `pnpm build` | Production build (also typechecks) |
| `pnpm typecheck` | Generate MDX/route types and `tsc --noEmit` |
| `pnpm lint` | Run ESLint |
| `pnpm test` | Run unit tests (Vitest) |
| Script | Description |
| ---------------- | ------------------------------------------- |
| `pnpm dev` | Start the dev server |
| `pnpm build` | Production build (also typechecks) |
| `pnpm typecheck` | Generate MDX/route types and `tsc --noEmit` |
| `pnpm lint` | Run oxlint (`.oxlintrc.json`) |
| `pnpm test` | Run unit tests (Vitest) |
See [`CONTRIBUTING.md`](./CONTRIBUTING.md) for the full list and project conventions.
+4 -16
View File
@@ -1,30 +1,18 @@
import '../global.css';
import { RootProvider } from 'fumadocs-ui/provider/next';
import { Inter, Vazirmatn } from 'next/font/google';
import { i18n, localeDirection } from '@/lib/i18n';
import { i18n } from '@/lib/i18n';
import { provider } from '@/lib/i18n-ui';
import SearchDialog from '@/components/search-dialog';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
// Persian UI font; covers Arabic + Latin glyphs so mixed content renders well.
const vazirmatn = Vazirmatn({ subsets: ['arabic'], display: 'swap' });
export function generateStaticParams() {
return i18n.languages.map((lang) => ({ lang }));
}
export default async function LangLayout({ params, children }: LayoutProps<'/[lang]'>) {
const { lang } = await params;
const dir = localeDirection(lang);
const fontClassName = lang === 'fa' ? vazirmatn.className : inter.className;
return (
<html lang={lang} dir={dir} className={fontClassName} suppressHydrationWarning>
<body className="flex min-h-screen flex-col" suppressHydrationWarning>
<RootProvider i18n={provider(lang)} search={{ SearchDialog }}>
{children}
</RootProvider>
</body>
</html>
<RootProvider i18n={provider(lang)} search={{ SearchDialog }} theme={{ enabled: false }}>
{children}
</RootProvider>
);
}
+2 -7
View File
@@ -5,13 +5,8 @@ import { createFromSource } from 'fumadocs-core/search/server';
export const revalidate = false;
export const dynamic = 'force-static';
// Static search index: works under both SSR/Vercel and static export
// (`output: 'export'`). The client loads this prebuilt index and searches
// in-browser (see the `type: 'static'` search option in app/[lang]/layout.tsx).
// All locales currently hold English (fallback) content, and Orama has no
// Persian tokenizer, so map every locale to the English tokenizer. When real
// translations land, switch ru -> 'russian', zh -> 'mandarin' (with
// @orama/tokenizers), etc. See https://docs.orama.com/open-source/supported-languages
// Every locale still serves English fallback content, so all map to zbsearch's
// English tokenizer (its SUPPORTED_LANGUAGES has no Persian or Chinese anyway).
export const { staticGET: GET } = createFromSource(source, {
localeMap: {
en: 'english',
+30 -5
View File
@@ -1,10 +1,16 @@
import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import { Inter, Vazirmatn } from 'next/font/google';
import './global.css';
import { appName, appTagline, siteUrl } from '@/lib/shared';
import { i18n, localeDirection } from '@/lib/i18n';
// Global SEO defaults. The real <html>/<body> live in `app/[lang]/layout.tsx`
// so we can set `lang`/`dir` per locale (RTL for fa); this root layout is a
// pass-through that only carries site-wide metadata.
const inter = Inter({ subsets: ['latin'], display: 'swap' });
// Persian UI font; covers Arabic + Latin glyphs so mixed content renders well.
const vazirmatn = Vazirmatn({ subsets: ['arabic'], display: 'swap' });
// Global SEO defaults and document shell. Locale-aware html attributes are
// computed from route params so RTL locales get a correct base direction.
export const metadata: Metadata = {
metadataBase: new URL(siteUrl),
title: {
@@ -26,6 +32,25 @@ export const metadata: Metadata = {
},
};
export default function RootLayout({ children }: { children: ReactNode }) {
return children;
export default async function RootLayout({
children,
params,
}: {
children: ReactNode;
params: Promise<{ lang?: string }>;
}) {
const { lang: rawLang } = await params;
const lang = i18n.languages.includes(rawLang as (typeof i18n.languages)[number])
? (rawLang as (typeof i18n.languages)[number])
: i18n.defaultLanguage;
const dir = localeDirection(lang);
const fontClassName = lang === 'fa' ? vazirmatn.className : inter.className;
return (
<html lang={lang} dir={dir} className={fontClassName} suppressHydrationWarning>
<body className="flex min-h-screen flex-col" suppressHydrationWarning>
{children}
</body>
</html>
);
}
+109 -97
View File
@@ -29,17 +29,17 @@ token), with a process restart as the fallback on older binaries.
Servers and processes, all launched from `main.go`:
| Server / process | Package | Purpose | Default port |
|---|---|---|---|
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
| **mtg-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | per inbound |
| Server / process | Package | Purpose | Default port |
| ---------------- | --------------------------------- | ------------------------------------------------------------------ | ----------------- |
| **Panel** | `internal/web` | Admin REST/WS API + serves the embedded SPA | 2053 |
| **Subscription** | `internal/sub` | Public endpoint that hands out client configs (raw / JSON / Clash) | `subPort` setting |
| **Xray-core** | supervised via `internal/xray` | The actual proxy engine; a child process, not Go code | `inbounds[].port` |
| **mtg-multi** | supervised via `internal/mtproto` | MTProto proxy child process for MTProto inbounds (multi-secret) | per inbound |
Two key ideas that explain most of the complexity:
1. **The DB → Xray config pipeline.** Inbounds/clients live in the DB. On every change the
backend regenerates the Xray config and applies it — preferring a *hot diff* (live gRPC
backend regenerates the Xray config and applies it — preferring a _hot diff_ (live gRPC
API mutation) over a full process restart. See §5.1.
2. **The Runtime abstraction (multi-node).** A panel can manage remote "nodes" (other 3x-ui
instances). Every state-changing inbound/client operation is dispatched through a
@@ -52,6 +52,7 @@ Two key ideas that explain most of the complexity:
## 2. Tech stack
**Backend (Go 1.26):**
- Web framework: **Gin** (`gin-gonic/gin`) + sessions (cookie store), gzip.
- ORM: **GORM** with **SQLite** (default) or **PostgreSQL** (`XUI_DB_TYPE=postgres`).
- Scheduler: **robfig/cron/v3** (seconds-precision) for all background jobs.
@@ -61,6 +62,7 @@ Two key ideas that explain most of the complexity:
- Misc: gorilla/websocket, gopsutil (system stats), go-qrcode, gotp (2FA TOTP).
**Frontend (`frontend/`):**
- **React 19** + **Ant Design 6** + **Vite 8** + **TypeScript**.
- Data layer: **TanStack Query** (`@tanstack/react-query`) over the native **Fetch API**; **Zod 4** schemas.
- Router: **react-router 8**. Charts: **uPlot** (`frontend/src/components/viz/Sparkline.tsx`). Editor: **CodeMirror 6**.
@@ -95,7 +97,7 @@ Browser (React, fetch)
```
The controller layer is thin. **Business logic lives in services.** When something is wrong
with *behavior*, the bug is almost always in a service file, not a controller.
with _behavior_, the bug is almost always in a service file, not a controller.
### 3.2 Subscription request (end-user fetching their config)
@@ -134,6 +136,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ └── model/ # **ALL GORM models** (model.go ~1.1k lines + siblings:
│ │ # node_client_traffic.go, node_client_ip.go,
│ │ # client_global_traffic.go). ⭐ Start here for data shape.
│ ├── pia/ # PIA WireGuard protocol client (auth, signed server list, /addKey)
│ ├── eventbus/ # In-process pub/sub (buffered channel): outbound.down|up,
│ │ # xray.crash, node.down|up, cpu.high, memory.high, login.attempt
│ ├── tunnelmonitor/ # Optional tunnel health probe (XUI_TUNNEL_HEALTH_* env vars):
@@ -147,7 +150,9 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ ├── inbound.go # Inbound JSON shaping
│ │ ├── client_traffic.go # ClientTraffic model (persisted as client_traffics)
│ │ ├── traffic.go # Traffic type helpers
│ │ ── log_writer.go # Pipe Xray stdout/stderr into the panel logger
│ │ ── log_writer.go # Pipe Xray stdout/stderr into the panel logger
│ │ └── geodata/ # Browse geosite/geoip .dat: streaming protowire reader,
│ │ # cached category index, routing-token parsing (token.go)
│ │
│ ├── web/ # The panel server
│ │ ├── web.go # ⭐ Server bootstrap: initRouter (all routes) + startTask (all cron jobs)
@@ -159,7 +164,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── host.go # /panel/api/hosts (per-inbound subscription host overrides)
│ │ │ ├── server.go # /panel/api/server (status, xray version, certs, logs, DB import/export)
│ │ │ ├── setting.go # /panel/api/setting (settings + API tokens)
│ │ │ ├── xray_setting.go # /panel/api/xray (raw Xray config editor, WARP/Nord)
│ │ │ ├── xray_setting.go # /panel/api/xray (raw Xray config editor, WARP/Nord/PIA, geodata)
│ │ │ ├── api.go # /panel/api gateway (token auth, envelope + CSRF wiring)
│ │ │ ├── index.go # login/logout/csrf/2FA
│ │ │ ├── spa.go # SPA fallback for /panel UI routes
@@ -189,6 +194,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── traffic_writer.go # Batched persistence of traffic deltas to the DB
│ │ │ ├── xray.go # ⭐ XrayService: config gen + restart/hot-apply (~1.2k lines)
│ │ │ ├── xray_setting.go # Raw Xray config persistence
│ │ │ ├── geodata.go # Geo database browsing + routing-token validation
│ │ │ ├── xray_metrics.go # Xray observability metrics
│ │ │ ├── metric_history.go # Historical system/xray metrics
│ │ │ ├── reality_scan.go # REALITY target scanner
@@ -197,7 +203,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ │ ├── port_conflict.go # Detect inbound port collisions
│ │ │ ├── fallback.go # Xray fallback (SNI/ALPN routing on shared port)
│ │ │ ├── email/ # Email notification service (SMTP)
│ │ │ ├── integration/ # External providers: warp.go (Cloudflare WARP), nord.go (NordVPN)
│ │ │ ├── integration/ # External providers: warp.go, nord.go, pia.go
│ │ │ ├── outbound/ # Outbound config service
│ │ │ ├── panel/ # Cross-cutting panel services:
│ │ │ │ ├── panel.go # panel-level helpers
@@ -265,7 +271,7 @@ node heartbeat every 5s, periodic traffic resets (hourly/daily/weekly/monthly).
│ │ └── queries/ # TanStack Query hooks (useNodesQuery, useStatusQuery, …)
│ ├── schemas/ # Zod schemas: protocols, forms, api, primitives
│ ├── generated/ # ⚠️ GENERATED from Go (see §5.5): schemas.ts, types.ts, zod.ts, examples.ts
│ ├── components/ # Reusable UI (clients/ form/ ui/ viz/ feedback/ utility/)
│ ├── components/ # Reusable UI (clients/ form/ geodata/ ui/ viz/ feedback/ utility/)
│ ├── lib/ # Frontend domain logic (xray/ inbounds/ clients/)
│ ├── hooks/, models/, layouts/, i18n/, utils/, styles/
│ └── test/ # Vitest + golden fixtures (config-generation snapshot tests)
@@ -309,8 +315,8 @@ Restart is debounced via an atomic "need restart" flag (`SetToNeedRestart` /
### 5.2 Runtime abstraction — Local vs Remote (multi-node) ⭐ most important
A "node" (`model.Node`) is another 3x-ui instance this panel controls. Every state-changing
inbound/client operation goes through the `runtime.Runtime` interface so the *same service
code* works whether the target is the local Xray or a remote node.
inbound/client operation goes through the `runtime.Runtime` interface so the _same service
code_ works whether the target is the local Xray or a remote node.
- **Interface:** `internal/web/runtime/runtime.go``Name`, `AddInbound`, `DelInbound`,
`UpdateInbound`, `AddUser`, `RemoveUser`, `UpdateUser`, `DeleteUser`, `AddClient`,
@@ -326,7 +332,7 @@ code* works whether the target is the local Xray or a remote node.
- **Dispatch:** `manager.go``Manager.RuntimeFor(nodeID *int)`; `nil` nodeID → `Local`,
otherwise a cached/lazy-loaded `Remote`. `InvalidateNode(id)` drops a cached remote client.
**Node identity & attribution (the hard part).** Inbounds carry a `NodeID` *and* an
**Node identity & attribution (the hard part).** Inbounds carry a `NodeID` _and_ an
`OriginNodeGuid`. Because inbounds can be pushed across hops, the panel attributes traffic and
online clients back to the originating panel using **stable GUIDs** rather than local IDs.
Relevant logic: `service/inbound_node.go` (`ReconcileNode`, `SetRemoteTraffic`, GUID merge,
@@ -335,6 +341,7 @@ tracking). Node "dirty" flags drive an **anti-entropy reconciliation** so an off
inbound edits converge once it reconnects.
**Where to look for node bugs:**
- Operation not reaching a node → `runtime/remote.go` + `runtime/manager.go`.
- Wrong traffic/online attribution across hops → `service/inbound_node.go` (GUID merge paths).
- Node shown offline / stale status → `job/node_heartbeat_job.go` + `service/node.go` (`Probe`, `UpdateHeartbeat`).
@@ -357,28 +364,28 @@ Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.Traffic
All registered in `web.go``startTask()`. Each is a struct with a `Run()` method in `internal/web/job/`:
| Schedule | Job | Purpose / condition |
|---|---|---|
| `@every 1s` | `check_xray_running_job` | Restart Xray if it died (2 consecutive down checks) |
| `@every 30s` | (inline func in `startTask`) | Debounced Xray restart — consumes the "need restart" flag (§5.1) |
| `@every 5s` | `xray_traffic_job` | Pull traffic stats from Xray (5s start delay) |
| `@every 5s` | `node_heartbeat_job` | Probe child nodes (online/offline) |
| `@every 5s` | `node_traffic_sync_job` | Pull + merge node traffic; push reconciliation |
| `@every 10s` | `check_client_ip_job` | Enforce per-client IP limits |
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets |
| `@weekly` | `periodic_traffic_reset_job("weekly")` | Weekly traffic resets |
| default `@every 1m` | `ldap_sync_job` | Only if LDAP enabled; schedule configurable |
| default `@daily` | `stats_notify_job` | Only if TG bot enabled; schedule configurable |
| `@every 2m` | `check_hash_storage` | Only if TG bot enabled; expires bot callback hashes |
| `@every 1m` | `check_cpu_usage` | Only if a CPU alarm is configured (TG or email); publishes `cpu.high` |
| `@every 1m` | `check_memory_usage` | Only if a memory alarm is configured; publishes `memory.high` |
| configurable | `free_os_memory` | Only if `sys.MemoryReleaseIntervalMinutes() > 0`; returns heap to OS |
| Schedule | Job | Purpose / condition |
| ------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `@every 1s` | `check_xray_running_job` | Restart Xray if it died (2 consecutive down checks) |
| `@every 30s` | (inline func in `startTask`) | Debounced Xray restart — consumes the "need restart" flag (§5.1) |
| `@every 5s` | `xray_traffic_job` | Pull traffic stats from Xray (5s start delay) |
| `@every 5s` | `node_heartbeat_job` | Probe child nodes (online/offline) |
| `@every 5s` | `node_traffic_sync_job` | Pull + merge node traffic; push reconciliation |
| `@every 10s` | `check_client_ip_job` | Enforce per-client IP limits |
| `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds |
| `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs |
| `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB |
| `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets |
| `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets |
| `@weekly` | `periodic_traffic_reset_job("weekly")` | Weekly traffic resets |
| default `@every 1m` | `ldap_sync_job` | Only if LDAP enabled; schedule configurable |
| default `@daily` | `stats_notify_job` | Only if TG bot enabled; schedule configurable |
| `@every 2m` | `check_hash_storage` | Only if TG bot enabled; expires bot callback hashes |
| `@every 1m` | `check_cpu_usage` | Only if a CPU alarm is configured (TG or email); publishes `cpu.high` |
| `@every 1m` | `check_memory_usage` | Only if a memory alarm is configured; publishes `memory.high` |
| configurable | `free_os_memory` | Only if `sys.MemoryReleaseIntervalMinutes() > 0`; returns heap to OS |
To change *when* something runs, edit `startTask()`. To change *what* it does, edit the job file.
To change _when_ something runs, edit `startTask()`. To change _what_ it does, edit the job file.
### 5.5 Type generation (Go → TypeScript) ⚠️ don't hand-edit generated files
@@ -397,8 +404,9 @@ frontend types (`cd frontend && npm run gen`) instead of editing `src/generated/
### 5.6 Share-link / subscription generation
Two distinct code paths produce client configs:
- **Per-client links in the panel** (the "copy link" / QR in the UI): `service/client_link.go`
+ `util/link/outbound.go`.
- `util/link/outbound.go`.
- **Subscription endpoint** (what a client app polls): `internal/sub/service.go` (raw links),
`internal/sub/json_service.go` (JSON), `internal/sub/clash_service.go` (Clash YAML).
**`Host` rows** (`model.Host`, edited under /panel/api/hosts) override address/SNI/path/
@@ -435,68 +443,70 @@ Xray restart.
GORM models in `internal/database/model/` (main file `model.go` + siblings); all registered
for AutoMigrate in `internal/database/db.go`.
| Model | Table role | Notable fields |
|---|---|---|
| `User` | Admin login | bcrypt password, `LoginEpoch` (invalidates sessions) |
| `Inbound` | An Xray inbound | `Tag` (unique), `Port`, `Protocol`, `Settings`/`StreamSettings`/`Sniffing` (JSON), `Enable`, `TrafficReset`, `NodeID`, **`OriginNodeGuid`**, `ClientStats` (assoc) |
| `Client` | In-memory client view | UUID/email/flow/limits (parsed from inbound JSON; not persisted) |
| `ClientRecord` | Persisted client (`clients`) | `Email` (unique), `SubID`, `UUID`, `TotalGB`, `ExpiryTime`, `LimitIP`, `Group`, `Reset` |
| `ClientGroup` / `ClientInbound` | Grouping + client↔inbound join | many-to-many wiring, `FlowOverride` |
| `ClientExternalLink` | Extra links attached to a client | `Kind`, `Value`, `Remark`, `SortIndex` |
| `Host` | Subscription host overrides (per inbound) | `Address`, `Port`, `Sni`, `Path`, `Security`, `Fingerprint`, `SortOrder`, visibility/exclusion flags |
| `Node` | A managed child panel | `Guid`, `Address`, `Status`, `TlsVerifyMode`, `PinnedCertSha256`, `ConfigDirty`, version/heartbeat/metric fields |
| `NodeClientTraffic` | Per-node client traffic baseline | cross-node merge (anti-double-count) |
| `NodeClientIp` | Per-node client IP attribution | `NodeGuid`, `Email`, `Ips` |
| `ClientGlobalTraffic` | Cross-master usage totals | `MasterGuid`, `Email`, `Up`, `Down` |
| `xray.ClientTraffic` | Per-client counters (`client_traffics`) | `Email`, `Up`, `Down`, `Total`, `ExpiryTime`, `LastOnline` |
| `InboundClientIps` | IP set per client email | drives IP-limit enforcement |
| `OutboundTraffics` | Outbound counters | per outbound tag |
| `OutboundSubscription` | External provider subs | Warp/Nord style |
| `Setting` | Key/value panel settings | everything configurable |
| `ApiToken` | REST API tokens | SHA-256 hash (plaintext shown once) |
| `InboundFallback` | Fallback routing on a shared port | SNI/ALPN/path → dest |
| `HistoryOfSeeders` | Seeder bookkeeping | prevents re-running one-off migrations |
| Model | Table role | Notable fields |
| ------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `User` | Admin login | bcrypt password, `LoginEpoch` (invalidates sessions) |
| `Inbound` | An Xray inbound | `Tag` (unique), `Port`, `Protocol`, `Settings`/`StreamSettings`/`Sniffing` (JSON), `Enable`, `TrafficReset`, `NodeID`, **`OriginNodeGuid`**, `ClientStats` (assoc) |
| `Client` | In-memory client view | UUID/email/flow/limits (parsed from inbound JSON; not persisted) |
| `ClientRecord` | Persisted client (`clients`) | `Email` (unique), `SubID`, `UUID`, `TotalGB`, `ExpiryTime`, `LimitIP`, `Group`, `Reset` |
| `ClientGroup` / `ClientInbound` | Grouping + client↔inbound join | many-to-many wiring, `FlowOverride` |
| `ClientExternalLink` | Extra links attached to a client | `Kind`, `Value`, `Remark`, `SortIndex` |
| `Host` | Subscription host overrides (per inbound) | `Address`, `Port`, `Sni`, `Path`, `Security`, `Fingerprint`, `SortOrder`, visibility/exclusion flags |
| `Node` | A managed child panel | `Guid`, `Address`, `Status`, `TlsVerifyMode`, `PinnedCertSha256`, `ConfigDirty`, version/heartbeat/metric fields |
| `NodeClientTraffic` | Per-node client traffic baseline | cross-node merge (anti-double-count) |
| `NodeClientIp` | Per-node client IP attribution | `NodeGuid`, `Email`, `Ips` |
| `ClientGlobalTraffic` | Cross-master usage totals | `MasterGuid`, `Email`, `Up`, `Down` |
| `xray.ClientTraffic` | Per-client counters (`client_traffics`) | `Email`, `Up`, `Down`, `Total`, `ExpiryTime`, `LastOnline` |
| `InboundClientIps` | IP set per client email | drives IP-limit enforcement |
| `OutboundTraffics` | Outbound counters | per outbound tag |
| `OutboundSubscription` | External provider subs | Warp/Nord style |
| `Setting` | Key/value panel settings | everything configurable |
| `ApiToken` | REST API tokens | SHA-256 hash (plaintext shown once) |
| `InboundFallback` | Fallback routing on a shared port | SNI/ALPN/path → dest |
| `HistoryOfSeeders` | Seeder bookkeeping | prevents re-running one-off migrations |
---
## 7. Symptom → File index (start here when debugging)
| Symptom / task | Primary file(s) | Then check |
|---|---|---|
| Add/modify an **API endpoint** | `controller/<resource>.go` (route registration at top of each file) | corresponding `service/*.go`, `frontend/src/pages/api-docs/endpoints.ts` |
| **Inbound** create/update/delete behavior | `service/inbound.go`, `service/inbound_clients.go` | `runtime/*`, `service/xray.go` |
| **Client** CRUD / limits / expiry | `service/client_crud.go`, `service/client_inbound_apply.go` | model `ClientRecord`, `service/inbound_traffic.go` |
| **Bulk** client operations slow/wrong | `service/client_bulk.go` | `service/client_paging.go` |
| Xray **won't apply** a config change | `service/xray.go` (`RestartXray`, `tryHotApply`) | `xray/hot_diff.go`, `xray/process.go` |
| Xray **restarts when it shouldn't** (kills connections) | `xray/hot_diff.go` (diff not classified as hot) | `service/xray.go` |
| **Traffic** counts wrong / reset behavior | `service/inbound_traffic.go`, `job/xray_traffic_job.go` | `service/traffic_writer.go`, `job/periodic_traffic_reset_job.go` |
| **Node** operation not propagating | `runtime/remote.go`, `runtime/manager.go` | `service/inbound_node.go` |
| **Multi-hop / cross-node attribution** (traffic or online clients on wrong panel) | `service/inbound_node.go` (GUID merge, `synthNodeGuid`, `effectiveNodeGuid`) | `service/node.go`, model `OriginNodeGuid`/`Node.Guid` |
| Node stuck **offline / stale** | `job/node_heartbeat_job.go`, `service/node.go` (`Probe`, `UpdateHeartbeat`) | `runtime/tls_client.go` (TLS verify) |
| Node **TLS / mTLS** auth failures | `runtime/tls_client.go`, `service/node_mtls.go`, `service/setting_mtls.go` | `service/node.go` (`FetchCertFingerprint`) |
| Offline node edits **not reconciling** on reconnect | `service/inbound_node.go` (`ReconcileNode`, dirty flags) | `service/node.go` (`MarkNodeDirty`/`NodeSyncState`) |
| **Share link / QR** malformed (per protocol) | `service/client_link.go`, `util/link/outbound.go` | `frontend/src/lib/xray/`, `frontend/src/schemas/protocols/` |
| **Subscription** output wrong (raw/JSON/Clash) | `internal/sub/service.go` | `sub/json_service.go`, `sub/clash_service.go`, sub golden tests |
| Subscription **host overrides** not applied | `service/host.go`, `sub/host_sub.go` | model `Host`, `frontend/src/pages/hosts/` |
| **External subscription** import/aggregation | `sub/external_subscription.go`, `sub/external_config.go` | `sub/clash_external.go` |
| **Settings** not saving / defaults | `service/setting.go`, `controller/setting.go` | model `Setting` |
| **Login / 2FA / sessions / CSRF** | `controller/index.go`, `service/panel/user.go`, `middleware/` | `session/` |
| **API tokens** | `service/panel/api_token.go`, `controller/setting.go` | model `ApiToken` |
| **Port conflict** on inbound add | `service/port_conflict.go` | `controller/inbound.go` |
| **Fallbacks** (shared 443, SNI routing) | `service/fallback.go`, `controller/inbound.go` | model `InboundFallback` |
| **Telegram bot** commands | `service/tgbot/` | `job/stats_notify_job.go` |
| **Email notifications** | `service/email/` | `internal/eventbus/` (consumers) |
| **CPU / memory alerts** not firing | `job/check_cpu_usage.go`, `job/check_memory_usage.go` | `internal/eventbus/`, notifier settings in `service/setting.go` |
| Xray auto-restart on **dead tunnel** | `internal/tunnelmonitor/` | `XUI_TUNNEL_HEALTH_*` in `internal/config/` |
| **WARP / Nord** outbound integration | `service/integration/warp.go` / `nord.go` | `service/outbound_subscription.go` |
| **MTProto** proxy issues | `internal/mtproto/manager.go`, `mtproto/process*.go` | `job/mtproto_job.go` |
| **DB migration** / new column | `internal/database/db.go` (AutoMigrate list), `migrate_data.go` | `model/model.go` |
| **Cron schedule** changes | `web.go` `startTask()` | the specific `job/*.go` |
| **CORS / security headers / HTTPS** | `middleware/`, `web.go` (`initRouter`, TLS setup) | `config/` (env) |
| **Env vars / paths / DB type** | `internal/config/config.go` | `.env.example` |
| **Frontend route / screen** | `frontend/src/pages/<area>/`, `frontend/src/routes.tsx` | `frontend/src/api/queries/` |
| **Frontend ↔ backend type mismatch** | regenerate: `cd frontend && npm run gen` (`tools/openapigen`) | `frontend/src/generated/` |
| **System status / CPU / metrics** | `service/server.go`, `service/xray_metrics.go`, `service/metric_history.go` | `controller/server.go`, gopsutil |
| Symptom / task | Primary file(s) | Then check |
| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Add/modify an **API endpoint** | `controller/<resource>.go` (route registration at top of each file) | corresponding `service/*.go`, `frontend/src/pages/api-docs/endpoints.ts` |
| **Inbound** create/update/delete behavior | `service/inbound.go`, `service/inbound_clients.go` | `runtime/*`, `service/xray.go` |
| **Client** CRUD / limits / expiry | `service/client_crud.go`, `service/client_inbound_apply.go` | model `ClientRecord`, `service/inbound_traffic.go` |
| **Bulk** client operations slow/wrong | `service/client_bulk.go` | `service/client_paging.go` |
| Xray **won't apply** a config change | `service/xray.go` (`RestartXray`, `tryHotApply`) | `xray/hot_diff.go`, `xray/process.go` |
| Xray **restarts when it shouldn't** (kills connections) | `xray/hot_diff.go` (diff not classified as hot) | `service/xray.go` |
| **Traffic** counts wrong / reset behavior | `service/inbound_traffic.go`, `job/xray_traffic_job.go` | `service/traffic_writer.go`, `job/periodic_traffic_reset_job.go` |
| **Node** operation not propagating | `runtime/remote.go`, `runtime/manager.go` | `service/inbound_node.go` |
| **Multi-hop / cross-node attribution** (traffic or online clients on wrong panel) | `service/inbound_node.go` (GUID merge, `synthNodeGuid`, `effectiveNodeGuid`) | `service/node.go`, model `OriginNodeGuid`/`Node.Guid` |
| Node stuck **offline / stale** | `job/node_heartbeat_job.go`, `service/node.go` (`Probe`, `UpdateHeartbeat`) | `runtime/tls_client.go` (TLS verify) |
| Node **TLS / mTLS** auth failures | `runtime/tls_client.go`, `service/node_mtls.go`, `service/setting_mtls.go` | `service/node.go` (`FetchCertFingerprint`) |
| Offline node edits **not reconciling** on reconnect | `service/inbound_node.go` (`ReconcileNode`, dirty flags) | `service/node.go` (`MarkNodeDirty`/`NodeSyncState`) |
| **Share link / QR** malformed (per protocol) | `service/client_link.go`, `util/link/outbound.go` | `frontend/src/lib/xray/`, `frontend/src/schemas/protocols/` |
| **Subscription** output wrong (raw/JSON/Clash) | `internal/sub/service.go` | `sub/json_service.go`, `sub/clash_service.go`, sub golden tests |
| Subscription **host overrides** not applied | `service/host.go`, `sub/host_sub.go` | model `Host`, `frontend/src/pages/hosts/` |
| **External subscription** import/aggregation | `sub/external_subscription.go`, `sub/external_config.go` | `sub/clash_external.go` |
| **Settings** not saving / defaults | `service/setting.go`, `controller/setting.go` | model `Setting` |
| **Login / 2FA / sessions / CSRF** | `controller/index.go`, `service/panel/user.go`, `middleware/` | `session/` |
| **API tokens** | `service/panel/api_token.go`, `controller/setting.go` | model `ApiToken` |
| **Port conflict** on inbound add | `service/port_conflict.go` | `controller/inbound.go` |
| **Fallbacks** (shared 443, SNI routing) | `service/fallback.go`, `controller/inbound.go` | model `InboundFallback` |
| **Geo category browser** empty / won't open | `xray/geodata/` (`Store`, `reader.go`), `service/geodata.go` | `controller/xray_setting.go` (`/panel/api/xray/geodata/*`), asset dir = `config.GetBinFolderPath()` |
| **`geosite:`/`geoip:` token** reported unknown in a routing rule | `xray/geodata/token.go`, `service/geodata.go` (`Validate`) | `frontend/src/lib/xray/geoTokens.ts`, `frontend/src/components/geodata/` |
| **Telegram bot** commands | `service/tgbot/` | `job/stats_notify_job.go` |
| **Email notifications** | `service/email/` | `internal/eventbus/` (consumers) |
| **CPU / memory alerts** not firing | `job/check_cpu_usage.go`, `job/check_memory_usage.go` | `internal/eventbus/`, notifier settings in `service/setting.go` |
| Xray auto-restart on **dead tunnel** | `internal/tunnelmonitor/` | `XUI_TUNNEL_HEALTH_*` in `internal/config/` |
| **WARP / Nord / PIA** outbound integration | `service/integration/warp.go` / `nord.go` / `pia.go` | `internal/pia/`, `frontend/src/pages/xray/overrides/` |
| **MTProto** proxy issues | `internal/mtproto/manager.go`, `mtproto/process*.go` | `job/mtproto_job.go` |
| **DB migration** / new column | `internal/database/db.go` (AutoMigrate list), `migrate_data.go` | `model/model.go` |
| **Cron schedule** changes | `web.go``startTask()` | the specific `job/*.go` |
| **CORS / security headers / HTTPS** | `middleware/`, `web.go` (`initRouter`, TLS setup) | `config/` (env) |
| **Env vars / paths / DB type** | `internal/config/config.go` | `.env.example` |
| **Frontend route / screen** | `frontend/src/pages/<area>/`, `frontend/src/routes.tsx` | `frontend/src/api/queries/` |
| **Frontend ↔ backend type mismatch** | regenerate: `cd frontend && npm run gen` (`tools/openapigen`) | `frontend/src/generated/` |
| **System status / CPU / metrics** | `service/server.go`, `service/xray_metrics.go`, `service/metric_history.go` | `controller/server.go`, gopsutil |
---
@@ -517,7 +527,7 @@ for AutoMigrate in `internal/database/db.go`.
Regenerate instead.
7. **Models are the contract.** Changing a model field that crosses the API boundary means:
update `model.go` → handle migration in `db.go`/`migrate_data.go` → regenerate frontend types.
8. **Two servers, two concerns.** Admin features go in `internal/web`; anything an *end user*
8. **Two servers, two concerns.** Admin features go in `internal/web`; anything an _end user_
fetches goes in `internal/sub`. Don't blur them.
9. **Cross-cutting notifications go through `internal/eventbus/`** — publish an event instead
of importing the Telegram/email services into producers.
@@ -531,6 +541,7 @@ The canonical gate is the **Makefile** (mirrors CI): `make verify`. Also: `make
frontend), `make race`, `make build`. Run `make help` for everything. Raw commands:
**Backend (Go):**
```bash
go build ./... # compile everything
go test ./... # run all Go tests (many *_test.go alongside sources)
@@ -542,12 +553,13 @@ golangci-lint run # full lint (gofumpt + goimports formatting)
go run main.go # run the panel locally (serves embedded dist if built)
```
**Frontend (`cd frontend`, Node ≥ 22):**
**Frontend (`cd frontend`, Node 24 — see `.nvmrc`):**
```bash
npm install
npm run dev # Vite dev server on :5173; proxies API to Go backend on :2053 (run `go run main.go` too)
npm run typecheck # tsc --noEmit
npm run lint # eslint src
npm run lint # oxlint src
npm run test # vitest (incl. golden config-generation snapshots)
npm run gen # regenerate src/generated/* from Go (gen:zod + gen:api)
npm run build # gen:api + vite build → outputs to internal/web/dist (then rebuild Go binary to embed)
+6 -10
View File
@@ -1,8 +1,8 @@
'use client';
import { create } from '@orama/orama';
import { create } from 'zbsearch';
import { useDocsSearch } from 'fumadocs-core/search/client';
import { oramaStaticClient } from 'fumadocs-core/search/client/orama-static';
import { staticClient } from 'fumadocs-core/search/client/orama-static';
import {
SearchDialog,
SearchDialogClose,
@@ -21,20 +21,16 @@ interface SharedProps {
onOpenChange: (open: boolean) => void;
}
// The static search index is keyed by locale code (en/fa/ru/zh). Fumadocs'
// default static dialog feeds those codes to Orama as a tokenizer language, but
// Orama only accepts full names ("english") and throws on "en" — which silently
// breaks search entirely. All docs content is English (other locales fall back
// to it), so re-create the dialog — the documented escape hatch for custom Orama
// setups — with an initOrama that always builds an English index.
// Fumadocs' default dialog passes the index's locale code as a tokenizer language,
// and zbsearch throws on anything but a full name — so force "english" everywhere.
export default function SearchDialogClient(props: SharedProps) {
const { locale } = useI18n();
const client = useMemo(
() =>
oramaStaticClient({
staticClient({
from: '/api/search',
locale,
initOrama: () => create({ schema: { _: 'string' }, language: 'english' }),
initDB: () => create({ schema: { _: 'string' }, language: 'english' }),
}),
[locale],
);
+104
View File
@@ -0,0 +1,104 @@
'use client';
import { Moon, Sun } from 'lucide-react';
import { useEffect, useState, useSyncExternalStore } from 'react';
import type { ComponentProps } from 'react';
import { cn } from '@/lib/cn';
type ThemeMode = 'light-dark' | 'light-dark-system';
type ThemePref = 'light' | 'dark' | 'system';
const STORAGE_KEY = 'docs-theme';
// `useSyncExternalStore` supplies the same value for SSR and hydration, then
// switches to the browser value after React has attached to the markup.
const subscribeToHydration = () => () => {};
const getHydrationClientSnapshot = () => true;
const getHydrationServerSnapshot = () => false;
function getStoredTheme(): ThemePref {
if (typeof window === 'undefined') return 'system';
const raw = window.localStorage.getItem(STORAGE_KEY);
return raw === 'light' || raw === 'dark' || raw === 'system' ? raw : 'system';
}
function getResolvedTheme(theme: ThemePref): 'light' | 'dark' {
if (theme !== 'system') return theme;
if (typeof window === 'undefined') return 'light';
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(theme: ThemePref): void {
if (typeof document === 'undefined') return;
const resolved = getResolvedTheme(theme);
const root = document.documentElement;
root.classList.toggle('dark', resolved === 'dark');
root.style.colorScheme = resolved;
}
export function DocsThemeSwitch({
className,
mode = 'light-dark-system',
...props
}: {
className?: string;
mode?: ThemeMode;
} & Omit<ComponentProps<'div'>, 'children'>) {
// Keep the server and first client render identical. Reading localStorage or
// matchMedia here would make a persisted/system preference change the client
// markup before React has finished hydrating it.
const [selectedTheme, setSelectedTheme] = useState<ThemePref>('system');
const hydrated = useSyncExternalStore(
subscribeToHydration,
getHydrationClientSnapshot,
getHydrationServerSnapshot,
);
const theme = hydrated ? getStoredTheme() : selectedTheme;
useEffect(() => {
if (hydrated) applyTheme(theme);
}, [hydrated, theme]);
useEffect(() => {
if (!hydrated) return;
if (theme !== 'system') return;
const media = window.matchMedia('(prefers-color-scheme: dark)');
const update = () => applyTheme('system');
media.addEventListener('change', update);
return () => media.removeEventListener('change', update);
}, [hydrated, theme]);
const resolved = hydrated ? getResolvedTheme(theme) : 'light';
const setTheme = (nextTheme: ThemePref) => {
window.localStorage.setItem(STORAGE_KEY, nextTheme);
applyTheme(nextTheme);
setSelectedTheme(nextTheme);
};
const nextTheme = () => {
if (mode === 'light-dark') return resolved === 'dark' ? 'light' : 'dark';
if (theme === 'light') return 'dark';
if (theme === 'dark') return 'system';
return resolved === 'dark' ? 'light' : 'dark';
};
const label =
mode === 'light-dark-system'
? `Switch theme (current: ${theme})`
: `Switch to ${resolved === 'dark' ? 'light' : 'dark'} mode`;
return (
<div className={cn('inline-flex', className)} {...props}>
<button
type="button"
aria-label={label}
title={label}
onClick={() => setTheme(nextTheme())}
className="inline-flex size-8 items-center justify-center rounded-lg text-fd-muted-foreground transition-colors hover:bg-fd-accent hover:text-fd-accent-foreground"
>
{resolved === 'dark' ? <Moon className="size-4" /> : <Sun className="size-4" />}
</button>
</div>
);
}
@@ -1,7 +1,12 @@
'use client';
import { useId, useState } from 'react';
import { buildCurl, buildFetchSnippet, type ApiRequestInput, type HttpMethod } from '@/lib/xray/api-client';
import {
buildCurl,
buildFetchSnippet,
type ApiRequestInput,
type HttpMethod,
} from '@/lib/xray/api-client';
import { ToolFrame } from './tool-frame';
import { TextField, SelectField } from './shared/fields';
import { OutputBlock } from './shared/output-block';
+72 -11
View File
@@ -38,8 +38,24 @@ const DEFAULT_BALANCERS: BalancerRow[] = [
{ tag: 'balancer', selector: 'proxy', strategy: 'leastPing', fallbackTag: '' },
];
const DEFAULT_RULES: RuleRow[] = [
{ domain: 'geosite:category-ads-all', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'block' },
{ domain: '', ip: 'geoip:private', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: 'direct' },
{
domain: 'geosite:category-ads-all',
ip: '',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: 'block',
},
{
domain: '',
ip: 'geoip:private',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: 'direct',
},
];
function list(s: string): string[] {
@@ -113,7 +129,10 @@ export function RoutingBuilder() {
type="button"
className={addBtn}
onClick={() =>
setBalancers((p) => [...p, { tag: '', selector: '', strategy: 'random', fallbackTag: '' }])
setBalancers((p) => [
...p,
{ tag: '', selector: '', strategy: 'random', fallbackTag: '' },
])
}
>
Add balancer
@@ -163,7 +182,15 @@ export function RoutingBuilder() {
onClick={() =>
setRules((p) => [
...p,
{ domain: '', ip: '', port: '', network: 'any', inboundTag: '', targetKind: 'outbound', targetTag: '' },
{
domain: '',
ip: '',
port: '',
network: 'any',
inboundTag: '',
targetKind: 'outbound',
targetTag: '',
},
])
}
>
@@ -174,13 +201,47 @@ export function RoutingBuilder() {
{rules.map((r, i) => (
<div key={i} className="rounded-xl border p-3">
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<TextField label="Domain (comma)" value={r.domain} onChange={(v) => patchRule(i, { domain: v })} placeholder="geosite:google, example.com" />
<TextField label="IP (comma)" value={r.ip} onChange={(v) => patchRule(i, { ip: v })} placeholder="geoip:cn, 1.1.1.1" />
<TextField label="Port" value={r.port} onChange={(v) => patchRule(i, { port: v })} placeholder="443 or 1000-2000" />
<SelectField label="Network" value={r.network} onChange={(v) => patchRule(i, { network: v })} options={NETWORKS} />
<TextField label="Inbound tag (comma)" value={r.inboundTag} onChange={(v) => patchRule(i, { inboundTag: v })} placeholder="optional" />
<SelectField label="Target kind" value={r.targetKind} onChange={(v) => patchRule(i, { targetKind: v as 'outbound' | 'balancer' })} options={TARGET_KINDS} />
<TextField label="Target tag" value={r.targetTag} onChange={(v) => patchRule(i, { targetTag: v })} />
<TextField
label="Domain (comma)"
value={r.domain}
onChange={(v) => patchRule(i, { domain: v })}
placeholder="geosite:google, example.com"
/>
<TextField
label="IP (comma)"
value={r.ip}
onChange={(v) => patchRule(i, { ip: v })}
placeholder="geoip:cn, 1.1.1.1"
/>
<TextField
label="Port"
value={r.port}
onChange={(v) => patchRule(i, { port: v })}
placeholder="443 or 1000-2000"
/>
<SelectField
label="Network"
value={r.network}
onChange={(v) => patchRule(i, { network: v })}
options={NETWORKS}
/>
<TextField
label="Inbound tag (comma)"
value={r.inboundTag}
onChange={(v) => patchRule(i, { inboundTag: v })}
placeholder="optional"
/>
<SelectField
label="Target kind"
value={r.targetKind}
onChange={(v) => patchRule(i, { targetKind: v as 'outbound' | 'balancer' })}
options={TARGET_KINDS}
/>
<TextField
label="Target tag"
value={r.targetTag}
onChange={(v) => patchRule(i, { targetTag: v })}
/>
</div>
<div className="mt-2 flex justify-end">
<button
+38 -7
View File
@@ -79,7 +79,15 @@ export function SubscriptionBuilder() {
setClients((prev) => prev.map((c, j) => (i === j ? { ...c, ...p } : c)));
}
const urlInput: SubUrlInput = { scheme, host, port: Number(port), subPath, jsonPath, subId, behindProxy };
const urlInput: SubUrlInput = {
scheme,
host,
port: Number(port),
subPath,
jsonPath,
subId,
behindProxy,
};
const urls = buildSubscriptionUrls(urlInput);
const subClients = clients.filter((c) => c.address.trim()).map(toClient);
@@ -159,16 +167,33 @@ export function SubscriptionBuilder() {
onChange={(v) => patch(i, { protocol: v as ClientProtocol })}
options={PROTOCOLS}
/>
<TextField label="Remark" value={c.remark} onChange={(v) => patch(i, { remark: v })} />
<TextField label="Address" value={c.address} onChange={(v) => patch(i, { address: v })} />
<TextField label="Port" value={c.port} onChange={(v) => patch(i, { port: v })} inputMode="numeric" />
<TextField
label="Remark"
value={c.remark}
onChange={(v) => patch(i, { remark: v })}
/>
<TextField
label="Address"
value={c.address}
onChange={(v) => patch(i, { address: v })}
/>
<TextField
label="Port"
value={c.port}
onChange={(v) => patch(i, { port: v })}
inputMode="numeric"
/>
<TextField
label={c.protocol === 'vless' || c.protocol === 'vmess' ? 'UUID (id)' : 'Password'}
value={c.credential}
onChange={(v) => patch(i, { credential: v })}
/>
{c.protocol === 'ss' ? (
<TextField label="Method" value={c.method} onChange={(v) => patch(i, { method: v })} />
<TextField
label="Method"
value={c.method}
onChange={(v) => patch(i, { method: v })}
/>
) : null}
<SelectField
label="Transport"
@@ -200,9 +225,15 @@ export function SubscriptionBuilder() {
</div>
<div className="mt-4 grid grid-cols-1 gap-4">
<OutputBlock label="Subscription links (decoded body)" value={buildShareLinks(subClients).join('\n')} />
<OutputBlock
label="Subscription links (decoded body)"
value={buildShareLinks(subClients).join('\n')}
/>
<OutputBlock label="Base64 body" value={buildBase64Subscription(subClients)} />
<OutputBlock label="JSON subscription (preview)" value={buildJsonSubscription(subClients)} />
<OutputBlock
label="JSON subscription (preview)"
value={buildJsonSubscription(subClients)}
/>
</div>
</ToolFrame>
);
@@ -1,13 +1,13 @@
---
title: Outbounds & Routing
description: Shape egress in 3x-ui — WARP and NordVPN outbounds, outbound subscriptions (server pools), routing rules, and load balancers.
description: Shape egress in 3x-ui — WARP, NordVPN, PIA WireGuard, outbound subscriptions, routing rules, and load balancers.
icon: Route
---
Inbounds accept clients; **outbounds** decide where their traffic goes next.
3x-ui can route traffic through Cloudflare WARP, NordVPN, or arbitrary outbound
pools imported from a subscription, and select between them with routing rules
and balancers.
3x-ui can route traffic through Cloudflare WARP, NordVPN, Private Internet Access
(WireGuard), or arbitrary outbound pools imported from a subscription,
and select between them with routing rules and balancers.
## Editing outbounds & routing
@@ -86,6 +86,23 @@ with a routing rule.
accept a private key directly) and list countries/servers, so you can build a
NordVPN outbound.
## PIA WireGuard
3x-ui can sign in with a PIA username and password, list countries/regions/servers
from the signed PIA server list, and build a WireGuard outbound. Open
**Xray → Outbounds → More → PIA**, sign in, pick a server, and add the outbound.
You can add several servers (one outbound per hostname). The tag is
`pia-<region>-<server>` (for example `pia-us-east-useast1`). Adding or using
**Reset** on a row registers a WireGuard key with PIA `/addKey` for that server.
The same hostname cannot be added twice. Logout clears the stored token only;
delete unused PIA outbounds from the Outbounds list. Reset and delete do not
revoke the WireGuard peer on the PIA account.
The password is not stored. The PIA API token is stored with the same
`NODE_TOKEN_ENCRYPTION` setting as node API tokens. If you retire an old
`XUI_NODE_TOKEN_KEY` without signing into PIA again, Add/Reset fail until you
re-login. Peer `allowedIPs` is IPv4-only (`0.0.0.0/0`).
## Outbound subscriptions (server pools)
An **outbound subscription** imports a remote share-link subscription and injects
@@ -1,66 +1,47 @@
---
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 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.'
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every API token, enabled or not. The token value is never returned
only metadata.
url: >-
#list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
title: List every API token, enabled or not. The token value is never returned —
only metadata.
url: '#list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata'
- depth: 2
title: >-
Mint a new API token. Name must be unique and 1-64 characters; the token
string is server-generated and returned only in this response — it is
stored hashed and cannot be retrieved later.
url: >-
#mint-a-new-api-token-name-must-be-unique-and-1-64-characters-the-token-string-is-server-generated-and-returned-only-in-this-response--it-is-stored-hashed-and-cannot-be-retrieved-later
title: Mint a scoped API token. The server-generated plaintext is returned only
once and stored as a hash.
url: '#mint-a-scoped-api-token-the-server-generated-plaintext-is-returned-only-once-and-stored-as-a-hash'
- depth: 2
title: >-
Permanently delete a token. Any caller using it stops authenticating
title: Permanently delete a token. Any caller using it stops authenticating
immediately.
url: >-
#permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
url: '#permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately'
- depth: 2
title: >-
Toggle a token enabled/disabled without deleting it. Disabled tokens are
title: Toggle a token enabled/disabled without deleting it. Disabled tokens are
rejected by checkAPIAuth on the next request.
url: >-
#toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
url: '#toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request'
structuredData:
headings:
- content: >-
List every API token, enabled or not. The token value is never
returnedonly metadata.
id: >-
list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
- content: >-
Mint a new API token. Name must be unique and 1-64 characters; the
token string is server-generated and returned only in this response —
it is stored hashed and cannot be retrieved later.
id: >-
mint-a-new-api-token-name-must-be-unique-and-1-64-characters-the-token-string-is-server-generated-and-returned-only-in-this-response--it-is-stored-hashed-and-cannot-be-retrieved-later
- content: >-
Permanently delete a token. Any caller using it stops authenticating
- content: List every API token, enabled or not. The token value is never returned
— only metadata.
id: list-every-api-token-enabled-or-not-the-token-value-is-never-returned--only-metadata
- content: Mint a scoped API token. The server-generated plaintext is returned
only once and stored as a hash.
id: mint-a-scoped-api-token-the-server-generated-plaintext-is-returned-only-once-and-stored-as-a-hash
- content: Permanently delete a token. Any caller using it stops authenticating
immediately.
id: >-
permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
- content: >-
Toggle a token enabled/disabled without deleting it. Disabled tokens
id: permanently-delete-a-token-any-caller-using-it-stops-authenticating-immediately
- content: Toggle a token enabled/disabled without deleting it. Disabled tokens
are rejected by checkAPIAuth on the next request.
id: >-
toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
id: toggle-a-token-enableddisabled-without-deleting-it-disabled-tokens-are-rejected-by-checkapiauth-on-the-next-request
contents: []
---
@@ -1,8 +1,7 @@
---
title: Authentication
description: >-
Two authentication modes are supported. UI sessions use a cookie set by the
login endpoint. Programmatic clients (bots, scripts, remote panels)
description: Two authentication modes are supported. UI sessions use a cookie
set by the login endpoint. Programmatic clients (bots, scripts, remote panels)
authenticate with a Bearer token taken from Settings → Security → API Token.
Both work for every endpoint under /panel/api/*.
full: true
@@ -11,51 +10,38 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Authenticate with username + password and receive a session cookie.
title: Authenticate with username + password and receive a session cookie.
Required before any cookie-based API call.
url: >-
#authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
url: '#authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call'
- depth: 2
title: Clear the session cookie. Requires the CSRF header for browser sessions.
url: '#clear-the-session-cookie-requires-the-csrf-header-for-browser-sessions'
- depth: 2
title: >-
Mint a CSRF token for the current session. The SPA replays it in the
title: Mint a CSRF token for the current session. The SPA replays it in the
X-CSRF-Token header on unsafe requests. Bearer-token callers can skip
this — the middleware short-circuits CSRF for authenticated API
requests.
url: >-
#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
url: '#mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests'
- depth: 2
title: >-
Returns whether 2FA is enabled on the panel — used by the login page to
title: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field.
url: >-
#returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
url: '#returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field'
structuredData:
headings:
- content: >-
Authenticate with username + password and receive a session cookie.
- content: Authenticate with username + password and receive a session cookie.
Required before any cookie-based API call.
id: >-
authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
- content: >-
Clear the session cookie. Requires the CSRF header for browser
id: authenticate-with-username--password-and-receive-a-session-cookie-required-before-any-cookie-based-api-call
- content: Clear the session cookie. Requires the CSRF header for browser
sessions.
id: clear-the-session-cookie-requires-the-csrf-header-for-browser-sessions
- content: >-
Mint a CSRF token for the current session. The SPA replays it in the
- content: Mint a CSRF token for the current session. The SPA replays it in the
X-CSRF-Token header on unsafe requests. Bearer-token callers can skip
this — the middleware short-circuits CSRF for authenticated API
requests.
id: >-
mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
- content: >-
Returns whether 2FA is enabled on the panelused by the login page
to decide whether to show the OTP field.
id: >-
returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
id: mint-a-csrf-token-for-the-current-session-the-spa-replays-it-in-the-x-csrf-token-header-on-unsafe-requests-bearer-token-callers-can-skip-this--the-middleware-short-circuits-csrf-for-authenticated-api-requests
- content: Returns whether 2FA is enabled on the panel — used by the login page to
decide whether to show the OTP field.
id: returns-whether-2fa-is-enabled-on-the-panel--used-by-the-login-page-to-decide-whether-to-show-the-otp-field
contents: []
---
@@ -7,18 +7,14 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Send a fresh DB backup to every Telegram chat configured as an admin
title: Send a fresh DB backup to every Telegram chat configured as an admin
recipient. No body, no params.
url: >-
#send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
url: '#send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params'
structuredData:
headings:
- content: >-
Send a fresh DB backup to every Telegram chat configured as an admin
- content: Send a fresh DB backup to every Telegram chat configured as an admin
recipient. No body, no params.
id: >-
send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
id: send-a-fresh-db-backup-to-every-telegram-chat-configured-as-an-admin-recipient-no-body-no-params
contents: []
---
+261 -346
View File
@@ -1,195 +1,149 @@
---
title: Clients
description: >-
Manage clients as first-class entities that can be attached to one or more
inbounds. A single client row drives the settings.clients entry in every
inbound it belongs to. Endpoints live under /panel/api/clients.
description: Manage clients as first-class entities that can be attached to one
or more inbounds. A single client row drives the settings.clients entry in
every inbound it belongs to. Endpoints live under /panel/api/clients.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every client with its attached inbound IDs and traffic record. The
title: List every client with its attached inbound IDs and traffic record. The
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
url: >-
#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
url: '#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write'
- depth: 2
title: >-
Filter, sort, and paginate clients on the server. Each item is a slim
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. 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'
- depth: 2
title: >-
Fetch one client by email, including the inbound IDs and external config
title: Fetch one client by email, including the inbound IDs and external config
IDs it is attached to.
url: >-
#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
url: '#fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to'
- depth: 2
title: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess, password
for Trojan/Shadowsocks, auth for Hysteria) are generated server-side
when omitted, so callers can send only the universal fields.
url: >-
#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
title: Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets are generated server-side when
omitted, so callers can send only the universal fields.
url: '#create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields'
- depth: 2
title: >-
Update an existing client by email. Changes propagate to every attached
title: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of fields
you want to keep (the server replaces the row, it does not patch).
url: >-
#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
url: '#update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch'
- depth: 2
title: >-
Delete a client by email. Removes it from every attached inbound and
title: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
url: >-
#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
url: '#delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed'
- depth: 2
title: >-
Attach an existing client to one or more additional inbounds. Body is
title: Attach an existing client to one or more additional inbounds. Body is
JSON.
url: >-
#attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
url: '#attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json'
- depth: 2
title: Detach a client from one or more inbounds without deleting the client.
url: '#detach-a-client-from-one-or-more-inbounds-without-deleting-the-client'
- depth: 2
title: >-
Replace a client's external links (per-client share links and remote
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
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'
- depth: 2
title: >-
Reset the up/down counters for every client globally. Quotas and expiry
title: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
moved.
url: >-
#reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
url: '#reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved'
- depth: 2
title: >-
Delete every client whose traffic quota is exhausted (used >= total,
when reset is disabled) or whose expiry has passed. Returns the deleted
count and triggers an Xray restart when any client was on a running
inbound.
url: >-
#delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
title: Delete every client whose traffic quota is exhausted (used >= total, when
reset is disabled) or whose expiry has passed. Returns the deleted count
and triggers an Xray restart when any client was on a running inbound.
url: '#delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound'
- depth: 2
title: >-
Delete every client that is not attached to any inbound, along with its
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
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'
- depth: 2
title: >-
Return every client as a {client, inboundIds} array — the same shape
title: Return every client as a {client, inboundIds} array — the same shape
/bulkCreate and /import accept — so the payload round-trips straight
back through /import. Clients with no inbound attachment are included
with an empty inboundIds list. The UI shows this in a CodeMirror viewer
(copy / download); programmatic callers get the array in obj.
url: >-
#return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
url: '#return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj'
- depth: 2
title: >-
Import clients from a JSON body { "data": "<json>" }, where data is a
title: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]). Items
with inboundIds are created and attached to those inbounds; items with
an empty inboundIds list are restored as unattached client records.
Existing emails are never overwritten — they are returned in skipped.
Triggers a single Xray restart at the end if any target inbound was
running.
url: >-
#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
running.'
url: '#import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running'
- depth: 2
title: >-
Shift expiry and/or traffic quota for many clients in one call.
title: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry
(expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the
corresponding field — bulk extend never converts unlimited to limited.
The optional flow directive sets the XTLS flow on every client: "none"
clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the
inbound supports it (omit or "" to leave it unchanged). Returns the
adjusted count and per-email skip reasons.
url: >-
#shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
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'
- depth: 2
title: >-
Enable many clients in one call. Emails are grouped by inbound and
title: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to add each user. Note that enabling a
client whose quota is exhausted or whose expiry has passed only flips
the flag — the traffic loop will disable it again on the next tick.
Returns the changed count and per-email skip reasons.
url: >-
#enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
url: '#enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons'
- depth: 2
title: >-
Disable many clients in one call. Emails are grouped by inbound and
title: Disable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to remove each user. Returns the
changed count and per-email skip reasons.
url: >-
#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
url: '#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons'
- depth: 2
title: >-
Delete many clients in one call. The server processes the list
title: Delete many clients in one call. The server processes the list
sequentially so each delete sees the committed state of the previous one
— avoids the race the per-email fan-out had on the panel side. Pass
keepTraffic=true to retain the xray_client_traffic rows after deletion.
url: >-
#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
url: '#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion'
- depth: 2
title: >-
Create many clients in one call. Body is a JSON array of {client,
title: Create many clients in one call. Body is a JSON array of {client,
inboundIds} payloads — the same shape /add accepts. Items are processed
sequentially; per-email skip reasons are returned for items that fail
(e.g., duplicate email). Triggers a single Xray restart at the end if
any inbound was running.
url: >-
#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
url: '#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running'
- depth: 2
title: >-
Add many clients to a group in one call. Updates clients.group_name and
title: Add many clients to a group in one call. Updates clients.group_name and
patches the matching client entry inside every owning inbound's settings
JSON in a single transaction. If the group name does not yet exist (in
client_groups or as a derived label), it is auto-created as a persistent
group. To clear the group label, use /groups/bulkRemove instead.
url: >-
#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
url: '#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead'
- depth: 2
title: >-
Clear the group label on many clients in one call. Inverse of
title: Clear the group label on many clients in one call. Inverse of
/groups/bulkAdd. Clients themselves are kept — only the group label is
cleared from clients.group_name and from each owning inbound's settings
JSON. Groups become empty if all their members are removed.
url: >-
#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
url: '#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed'
- depth: 2
title: >-
Attach many existing clients to many inbounds in one call. Each client
title: Attach many existing clients to many inbounds in one call. Each client
keeps its identity (email/UUID/password/subId) and a shared traffic row;
all clients are added to a target inbound in a single AddInboundClient
call. Clients already present on a target are reported under skipped.
Returns per-email attached/skipped/errors lists and triggers a single
Xray restart if any target inbound was running.
url: >-
#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: >-
Mirror of bulkAttach: detach many existing clients from many inbounds in
title: "Mirror of bulkAttach: detach many existing clients from many inbounds in
one call. For each email, intersects the client's current inbounds with
the requested set and detaches from those only; (email, inbound) pairs
where the client is not currently attached are silently no-ops. Emails
@@ -197,110 +151,82 @@ _openapi:
skipped. Client records are kept even if they become orphaned — use
bulkDel for full removal. Returns per-email detached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
url: >-
#mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
running."
url: '#mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: >-
Zero up/down counters for many clients in one call. Loops the
title: Zero up/down counters for many clients in one call. Loops the
single-reset path so each client is re-enabled across its attached
inbounds and pushed to Xray/remote nodes. Returns the count of
successfully reset clients.
url: >-
#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
url: '#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients'
- depth: 2
title: >-
List all client groups with their member counts. Merges persisted groups
title: List all client groups with their member counts. Merges persisted groups
(rows in client_groups, including empty placeholders) with the distinct
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
url: '#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
title: Return just the email list of clients that currently belong to the given
group. Useful for fanning a single bulk action over an entire group
without round-tripping the full client list.
url: >-
#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
url: '#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list'
- depth: 2
title: >-
Create a new empty (placeholder) group. The group becomes selectable in
title: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
url: '#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists'
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
title: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
url: '#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated'
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
title: Remove a group. Deletes the client_groups row and clears the group label
from every matching client (both clients.group_name and the inbound
settings JSON). The clients themselves are NOT deleted — use /bulkDel
after filtering by group for that. Returns the count of clients whose
label was cleared.
url: >-
#remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
url: '#remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared'
- depth: 2
title: >-
Zero out a single clients up/down counters. Re-enables the client
across every attached inbound and pushes the change to Xray (or the
remote node) so depleted users can connect again immediately.
url: >-
#zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
title: Zero out a single clients up/down counters. Re-enables the client across
every attached inbound and pushes the change to Xray (or the remote
node) so depleted users can connect again immediately.
url: '#zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately'
- depth: 2
title: >-
Manually adjust a clients upload + download counters. Useful for
title: Manually adjust a clients upload + download counters. Useful for
migrations from external accounting systems.
url: >-
#manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
url: '#manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems'
- depth: 2
title: >-
List source IPs that have connected with the given clients credentials.
title: List source IPs that have connected with the given clients credentials.
Returns an array of "ip (timestamp)" strings.
url: >-
#list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
url: '#list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings'
- depth: 2
title: Reset the recorded IP list for a client.
url: '#reset-the-recorded-ip-list-for-a-client'
- depth: 2
title: >-
List the emails of currently connected clients (last seen within the
title: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
url: >-
#list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
url: '#list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node'
- depth: 2
title: >-
Online client emails grouped by the panelGuid of the node that
physically hosts each client. The local panel uses its own GUID; each
node (at any depth in a chain) uses its GUID. Lets the inbounds page
attribute online status to the real node instead of the intermediate one
it syncs through.
url: >-
#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
title: Online client emails grouped by the panelGuid of the node that physically
hosts each client. The local panel uses its own GUID; each node (at any
depth in a chain) uses its GUID. Lets the inbounds page attribute online
status to the real node instead of the intermediate one it syncs
through.
url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through'
- depth: 2
title: >-
Per-client source IPs grouped by the panelGuid of the node that observed
title: Per-client source IPs grouped by the panelGuid of the node that observed
them. Lets the central panel attribute and enforce per-client IP limits
using the real visitor IPs each node sees, instead of the address of the
intermediate panel it syncs through.
url: >-
#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
url: '#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through'
- depth: 2
title: >-
Inbound tags that carried traffic within the heartbeat window, grouped
by the hosting node's panelGuid. Pairs with onlinesByGuid so the
inbounds page only marks a multi-inbound client online on the inbounds
it actually used. Nodes that do not report per-inbound activity are
absent.
url: >-
#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
title: Inbound tags that carried traffic within the heartbeat window, grouped by
the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds
page only marks a multi-inbound client online on the inbounds it
actually used. Nodes that do not report per-inbound activity are absent.
url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent'
- depth: 2
title: Map of client email → last-seen unix timestamp.
url: '#map-of-client-email--last-seen-unix-timestamp'
@@ -308,189 +234,151 @@ _openapi:
title: Traffic counters for a client identified by email.
url: '#traffic-counters-for-a-client-identified-by-email'
- depth: 2
title: >-
Return every protocol URL (vless://, vmess://, trojan://, ss://,
title: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
result set as /sub/<subId>, but as a JSON array — no base64. When an
inbound has streamSettings.externalProxy set, one URL is emitted per
external proxy. Empty array when the subId has no enabled clients.
url: >-
#return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
url: '#return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients'
- depth: 2
title: >-
Return every URL for one client across all attached inbounds — the same
title: 'Return every URL for one client across all attached inbounds — the same
strings the Copy URL button copies in the panel UI. Supported protocols:
vmess, vless, trojan, shadowsocks, hysteria. If
streamSettings.externalProxy is set, returns one URL per external proxy.
Protocols without a URL form (socks, http, mixed, wireguard, dokodemo,
tunnel) contribute nothing.
url: >-
#return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
tunnel) contribute nothing.'
url: '#return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing'
- 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'
structuredData:
headings:
- content: >-
List every client with its attached inbound IDs and traffic record.
The reverse field, if set, is returned as a nested JSON object (legacy
- content: List every client with its attached inbound IDs and traffic record. The
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
id: >-
list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: >-
Filter, sort, and paginate clients on the server. Each item is a slim
id: list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
response also includes a summary computed across the full DB row set
so dashboard counters stay stable as the user paginates or filters.
Page size capped at 200; fetch /get/:email to obtain the full
per-client payload for an edit/info modal.
id: >-
filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal
- content: >-
Fetch one client by email, including the inbound IDs and external
id: filter-sort-and-paginate-clients-on-the-server-each-item-is-a-slim-row-no-uuidpasswordauthflowsecurityreversetgid-so-the-clients-page-can-ship-25-ish-rows-in-a-few-kb-instead-of-the-full-table-the-response-also-includes-a-summary-computed-across-the-full-db-row-set-so-dashboard-counters-stay-stable-as-the-user-paginates-or-filters-page-size-capped-at-200-fetch-getemail-to-obtain-the-full-per-client-payload-for-an-editinfo-modal
- content: Fetch one client by email, including the inbound IDs and external
config IDs it is attached to.
id: >-
fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: >-
Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets (UUID for VLESS/VMess,
password for Trojan/Shadowsocks, auth for Hysteria) are generated
server-side when omitted, so callers can send only the universal
fields.
id: >-
create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-uuid-for-vlessvmess-password-for-trojanshadowsocks-auth-for-hysteria-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: >-
Update an existing client by email. Changes propagate to every
attached inbound. Body is the JSON client payload — supply the full
set of fields you want to keep (the server replaces the row, it does
not patch).
id: >-
update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
- content: >-
Delete a client by email. Removes it from every attached inbound and
id: fetch-one-client-by-email-including-the-inbound-ids-and-external-config-ids-it-is-attached-to
- content: Create a new client and attach it to one or more inbounds in a single
call. Body is JSON. Per-protocol secrets are generated server-side
when omitted, so callers can send only the universal fields.
id: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: Update an existing client by email. Changes propagate to every attached
inbound. Body is the JSON client payload — supply the full set of
fields you want to keep (the server replaces the row, it does not
patch).
id: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload--supply-the-full-set-of-fields-you-want-to-keep-the-server-replaces-the-row-it-does-not-patch
- content: Delete a client by email. Removes it from every attached inbound and
drops its traffic record unless keepTraffic=1 is passed.
id: >-
delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: >-
Attach an existing client to one or more additional inbounds. Body is
id: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed
- content: Attach an existing client to one or more additional inbounds. Body is
JSON.
id: >-
attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
id: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
- content: Detach a client from one or more inbounds without deleting the client.
id: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client
- content: >-
Replace a client's external links (per-client share links and remote
- content: Replace a client's external links (per-client share links and remote
subscription URLs surfaced in their subscription). Sends the full set;
the server replaces all rows.
id: >-
replace-a-clients-external-links-per-client-share-links-and-remote-subscription-urls-surfaced-in-their-subscription-sends-the-full-set-the-server-replaces-all-rows
- content: >-
Reset the up/down counters for every client globally. Quotas and
expiry are not affected. Triggers an Xray restart if any counter
actually moved.
id: >-
reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
- content: >-
Delete every client whose traffic quota is exhausted (used >= total,
id: replace-a-clients-external-links-per-client-share-links-and-remote-subscription-urls-surfaced-in-their-subscription-sends-the-full-set-the-server-replaces-all-rows
- content: Reset the up/down counters for every client globally. Quotas and expiry
are not affected. Triggers an Xray restart if any counter actually
moved.
id: reset-the-updown-counters-for-every-client-globally-quotas-and-expiry-are-not-affected-triggers-an-xray-restart-if-any-counter-actually-moved
- content: Delete every client whose traffic quota is exhausted (used >= total,
when reset is disabled) or whose expiry has passed. Returns the
deleted count and triggers an Xray restart when any client was on a
running inbound.
id: >-
delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
- content: >-
Delete every client that is not attached to any inbound, along with
its traffic record, IP log, and external links. Useful for clearing
id: delete-every-client-whose-traffic-quota-is-exhausted-used--total-when-reset-is-disabled-or-whose-expiry-has-passed-returns-the-deleted-count-and-triggers-an-xray-restart-when-any-client-was-on-a-running-inbound
- content: Delete every client that is not attached to any inbound, along with its
traffic record, IP log, and external links. Useful for clearing
clients left unattached after their inbounds were removed. Returns the
deleted count. Cannot be undone.
id: >-
delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
- content: >-
Return every client as a {client, inboundIds} array — the same shape
id: delete-every-client-that-is-not-attached-to-any-inbound-along-with-its-traffic-record-ip-log-and-external-links-useful-for-clearing-clients-left-unattached-after-their-inbounds-were-removed-returns-the-deleted-count-cannot-be-undone
- content: Return every client as a {client, inboundIds} array — the same shape
/bulkCreate and /import accept — so the payload round-trips straight
back through /import. Clients with no inbound attachment are included
with an empty inboundIds list. The UI shows this in a CodeMirror
viewer (copy / download); programmatic callers get the array in obj.
id: >-
return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
- content: >-
Import clients from a JSON body { "data": "<json>" }, where data is a
id: return-every-client-as-a-client-inboundids-array--the-same-shape-bulkcreate-and-import-accept--so-the-payload-round-trips-straight-back-through-import-clients-with-no-inbound-attachment-are-included-with-an-empty-inboundids-list-the-ui-shows-this-in-a-codemirror-viewer-copy--download-programmatic-callers-get-the-array-in-obj
- content: 'Import clients from a JSON body { "data": "<json>" }, where data is a
string-encoded array produced by /export ([{client, inboundIds}]).
Items with inboundIds are created and attached to those inbounds;
items with an empty inboundIds list are restored as unattached client
records. Existing emails are never overwritten — they are returned in
skipped. Triggers a single Xray restart at the end if any target
inbound was running.
id: >-
import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
- content: >-
Shift expiry and/or traffic quota for many clients in one call.
inbound was running.'
id: import-clients-from-a-json-body--data-json--where-data-is-a-string-encoded-array-produced-by-export-client-inboundids-items-with-inboundids-are-created-and-attached-to-those-inbounds-items-with-an-empty-inboundids-list-are-restored-as-unattached-client-records-existing-emails-are-never-overwritten--they-are-returned-in-skipped-triggers-a-single-xray-restart-at-the-end-if-any-target-inbound-was-running
- content: 'Shift expiry and/or traffic quota for many clients in one call.
addDays/addBytes may be negative. Clients with unlimited expiry
(expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the
corresponding field — bulk extend never converts unlimited to limited.
The optional flow directive sets the XTLS flow on every client: "none"
clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where
the inbound supports it (omit or "" to leave it unchanged). Returns
the adjusted count and per-email skip reasons.
id: >-
shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
- content: >-
Enable many clients in one call. Emails are grouped by inbound and
the adjusted count and per-email skip reasons.'
id: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-returns-the-adjusted-count-and-per-email-skip-reasons
- content: Enable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to add each user. Note that enabling
a client whose quota is exhausted or whose expiry has passed only
flips the flag — the traffic loop will disable it again on the next
tick. Returns the changed count and per-email skip reasons.
id: >-
enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
- content: >-
Disable many clients in one call. Emails are grouped by inbound and
id: enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons
- content: Disable many clients in one call. Emails are grouped by inbound and
applied with a single read-modify-write per inbound; the running Xray
(local or remote node) is updated to remove each user. Returns the
changed count and per-email skip reasons.
id: >-
disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
- content: >-
Delete many clients in one call. The server processes the list
id: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
- content: Delete many clients in one call. The server processes the list
sequentially so each delete sees the committed state of the previous
one — avoids the race the per-email fan-out had on the panel side.
Pass keepTraffic=true to retain the xray_client_traffic rows after
deletion.
id: >-
delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
- content: >-
Create many clients in one call. Body is a JSON array of {client,
id: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
- content: Create many clients in one call. Body is a JSON array of {client,
inboundIds} payloads — the same shape /add accepts. Items are
processed sequentially; per-email skip reasons are returned for items
that fail (e.g., duplicate email). Triggers a single Xray restart at
the end if any inbound was running.
id: >-
create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
- content: >-
Add many clients to a group in one call. Updates clients.group_name
and patches the matching client entry inside every owning inbound's
id: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
- content: Add many clients to a group in one call. Updates clients.group_name and
patches the matching client entry inside every owning inbound's
settings JSON in a single transaction. If the group name does not yet
exist (in client_groups or as a derived label), it is auto-created as
a persistent group. To clear the group label, use /groups/bulkRemove
instead.
id: >-
add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
- content: >-
Clear the group label on many clients in one call. Inverse of
id: add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
- content: Clear the group label on many clients in one call. Inverse of
/groups/bulkAdd. Clients themselves are kept — only the group label is
cleared from clients.group_name and from each owning inbound's
settings JSON. Groups become empty if all their members are removed.
id: >-
clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
- content: >-
Attach many existing clients to many inbounds in one call. Each client
id: clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
- content: Attach many existing clients to many inbounds in one call. Each client
keeps its identity (email/UUID/password/subId) and a shared traffic
row; all clients are added to a target inbound in a single
AddInboundClient call. Clients already present on a target are
reported under skipped. Returns per-email attached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
id: >-
attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: >-
Mirror of bulkAttach: detach many existing clients from many inbounds
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: "Mirror of bulkAttach: detach many existing clients from many inbounds
in one call. For each email, intersects the client's current inbounds
with the requested set and detaches from those only; (email, inbound)
pairs where the client is not currently attached are silently no-ops.
@@ -498,118 +386,145 @@ _openapi:
under skipped. Client records are kept even if they become orphaned —
use bulkDel for full removal. Returns per-email
detached/skipped/errors lists and triggers a single Xray restart if
any target inbound was running.
id: >-
mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: >-
Zero up/down counters for many clients in one call. Loops the
any target inbound was running."
id: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: Zero up/down counters for many clients in one call. Loops the
single-reset path so each client is re-enabled across its attached
inbounds and pushed to Xray/remote nodes. Returns the count of
successfully reset clients.
id: >-
zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
- content: >-
List all client groups with their member counts. Merges persisted
id: zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-returns-the-count-of-successfully-reset-clients
- content: List all client groups with their member counts. Merges persisted
groups (rows in client_groups, including empty placeholders) with the
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
id: list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
group without round-tripping the full client list.
id: >-
return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: >-
Create a new empty (placeholder) group. The group becomes selectable
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
id: return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
id: create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
id: rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
- content: Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
inbound settings JSON). The clients themselves are NOT deleted — use
/bulkDel after filtering by group for that. Returns the count of
clients whose label was cleared.
id: >-
remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
- content: >-
Zero out a single clients up/down counters. Re-enables the client
id: remove-a-group-deletes-the-client_groups-row-and-clears-the-group-label-from-every-matching-client-both-clientsgroup_name-and-the-inbound-settings-json-the-clients-themselves-are-not-deleted--use-bulkdel-after-filtering-by-group-for-that-returns-the-count-of-clients-whose-label-was-cleared
- content: Zero out a single clients up/down counters. Re-enables the client
across every attached inbound and pushes the change to Xray (or the
remote node) so depleted users can connect again immediately.
id: >-
zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
- content: >-
Manually adjust a clients upload + download counters. Useful for
id: zero-out-a-single-clients-updown-counters-re-enables-the-client-across-every-attached-inbound-and-pushes-the-change-to-xray-or-the-remote-node-so-depleted-users-can-connect-again-immediately
- content: Manually adjust a clients upload + download counters. Useful for
migrations from external accounting systems.
id: >-
manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
- content: >-
List source IPs that have connected with the given clients
id: manually-adjust-a-clients-upload--download-counters-useful-for-migrations-from-external-accounting-systems
- content: List source IPs that have connected with the given clients
credentials. Returns an array of "ip (timestamp)" strings.
id: >-
list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
id: list-source-ips-that-have-connected-with-the-given-clients-credentials-returns-an-array-of-ip-timestamp-strings
- content: Reset the recorded IP list for a client.
id: reset-the-recorded-ip-list-for-a-client
- content: >-
List the emails of currently connected clients (last seen within the
- content: List the emails of currently connected clients (last seen within the
heartbeat window), deduped across every node.
id: >-
list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
- content: >-
Online client emails grouped by the panelGuid of the node that
id: list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
- content: Online client emails grouped by the panelGuid of the node that
physically hosts each client. The local panel uses its own GUID; each
node (at any depth in a chain) uses its GUID. Lets the inbounds page
attribute online status to the real node instead of the intermediate
one it syncs through.
id: >-
online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
- content: >-
Per-client source IPs grouped by the panelGuid of the node that
id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
- content: Per-client source IPs grouped by the panelGuid of the node that
observed them. Lets the central panel attribute and enforce per-client
IP limits using the real visitor IPs each node sees, instead of the
address of the intermediate panel it syncs through.
id: >-
per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
- content: >-
Inbound tags that carried traffic within the heartbeat window, grouped
id: per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
- content: Inbound tags that carried traffic within the heartbeat window, grouped
by the hosting node's panelGuid. Pairs with onlinesByGuid so the
inbounds page only marks a multi-inbound client online on the inbounds
it actually used. Nodes that do not report per-inbound activity are
absent.
id: >-
inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
- content: Map of client email → last-seen unix timestamp.
id: map-of-client-email--last-seen-unix-timestamp
- content: Traffic counters for a client identified by email.
id: traffic-counters-for-a-client-identified-by-email
- content: >-
Return every protocol URL (vless://, vmess://, trojan://, ss://,
- content: Return every protocol URL (vless://, vmess://, trojan://, ss://,
hysteria://, hy2://) for clients matching the subscription ID. Same
result set as /sub/<subId>, but as a JSON array — no base64. When an
inbound has streamSettings.externalProxy set, one URL is emitted per
external proxy. Empty array when the subId has no enabled clients.
id: >-
return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
- content: >-
Return every URL for one client across all attached inbounds — the
id: return-every-protocol-url-vless-vmess-trojan-ss-hysteria-hy2-for-clients-matching-the-subscription-id-same-result-set-as-subsubid-but-as-a-json-array--no-base64-when-an-inbound-has-streamsettingsexternalproxy-set-one-url-is-emitted-per-external-proxy-empty-array-when-the-subid-has-no-enabled-clients
- content: 'Return every URL for one client across all attached inbounds — the
same strings the Copy URL button copies in the panel UI. Supported
protocols: vmess, vless, trojan, shadowsocks, hysteria. If
streamSettings.externalProxy is set, returns one URL per external
proxy. Protocols without a URL form (socks, http, mixed, wireguard,
dokodemo, tunnel) contribute nothing.
id: >-
return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
contents: []
dokodemo, tunnel) contribute nothing.'
id: return-every-url-for-one-client-across-all-attached-inbounds--the-same-strings-the-copy-url-button-copies-in-the-panel-ui-supported-protocols-vmess-vless-trojan-shadowsocks-hysteria-if-streamsettingsexternalproxy-is-set-returns-one-url-per-external-proxy-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing
- 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
contents:
- content: >-
Fields the server fills in when they are omitted — a valid value sent
by the caller is never overwritten. Re-adding an email that already
exists, with its stored `subId`, reuses the stored `id`, `password`,
`auth` and `secret` instead of minting new ones, so the identity stays
in sync across its inbounds.
- **VLESS / VMess** — `id`, a fresh UUID
- **Trojan** — `password`
- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a
supplied password that does not base64-decode to the key length of the
cipher (16 or 32 bytes) is replaced by a generated key and the call
still succeeds, so read the client back if you did not let the server
pick. Legacy ciphers keep any non-empty password
- **Hysteria** — `auth`
- **mtproto** — `secret`, a FakeTLS secret derived from the fronting
domain of the inbound, or from `www.cloudflare.com` when it has none
- **WireGuard** — `privateKey` and `publicKey` when both are blank, or
`publicKey` alone when only a `privateKey` was sent, plus
`allowedIPs`: one free `/32` taken from the /24 the existing peers of
that inbound already sit in, or from `10.0.0.0/24` when it has none
Accepted on the same body but never generated: `preSharedKey` and
`keepAlive` (WireGuard), `adTag` (mtproto).
WireGuard is the only one of these that can fail. Allocation widens
the search to the containing /16 before giving up with `wireguard: no
free address available in <scope>`, and an `allowedIPs` supplied by
the caller is validated instead of allocated: `wireguard: allowedIPs
entry already used by another client: <address>` when a different
client of that same inbound already holds it. The check is per
inbound, so the same address on two different inbounds is accepted.
The same validation runs on POST /panel/api/clients/{email}/attach,
where a client that already carries an address brings it along.
heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields
- content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound
instead of being given a fresh address, so the call fails with
`wireguard: allowedIPs entry already used by another client:
<address>` when a different client of the target inbound already holds
it. Free the address on that inbound first — see POST
/panel/api/clients/add for the full rule.'
heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json
---
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
@@ -621,7 +536,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/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"},{"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"}]} showTitle />
</>
);
}
+19 -36
View File
@@ -1,7 +1,6 @@
---
title: Hosts
description: >-
Per-inbound override endpoints. Each enabled host renders one extra
description: Per-inbound override endpoints. Each enabled host renders one extra
subscription link/proxy with its own address/port/TLS, superseding the legacy
externalProxy array. All endpoints under /panel/api/hosts.
full: true
@@ -10,11 +9,9 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every host across all inbounds, grouped by inbound then ordered by
title: List every host across all inbounds, grouped by inbound then ordered by
sort order.
url: >-
#list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order
url: '#list-every-host-across-all-inbounds-grouped-by-inbound-then-ordered-by-sort-order'
- depth: 2
title: Fetch a single host by ID.
url: '#fetch-a-single-host-by-id'
@@ -25,26 +22,20 @@ _openapi:
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
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
url: '#create-a-host-on-an-inbound-inboundid-and-remark-are-required-security-defaults-to-same-inherit-the-inbound'
- depth: 2
title: >-
Replace a hosts content. The inbound and sort order are immutable here
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
url: '#replace-a-hosts-content-the-inbound-and-sort-order-are-immutable-here-use-reorder-for-ordering'
- depth: 2
title: Delete a host.
url: '#delete-a-host'
- depth: 2
title: >-
Enable or disable a single host (disabled hosts are skipped in
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
url: '#enable-or-disable-a-single-host-disabled-hosts-are-skipped-in-subscriptions'
- 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'
@@ -56,34 +47,26 @@ _openapi:
url: '#delete-many-hosts-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: 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: 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;
- 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
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
- 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
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.
+68 -120
View File
@@ -1,8 +1,7 @@
---
title: Inbounds
description: >-
Manage inbound configurations and their clients. All endpoints live under
/panel/api/inbounds and require a logged-in session or Bearer token.
description: Manage inbound configurations and their clients. All endpoints live
under /panel/api/inbounds and require a logged-in session or Bearer token.
Link-generating endpoints honour forwarded headers only when the request comes
from a configured trusted proxy.
full: true
@@ -11,25 +10,20 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every inbound owned by the authenticated user, including each
title: List every inbound owned by the authenticated user, including each
inbounds clientStats traffic counters. settings, streamSettings, and
sniffing are returned as nested JSON objects (no escaped strings);
legacy callers that send them back as JSON-encoded strings are still
accepted on write.
url: >-
#list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
url: '#list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write'
- depth: 2
title: >-
Same shape as /list but with settings.clients[] stripped down to {email,
title: Same shape as /list but with settings.clients[] stripped down to {email,
enable, comment} and ClientStats not enriched with UUID/SubId. Use this
for list pages; fetch /get/:id when you need the full per-client payload
(uuid, password, flow, ...).
url: >-
#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-'
- depth: 2
title: >-
Lightweight picker projection of the authenticated users inbounds.
title: Lightweight picker projection of the authenticated users inbounds.
Returns id, remark, tag, protocol, port, a server-computed
tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on
XHTTP with VLESS encryption / vlessenc enabled), and ssMethod (the
@@ -38,110 +32,86 @@ _openapi:
dropdowns and attach pickers — it skips settings, streamSettings, and
clientStats so the payload stays small even on panels with thousands of
clients.
url: >-
#lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
url: '#lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients'
- depth: 2
title: Fetch a single inbound by numeric ID.
url: '#fetch-a-single-inbound-by-numeric-id'
- depth: 2
title: >-
Create a new inbound. Send the full inbound payload (protocol, port,
title: Create a new inbound. Send the full inbound payload (protocol, port,
settings, streamSettings, sniffing, remark, expiryTime, total, enable).
settings, streamSettings, and sniffing may be sent as nested JSON
objects (preferred) or as JSON-encoded strings (legacy).
url: >-
#create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
url: '#create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy'
- depth: 2
title: Delete an inbound by ID. Also removes its associated client stats rows.
url: '#delete-an-inbound-by-id-also-removes-its-associated-client-stats-rows'
- depth: 2
title: >-
Delete many inbounds in one call. Processes the list sequentially;
title: Delete many inbounds in one call. Processes the list sequentially;
failures are reported per id and the rest still proceed. Restarts xray
at most once.
url: >-
#delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
url: '#delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once'
- depth: 2
title: >-
Replace an inbounds configuration. Body shape mirrors /add. Heavy on
title: Replace an inbounds configuration. Body shape mirrors /add. Heavy on
inbounds with thousands of clients — prefer /setEnable for enable-only
flips.
url: >-
#replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
url: '#replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips'
- depth: 2
title: >-
Toggle only the enable flag without serialising the whole settings JSON.
title: Toggle only the enable flag without serialising the whole settings JSON.
Recommended for UI switches on large inbounds.
url: >-
#toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
url: '#toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds'
- depth: 2
title: >-
Zero out upload + download counters for a single inbound. Does not touch
title: Zero out upload + download counters for a single inbound. Does not touch
per-client counters.
url: >-
#zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
url: '#zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters'
- depth: 2
title: >-
Remove every client attached to a single inbound while keeping the
title: Remove every client attached to a single inbound while keeping the
inbound itself. Collects emails from settings.clients[] and feeds them
into the optimized bulk-delete path (runtime user removal + traffic-row
cleanup + SyncInbound). Destructive and cannot be undone.
url: >-
#remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
url: '#remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone'
- depth: 2
title: >-
Reset upload + download counters on every inbound. Destructive —
title: Reset upload + download counters on every inbound. Destructive —
accounting history is lost.
url: >-
#reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
url: '#reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost'
- depth: 2
title: >-
Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
title: Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
The body uses form encoding with a single "data" field.
url: >-
#bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
url: '#bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field'
- depth: 2
title: >-
Receive a master panel's aggregated per-client usage, keyed by the
title: Receive a master panel's aggregated per-client usage, keyed by the
master's GUID. Stored in a side table used only for the UI display
overlay and local quota enforcement — never folded into the local
counters that masters poll, so delta accounting stays intact. Called
panel-to-panel by the node traffic sync job.
url: >-
#receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
url: '#receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job'
- depth: 2
title: >-
List the fallback rules attached to a master VLESS/Trojan TCP-TLS
title: List the fallback rules attached to a master VLESS/Trojan TCP-TLS
inbound. Each rule links one child inbound (the dest) to optional
SNI/ALPN/path/dest/xver match criteria. When dest is empty the child
inbound's listen+port is used.
url: >-
#list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
url: '#list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used'
- depth: 2
title: >-
Replace the entire fallback list for a master inbound. Body is JSON.
title: Replace the entire fallback list for a master inbound. Body is JSON.
Triggers an Xray restart.
url: >-
#replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
url: '#replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart'
- 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
- content: List every inbound owned by the authenticated user, including each
inbounds clientStats traffic counters. settings, streamSettings, and
sniffing are returned as nested JSON objects (no escaped strings);
legacy callers that send them back as JSON-encoded strings are still
accepted on write.
id: >-
list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
- content: >-
Same shape as /list but with settings.clients[] stripped down to
id: list-every-inbound-owned-by-the-authenticated-user-including-each-inbounds-clientstats-traffic-counters-settings-streamsettings-and-sniffing-are-returned-as-nested-json-objects-no-escaped-strings-legacy-callers-that-send-them-back-as-json-encoded-strings-are-still-accepted-on-write
- content: Same shape as /list but with settings.clients[] stripped down to
{email, enable, comment} and ClientStats not enriched with UUID/SubId.
Use this for list pages; fetch /get/:id when you need the full
per-client payload (uuid, password, flow, ...).
id: >-
same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
- content: >-
Lightweight picker projection of the authenticated users inbounds.
id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
- content: Lightweight picker projection of the authenticated users inbounds.
Returns id, remark, tag, protocol, port, a server-computed
tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on
XHTTP with VLESS encryption / vlessenc enabled), and ssMethod (the
@@ -150,80 +120,58 @@ _openapi:
dropdowns and attach pickers — it skips settings, streamSettings, and
clientStats so the payload stays small even on panels with thousands
of clients.
id: >-
lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
id: lightweight-picker-projection-of-the-authenticated-users-inbounds-returns-id-remark-tag-protocol-port-a-server-computed-tlsflowcapable-flag-true-for-vless-on-tcp-with-tls-or-reality-or-on-xhttp-with-vless-encryption--vlessenc-enabled-and-ssmethod-the-shadowsocks-cipher-empty-for-non-shadowsocks-inbounds--used-by-the-client-ui-to-generate-a-valid-shadowsocks-2022-psk-use-this-for-dropdowns-and-attach-pickers--it-skips-settings-streamsettings-and-clientstats-so-the-payload-stays-small-even-on-panels-with-thousands-of-clients
- content: Fetch a single inbound by numeric ID.
id: fetch-a-single-inbound-by-numeric-id
- content: >-
Create a new inbound. Send the full inbound payload (protocol, port,
- content: Create a new inbound. Send the full inbound payload (protocol, port,
settings, streamSettings, sniffing, remark, expiryTime, total,
enable). settings, streamSettings, and sniffing may be sent as nested
JSON objects (preferred) or as JSON-encoded strings (legacy).
id: >-
create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
- content: >-
Delete an inbound by ID. Also removes its associated client stats
rows.
id: create-a-new-inbound-send-the-full-inbound-payload-protocol-port-settings-streamsettings-sniffing-remark-expirytime-total-enable-settings-streamsettings-and-sniffing-may-be-sent-as-nested-json-objects-preferred-or-as-json-encoded-strings-legacy
- content: Delete an inbound by ID. Also removes its associated client stats rows.
id: delete-an-inbound-by-id-also-removes-its-associated-client-stats-rows
- content: >-
Delete many inbounds in one call. Processes the list sequentially;
- content: Delete many inbounds in one call. Processes the list sequentially;
failures are reported per id and the rest still proceed. Restarts xray
at most once.
id: >-
delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
- content: >-
Replace an inbounds configuration. Body shape mirrors /add. Heavy on
id: delete-many-inbounds-in-one-call-processes-the-list-sequentially-failures-are-reported-per-id-and-the-rest-still-proceed-restarts-xray-at-most-once
- content: Replace an inbounds configuration. Body shape mirrors /add. Heavy on
inbounds with thousands of clients — prefer /setEnable for enable-only
flips.
id: >-
replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
- content: >-
Toggle only the enable flag without serialising the whole settings
id: replace-an-inbounds-configuration-body-shape-mirrors-add-heavy-on-inbounds-with-thousands-of-clients--prefer-setenable-for-enable-only-flips
- content: Toggle only the enable flag without serialising the whole settings
JSON. Recommended for UI switches on large inbounds.
id: >-
toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
- content: >-
Zero out upload + download counters for a single inbound. Does not
id: toggle-only-the-enable-flag-without-serialising-the-whole-settings-json-recommended-for-ui-switches-on-large-inbounds
- content: Zero out upload + download counters for a single inbound. Does not
touch per-client counters.
id: >-
zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
- content: >-
Remove every client attached to a single inbound while keeping the
id: zero-out-upload--download-counters-for-a-single-inbound-does-not-touch-per-client-counters
- content: Remove every client attached to a single inbound while keeping the
inbound itself. Collects emails from settings.clients[] and feeds them
into the optimized bulk-delete path (runtime user removal +
traffic-row cleanup + SyncInbound). Destructive and cannot be undone.
id: >-
remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
- content: >-
Reset upload + download counters on every inbound. Destructive —
id: remove-every-client-attached-to-a-single-inbound-while-keeping-the-inbound-itself-collects-emails-from-settingsclients-and-feeds-them-into-the-optimized-bulk-delete-path-runtime-user-removal--traffic-row-cleanup--syncinbound-destructive-and-cannot-be-undone
- content: Reset upload + download counters on every inbound. Destructive
accounting history is lost.
id: >-
reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
- content: >-
Bulk-import an inbound from a JSON blob (e.g. one exported via the
UI). The body uses form encoding with a single "data" field.
id: >-
bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
- content: >-
Receive a master panel's aggregated per-client usage, keyed by the
id: reset-upload--download-counters-on-every-inbound-destructive--accounting-history-is-lost
- content: Bulk-import an inbound from a JSON blob (e.g. one exported via the UI).
The body uses form encoding with a single "data" field.
id: bulk-import-an-inbound-from-a-json-blob-eg-one-exported-via-the-ui-the-body-uses-form-encoding-with-a-single-data-field
- content: Receive a master panel's aggregated per-client usage, keyed by the
master's GUID. Stored in a side table used only for the UI display
overlay and local quota enforcement — never folded into the local
counters that masters poll, so delta accounting stays intact. Called
panel-to-panel by the node traffic sync job.
id: >-
receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
- content: >-
List the fallback rules attached to a master VLESS/Trojan TCP-TLS
id: receive-a-master-panels-aggregated-per-client-usage-keyed-by-the-masters-guid-stored-in-a-side-table-used-only-for-the-ui-display-overlay-and-local-quota-enforcement--never-folded-into-the-local-counters-that-masters-poll-so-delta-accounting-stays-intact-called-panel-to-panel-by-the-node-traffic-sync-job
- content: List the fallback rules attached to a master VLESS/Trojan TCP-TLS
inbound. Each rule links one child inbound (the dest) to optional
SNI/ALPN/path/dest/xver match criteria. When dest is empty the child
inbound's listen+port is used.
id: >-
list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
- content: >-
Replace the entire fallback list for a master inbound. Body is JSON.
id: list-the-fallback-rules-attached-to-a-master-vlesstrojan-tcp-tls-inbound-each-rule-links-one-child-inbound-the-dest-to-optional-snialpnpathdestxver-match-criteria-when-dest-is-empty-the-child-inbounds-listenport-is-used
- content: Replace the entire fallback list for a master inbound. Body is JSON.
Triggers an Xray restart.
id: >-
replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-triggers-an-xray-restart
- 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: []
---
@@ -236,7 +184,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/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 />
</>
);
}
+56 -88
View File
@@ -1,51 +1,40 @@
---
title: Nodes
description: >-
Manage remote 3x-ui panels acting as nodes for a central panel. All endpoints
under /panel/api/nodes.
description: Manage remote 3x-ui panels acting as nodes for a central panel. All
endpoints under /panel/api/nodes.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
List every configured node with its connection details, health, and last
title: List every configured node with its connection details, health, and last
heartbeat patch.
url: >-
#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch'
- depth: 2
title: >-
This panel's node-auth CA certificate (public, PEM) to paste into a
title: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
url: >-
#this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
url: '#this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node'
- depth: 2
title: >-
Set the CA certificate this panel trusts for incoming node-API client
title: Set the CA certificate this panel trusts for incoming node-API client
certificates (this panel acting as a node). Paste the managing panel's
CA (from nodes/mtls/ca). An empty caCert disables it. A non-empty value
must be a PEM certificate. Applied on the next panel restart.
url: >-
#set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
url: '#set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart'
- depth: 2
title: Fetch a single node by ID.
url: '#fetch-a-single-node-by-id'
- depth: 2
title: >-
Fetch a node's own web TLS certificate/key file paths (proxied to the
title: Fetch a node's own web TLS certificate/key file paths (proxied to the
node). Used by the inbound form's "Set Cert from Panel" so a
node-assigned inbound gets paths that exist on the node, not the central
panel.
url: >-
#fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel
url: '#fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel'
- depth: 2
title: >-
Register a new remote node. Provide its URL, apiToken, and optional
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
url: '#register-a-new-remote-node-provide-its-url-apitoken-and-optional-remark--allowprivateaddress-flag'
- depth: 2
title: Replace a nodes connection details. Same body shape as /add.
url: '#replace-a-nodes-connection-details-same-body-shape-as-add'
@@ -56,115 +45,94 @@ _openapi:
title: Pause or resume traffic sync with this node.
url: '#pause-or-resume-traffic-sync-with-this-node'
- depth: 2
title: >-
Probe a node without saving it. Uses the body as connection details and
title: Probe a node without saving it. Uses the body as connection details and
returns the same heartbeat snapshot a registered node would have.
url: >-
#probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
url: '#probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have'
- depth: 2
title: >-
Connect to the node over HTTPS without verifying its certificate and
title: Connect to the node over HTTPS without verifying its certificate and
return the leaf certificate's SHA-256 (base64). Used by the Add/Edit
Node dialog to fetch and pin a self-signed certificate. Uses the same
body as /test.
url: >-
#connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
url: '#connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test'
- depth: 2
title: >-
Use unsaved node connection details to list the remote inbounds
available for selective import.
url: >-
#use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
title: Use unsaved node connection details to list the remote inbounds available
for selective import.
url: '#use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import'
- depth: 2
title: Probe an existing node, updating its cached health state.
url: '#probe-an-existing-node-updating-its-cached-health-state'
- depth: 2
title: >-
Trigger the official panel self-updater on each given node (downloads
title: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
updated; offline/disabled ones are reported as skipped. Set "dev": true
to move the nodes to the rolling per-commit dev channel instead of the
latest stable release. Returns a per-node result list.
url: >-
#trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
latest stable release. Returns a per-node result list.'
url: '#trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list'
- depth: 2
title: >-
Aggregated metric history for a node — same shape as /server/history,
title: Aggregated metric history for a node — same shape as /server/history,
scoped to one node.
url: >-
#aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
url: '#aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node'
- 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
- content: List every configured node with its connection details, health, and
last heartbeat patch.
id: >-
list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
- content: >-
This panel's node-auth CA certificate (public, PEM) to paste into a
id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
- content: This panel's node-auth CA certificate (public, PEM) to paste into a
node's mTLS trust setting. Lazily mints the CA and the master client
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
id: >-
this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
- content: >-
Set the CA certificate this panel trusts for incoming node-API client
id: this-panels-node-auth-ca-certificate-public-pem-to-paste-into-a-nodes-mtls-trust-setting-lazily-mints-the-ca-and-the-master-client-cert-on-first-call-pair-with-setting-tlsverifymodemtls-on-the-node
- content: Set the CA certificate this panel trusts for incoming node-API client
certificates (this panel acting as a node). Paste the managing panel's
CA (from nodes/mtls/ca). An empty caCert disables it. A non-empty
value must be a PEM certificate. Applied on the next panel restart.
id: >-
set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
id: set-the-ca-certificate-this-panel-trusts-for-incoming-node-api-client-certificates-this-panel-acting-as-a-node-paste-the-managing-panels-ca-from-nodesmtlsca-an-empty-cacert-disables-it-a-non-empty-value-must-be-a-pem-certificate-applied-on-the-next-panel-restart
- content: Fetch a single node by ID.
id: fetch-a-single-node-by-id
- content: >-
Fetch a node's own web TLS certificate/key file paths (proxied to the
- content: Fetch a node's own web TLS certificate/key file paths (proxied to the
node). Used by the inbound form's "Set Cert from Panel" so a
node-assigned inbound gets paths that exist on the node, not the
central panel.
id: >-
fetch-a-nodes-own-web-tls-certificatekey-file-paths-proxied-to-the-node-used-by-the-inbound-forms-set-cert-from-panel-so-a-node-assigned-inbound-gets-paths-that-exist-on-the-node-not-the-central-panel
- content: >-
Register a new remote node. Provide its URL, apiToken, and optional
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
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: Delete a node. Inbounds bound to it are not auto-migrated.
id: delete-a-node-inbounds-bound-to-it-are-not-auto-migrated
- content: Pause or resume traffic sync with this node.
id: pause-or-resume-traffic-sync-with-this-node
- content: >-
Probe a node without saving it. Uses the body as connection details
and returns the same heartbeat snapshot a registered node would have.
id: >-
probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
- content: >-
Connect to the node over HTTPS without verifying its certificate and
- content: Probe a node without saving it. Uses the body as connection details and
returns the same heartbeat snapshot a registered node would have.
id: probe-a-node-without-saving-it-uses-the-body-as-connection-details-and-returns-the-same-heartbeat-snapshot-a-registered-node-would-have
- content: Connect to the node over HTTPS without verifying its certificate and
return the leaf certificate's SHA-256 (base64). Used by the Add/Edit
Node dialog to fetch and pin a self-signed certificate. Uses the same
body as /test.
id: >-
connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
- content: >-
Use unsaved node connection details to list the remote inbounds
id: connect-to-the-node-over-https-without-verifying-its-certificate-and-return-the-leaf-certificates-sha-256-base64-used-by-the-addedit-node-dialog-to-fetch-and-pin-a-self-signed-certificate-uses-the-same-body-as-test
- content: Use unsaved node connection details to list the remote inbounds
available for selective import.
id: >-
use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
id: use-unsaved-node-connection-details-to-list-the-remote-inbounds-available-for-selective-import
- content: Probe an existing node, updating its cached health state.
id: probe-an-existing-node-updating-its-cached-health-state
- content: >-
Trigger the official panel self-updater on each given node (downloads
- content: 'Trigger the official panel self-updater on each given node (downloads
the latest release and restarts). Only enabled, online nodes are
updated; offline/disabled ones are reported as skipped. Set "dev":
true to move the nodes to the rolling per-commit dev channel instead
of the latest stable release. Returns a per-node result list.
id: >-
trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
- content: >-
Aggregated metric history for a node — same shape as /server/history,
of the latest stable release. Returns a per-node result list.'
id: trigger-the-official-panel-self-updater-on-each-given-node-downloads-the-latest-release-and-restarts-only-enabled-online-nodes-are-updated-offlinedisabled-ones-are-reported-as-skipped-set-dev-true-to-move-the-nodes-to-the-rolling-per-commit-dev-channel-instead-of-the-latest-stable-release-returns-a-per-node-result-list
- content: Aggregated metric history for a node — same shape as /server/history,
scoped to one node.
id: >-
aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
id: aggregated-metric-history-for-a-node--same-shape-as-serverhistory-scoped-to-one-node
- 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: []
---
@@ -177,7 +145,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
<Comp document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/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 />
</>
);
}
+121 -229
View File
@@ -1,65 +1,48 @@
---
title: Server
description: >-
System status, log retrieval, certificate generators, Xray binary management,
and backup/restore. All under /panel/api/server.
description: System status, log retrieval, certificate generators, Xray binary
management, and backup/restore. All under /panel/api/server.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
title: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
seconds in the background.
url: >-
#real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
seconds in the background.'
url: '#real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background'
- depth: 2
title: >-
Reports whether per-client IP limits can be enforced on this host. The
title: Reports whether per-client IP limits can be enforced on this host. The
panel uses it to gate the "IP Limit" field, since enforcement depends on
Fail2ban being installed.
url: >-
#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
url: '#reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed'
- depth: 2
title: >-
Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.
url: >-
#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
title: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead — same
data with a uniform {t, v} shape.'
url: '#legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape'
- depth: 2
title: >-
Aggregated time-series for one metric. Returns an array of {t, v}
samples covering the last ~6 hours.
url: >-
#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
title: Aggregated time-series for one metric. Returns an array of {t, v} samples
covering the last ~6 hours.
url: '#aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours'
- depth: 2
title: >-
Xray runtime metrics state — whether the xray config has a `metrics`
title: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
url: >-
#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
url: '#xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured'
- depth: 2
title: >-
Time-series history for one Xray runtime metric over the last ~6 hours.
title: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
url: >-
#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
url: '#time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket'
- depth: 2
title: >-
Latest snapshot from the Xray observatory — per-outbound latency, health
title: Latest snapshot from the Xray observatory — per-outbound latency, health
status, and last-probe time. Only populated when the Xray config has an
observatory configured.
url: >-
#latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
url: '#latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured'
- depth: 2
title: >-
Time-series of observatory probe results for one outbound tag. Same {t,
title: Time-series of observatory probe results for one outbound tag. Same {t,
v} shape as the other history endpoints.
url: >-
#time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
url: '#time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints'
- depth: 2
title: List Xray binary versions available for install on this host.
url: '#list-xray-binary-versions-available-for-install-on-this-host'
@@ -70,90 +53,66 @@ _openapi:
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.
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'
- depth: 2
title: >-
Stream a cross-engine migration file as an attachment: a .dump (SQL
title: 'Stream a cross-engine migration file as an attachment: a .dump (SQL
text) on SQLite, or a .db SQLite database built from the live data on
PostgreSQL.
url: >-
#stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
PostgreSQL.'
url: '#stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql'
- depth: 2
title: Generate a fresh UUID v4. Convenience helper for client IDs.
url: '#generate-a-fresh-uuid-v4-convenience-helper-for-client-ids'
- depth: 2
title: >-
Return this panel's own web TLS certificate and key file paths. The
title: Return this panel's own web TLS certificate and key file paths. The
central panel calls it on a node (via the node API token) so "Set Cert
from Panel" fills a node-assigned inbound with paths that exist on the
node.
url: >-
#return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
url: '#return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node'
- depth: 2
title: >-
Read-only summaries (guid, parentGuid, name, address, status, versions)
title: Read-only summaries (guid, parentGuid, name, address, status, versions)
of the nodes this panel manages. A parent panel calls it on a node (via
the node API token) to surface transitive sub-nodes in a chained
topology. Counts are computed by the parent, not returned here.
url: >-
#read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
url: '#read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here'
- depth: 2
title: Generate a new X25519 keypair for Reality.
url: '#generate-a-new-x25519-keypair-for-reality'
- depth: 2
title: >-
Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
title: Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
{privateKey, publicKey, seed}.
url: >-
#generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
url: '#generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed'
- depth: 2
title: >-
Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
{clientKey, serverKey}.
url: >-
#generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
title: Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns {clientKey,
serverKey}.
url: '#generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey'
- depth: 2
title: >-
Generate VLESS encryption auth options. Returns an auths array each with
title: Generate VLESS encryption auth options. Returns an auths array each with
id, label, encryption, and decryption fields.
url: >-
#generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
url: '#generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields'
- depth: 2
title: Stop the Xray binary. All proxies go offline immediately.
url: '#stop-the-xray-binary-all-proxies-go-offline-immediately'
- depth: 2
title: >-
Reload Xray with the current config. Typically required after structural
title: Reload Xray with the current config. Typically required after structural
inbound or routing changes.
url: >-
#reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
url: '#reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes'
- depth: 2
title: >-
Download and install the specified Xray version. Pass "latest" for the
title: Download and install the specified Xray version. Pass "latest" for the
newest release.
url: >-
#download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
url: '#download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release'
- depth: 2
title: >-
Self-update the panel to the latest version. The server restarts on
title: Self-update the panel to the latest version. The server restarts on
success.
url: >-
#self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
url: '#self-update-the-panel-to-the-latest-version-the-server-restarts-on-success'
- depth: 2
title: >-
Toggle the panel update channel between stable and the rolling
per-commit dev release. Only effective on dev builds.
url: >-
#toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
title: Toggle the panel update channel between stable and the rolling per-commit
dev release. Only effective on dev builds.
url: '#toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds'
- depth: 2
title: >-
Refresh the default GeoIP / GeoSite data files. Body can include a
title: Refresh the default GeoIP / GeoSite data files. Body can include a
fileName, or use the /:fileName variant.
url: >-
#refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
url: '#refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant'
- depth: 2
title: Refresh a single Geo file by filename (e.g. geoip.dat, geosite.dat).
url: '#refresh-a-single-geo-file-by-filename-eg-geoipdat-geositedat'
@@ -164,205 +123,138 @@ _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
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
url: '#restore-the-panel-db-from-an-uploaded-sqlite-file-multipart-form-field-name-db-the-panel-restarts-after-restore-destructive'
- depth: 2
title: >-
Generate a new ECH (Encrypted Client Hello) keypair and config list for
title: Generate a new ECH (Encrypted Client Hello) keypair and config list for
the given SNI.
url: >-
#generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
url: '#generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni'
- depth: 2
title: >-
Compute the hex SHA-256 of a certificate (DER) for pinning
title: Compute the hex SHA-256 of a certificate (DER) for pinning
(pinnedPeerCertSha256). Provide either a server file path or inline
PEM/DER content.
url: >-
#compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
url: '#compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content'
- depth: 2
title: >-
Run `xray tls ping` against a remote server and return its live
title: Run `xray tls ping` against a remote server and return its live
leaf-certificate SHA-256 hash(es) for pinning (pinnedPeerCertSha256).
url: >-
#run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
url: '#run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256'
- depth: 2
title: >-
Fetch the fully aggregated inbound_client_ips database table. Used by
title: Fetch the fully aggregated inbound_client_ips database table. Used by
nodes to sync recently active IPs across the cluster.
url: >-
#fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
url: '#fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster'
- depth: 2
title: >-
Submit a list of recently active IP timestamps. The panel merges them
title: Submit a list of recently active IP timestamps. The panel merges them
with the existing database to maintain a unified global IP-limit view.
url: >-
#submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
url: '#submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view'
structuredData:
headings:
- content: >-
Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
- content: 'Real-time machine snapshot: CPU, memory, swap, disk, network IO, load
averages, open connections, Xray state. Cached and refreshed every 2
seconds in the background.
id: >-
real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
- content: >-
Reports whether per-client IP limits can be enforced on this host. The
seconds in the background.'
id: real-time-machine-snapshot-cpu-memory-swap-disk-network-io-load-averages-open-connections-xray-state-cached-and-refreshed-every-2-seconds-in-the-background
- content: Reports whether per-client IP limits can be enforced on this host. The
panel uses it to gate the "IP Limit" field, since enforcement depends
on Fail2ban being installed.
id: >-
reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: >-
Legacy: aggregated CPU history. Use /history/cpu/:bucket instead
same data with a uniform {t, v} shape.
id: >-
legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
- content: >-
Aggregated time-series for one metric. Returns an array of {t, v}
id: reports-whether-per-client-ip-limits-can-be-enforced-on-this-host-the-panel-uses-it-to-gate-the-ip-limit-field-since-enforcement-depends-on-fail2ban-being-installed
- content: 'Legacy: aggregated CPU history. Use /history/cpu/:bucket instead —
same data with a uniform {t, v} shape.'
id: legacy-aggregated-cpu-history-use-historycpubucket-instead--same-data-with-a-uniform-t-v-shape
- content: Aggregated time-series for one metric. Returns an array of {t, v}
samples covering the last ~6 hours.
id: >-
aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
- content: >-
Xray runtime metrics state — whether the xray config has a `metrics`
id: aggregated-time-series-for-one-metric-returns-an-array-of-t-v-samples-covering-the-last-6-hours
- content: Xray runtime metrics state — whether the xray config has a `metrics`
block, which expvar keys are flowing, and the current snapshot values
for each. Returns an empty state when metrics are not configured.
id: >-
xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
- content: >-
Time-series history for one Xray runtime metric over the last ~6
hours. Same {t, v} shape as /history/:metric/:bucket.
id: >-
time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
- content: >-
Latest snapshot from the Xray observatory — per-outbound latency,
id: xray-runtime-metrics-state--whether-the-xray-config-has-a-metrics-block-which-expvar-keys-are-flowing-and-the-current-snapshot-values-for-each-returns-an-empty-state-when-metrics-are-not-configured
- content: Time-series history for one Xray runtime metric over the last ~6 hours.
Same {t, v} shape as /history/:metric/:bucket.
id: time-series-history-for-one-xray-runtime-metric-over-the-last-6-hours-same-t-v-shape-as-historymetricbucket
- content: Latest snapshot from the Xray observatory — per-outbound latency,
health status, and last-probe time. Only populated when the Xray
config has an observatory configured.
id: >-
latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
- content: >-
Time-series of observatory probe results for one outbound tag. Same
{t, v} shape as the other history endpoints.
id: >-
time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
id: latest-snapshot-from-the-xray-observatory--per-outbound-latency-health-status-and-last-probe-time-only-populated-when-the-xray-config-has-an-observatory-configured
- content: Time-series of observatory probe results for one outbound tag. Same {t,
v} shape as the other history endpoints.
id: time-series-of-observatory-probe-results-for-one-outbound-tag-same-t-v-shape-as-the-other-history-endpoints
- content: List Xray binary versions available for install on this host.
id: list-xray-binary-versions-available-for-install-on-this-host
- content: Check whether a newer 3x-ui release is available on GitHub.
id: check-whether-a-newer-3x-ui-release-is-available-on-github
- content: >-
Return the assembled Xray config thats currently running on this
host.
- content: 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
- content: Stream the SQLite database file as an attachment. Use as a manual
backup.
id: >-
stream-the-sqlite-database-file-as-an-attachment-use-as-a-manual-backup
- content: >-
Stream a cross-engine migration file as an attachment: a .dump (SQL
id: stream-the-sqlite-database-file-as-an-attachment-use-as-a-manual-backup
- content: 'Stream a cross-engine migration file as an attachment: a .dump (SQL
text) on SQLite, or a .db SQLite database built from the live data on
PostgreSQL.
id: >-
stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
PostgreSQL.'
id: stream-a-cross-engine-migration-file-as-an-attachment-a-dump-sql-text-on-sqlite-or-a-db-sqlite-database-built-from-the-live-data-on-postgresql
- content: Generate a fresh UUID v4. Convenience helper for client IDs.
id: generate-a-fresh-uuid-v4-convenience-helper-for-client-ids
- content: >-
Return this panel's own web TLS certificate and key file paths. The
- content: Return this panel's own web TLS certificate and key file paths. The
central panel calls it on a node (via the node API token) so "Set Cert
from Panel" fills a node-assigned inbound with paths that exist on the
node.
id: >-
return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
- content: >-
Read-only summaries (guid, parentGuid, name, address, status,
versions) of the nodes this panel manages. A parent panel calls it on
a node (via the node API token) to surface transitive sub-nodes in a
chained topology. Counts are computed by the parent, not returned
here.
id: >-
read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
id: return-this-panels-own-web-tls-certificate-and-key-file-paths-the-central-panel-calls-it-on-a-node-via-the-node-api-token-so-set-cert-from-panel-fills-a-node-assigned-inbound-with-paths-that-exist-on-the-node
- content: Read-only summaries (guid, parentGuid, name, address, status, versions)
of the nodes this panel manages. A parent panel calls it on a node
(via the node API token) to surface transitive sub-nodes in a chained
topology. Counts are computed by the parent, not returned here.
id: read-only-summaries-guid-parentguid-name-address-status-versions-of-the-nodes-this-panel-manages-a-parent-panel-calls-it-on-a-node-via-the-node-api-token-to-surface-transitive-sub-nodes-in-a-chained-topology-counts-are-computed-by-the-parent-not-returned-here
- content: Generate a new X25519 keypair for Reality.
id: generate-a-new-x25519-keypair-for-reality
- content: >-
Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
- content: Generate a new ML-DSA-65 keypair (post-quantum signature). Returns
{privateKey, publicKey, seed}.
id: >-
generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
- content: >-
Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
id: generate-a-new-ml-dsa-65-keypair-post-quantum-signature-returns-privatekey-publickey-seed
- content: Generate a new ML-KEM-768 keypair (post-quantum KEM). Returns
{clientKey, serverKey}.
id: >-
generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
- content: >-
Generate VLESS encryption auth options. Returns an auths array each
id: generate-a-new-ml-kem-768-keypair-post-quantum-kem-returns-clientkey-serverkey
- content: Generate VLESS encryption auth options. Returns an auths array each
with id, label, encryption, and decryption fields.
id: >-
generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
id: generate-vless-encryption-auth-options-returns-an-auths-array-each-with-id-label-encryption-and-decryption-fields
- content: Stop the Xray binary. All proxies go offline immediately.
id: stop-the-xray-binary-all-proxies-go-offline-immediately
- content: >-
Reload Xray with the current config. Typically required after
- content: Reload Xray with the current config. Typically required after
structural inbound or routing changes.
id: >-
reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
- content: >-
Download and install the specified Xray version. Pass "latest" for the
id: reload-xray-with-the-current-config-typically-required-after-structural-inbound-or-routing-changes
- content: Download and install the specified Xray version. Pass "latest" for the
newest release.
id: >-
download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
- content: >-
Self-update the panel to the latest version. The server restarts on
id: download-and-install-the-specified-xray-version-pass-latest-for-the-newest-release
- content: Self-update the panel to the latest version. The server restarts on
success.
id: >-
self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
- content: >-
Toggle the panel update channel between stable and the rolling
id: self-update-the-panel-to-the-latest-version-the-server-restarts-on-success
- content: Toggle the panel update channel between stable and the rolling
per-commit dev release. Only effective on dev builds.
id: >-
toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
- content: >-
Refresh the default GeoIP / GeoSite data files. Body can include a
id: toggle-the-panel-update-channel-between-stable-and-the-rolling-per-commit-dev-release-only-effective-on-dev-builds
- content: Refresh the default GeoIP / GeoSite data files. Body can include a
fileName, or use the /:fileName variant.
id: >-
refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
id: refresh-the-default-geoip--geosite-data-files-body-can-include-a-filename-or-use-the-filename-variant
- content: Refresh a single Geo file by filename (e.g. geoip.dat, geosite.dat).
id: refresh-a-single-geo-file-by-filename-eg-geoipdat-geositedat
- content: Return the last N lines of the panels own log.
id: return-the-last-n-lines-of-the-panels-own-log
- content: Return the last N lines of the Xray process log.
id: return-the-last-n-lines-of-the-xray-process-log
- content: >-
Restore the panel DB from an uploaded SQLite file (multipart form,
- content: Restore the panel DB from an uploaded SQLite file (multipart form,
field name "db"). The panel restarts after restore. Destructive.
id: >-
restore-the-panel-db-from-an-uploaded-sqlite-file-multipart-form-field-name-db-the-panel-restarts-after-restore-destructive
- content: >-
Generate a new ECH (Encrypted Client Hello) keypair and config list
for the given SNI.
id: >-
generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
- content: >-
Compute the hex SHA-256 of a certificate (DER) for pinning
id: restore-the-panel-db-from-an-uploaded-sqlite-file-multipart-form-field-name-db-the-panel-restarts-after-restore-destructive
- content: Generate a new ECH (Encrypted Client Hello) keypair and config list for
the given SNI.
id: generate-a-new-ech-encrypted-client-hello-keypair-and-config-list-for-the-given-sni
- content: Compute the hex SHA-256 of a certificate (DER) for pinning
(pinnedPeerCertSha256). Provide either a server file path or inline
PEM/DER content.
id: >-
compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
- content: >-
Run `xray tls ping` against a remote server and return its live
id: compute-the-hex-sha-256-of-a-certificate-der-for-pinning-pinnedpeercertsha256-provide-either-a-server-file-path-or-inline-pemder-content
- content: Run `xray tls ping` against a remote server and return its live
leaf-certificate SHA-256 hash(es) for pinning (pinnedPeerCertSha256).
id: >-
run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
- content: >-
Fetch the fully aggregated inbound_client_ips database table. Used by
id: run-xray-tls-ping-against-a-remote-server-and-return-its-live-leaf-certificate-sha-256-hashes-for-pinning-pinnedpeercertsha256
- content: Fetch the fully aggregated inbound_client_ips database table. Used by
nodes to sync recently active IPs across the cluster.
id: >-
fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
- content: >-
Submit a list of recently active IP timestamps. The panel merges them
id: fetch-the-fully-aggregated-inbound_client_ips-database-table-used-by-nodes-to-sync-recently-active-ips-across-the-cluster
- content: Submit a list of recently active IP timestamps. The panel merges them
with the existing database to maintain a unified global IP-limit view.
id: >-
submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
id: submit-a-list-of-recently-active-ip-timestamps-the-panel-merges-them-with-the-existing-database-to-maintain-a-unified-global-ip-limit-view
contents: []
---
+37 -70
View File
@@ -1,7 +1,6 @@
---
title: Settings
description: >-
Panel configuration and user credentials. All endpoints live under
description: Panel configuration and user credentials. All endpoints live under
/panel/api/setting and require a logged-in session or Bearer token.
full: true
_openapi:
@@ -9,101 +8,69 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.
url: >-
#return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
title: 'Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.'
url: '#return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits'
- depth: 2
title: >-
Return the computed default settings based on the request host. Useful
to preview what a fresh install would use.
url: >-
#return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
title: Return the computed default settings based on the request host. Useful to
preview what a fresh install would use.
url: '#return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use'
- depth: 2
title: >-
Persist every setting at once. The body mirrors the shape returned by
title: Persist every setting at once. The body mirrors the shape returned by
/all. Invalid values (bad ports, missing cert pairs, etc.) are rejected
before write.
url: >-
#persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
url: '#persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write'
- depth: 2
title: >-
Change the panel admin username and password. Requires the current
title: Change the panel admin username and password. Requires the current
credentials for verification. The session is refreshed with the new
values on success.
url: >-
#change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
url: '#change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success'
- depth: 2
title: >-
Restart the entire 3x-ui process after a 3-second grace period. The
title: Restart the entire 3x-ui process after a 3-second grace period. The
connection drops immediately; the panel comes back online ~5-10 seconds
later.
url: >-
#restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
url: '#restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later'
- depth: 2
title: >-
Test SMTP connection with stage-by-stage reporting (connect, auth,
send). Returns structured result with stage and message.
url: >-
#test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
title: Test SMTP connection with stage-by-stage reporting (connect, auth, send).
Returns structured result with stage and message.
url: '#test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message'
- depth: 2
title: >-
Test Telegram bot connection by sending a test message to the configured
title: Test Telegram bot connection by sending a test message to the configured
chat.
url: >-
#test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
url: '#test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat'
- depth: 2
title: >-
Return the built-in default Xray JSON config template that ships with
title: Return the built-in default Xray JSON config template that ships with
this panel version.
url: >-
#return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
url: '#return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version'
structuredData:
headings:
- content: >-
Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.
id: >-
return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
- content: >-
Return the computed default settings based on the request host. Useful
- content: 'Return every panel setting: web server, Telegram bot, subscription,
security, LDAP. The full JSON blob that the Settings page edits.'
id: return-every-panel-setting-web-server-telegram-bot-subscription-security-ldap-the-full-json-blob-that-the-settings-page-edits
- content: Return the computed default settings based on the request host. Useful
to preview what a fresh install would use.
id: >-
return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
- content: >-
Persist every setting at once. The body mirrors the shape returned by
id: return-the-computed-default-settings-based-on-the-request-host-useful-to-preview-what-a-fresh-install-would-use
- content: Persist every setting at once. The body mirrors the shape returned by
/all. Invalid values (bad ports, missing cert pairs, etc.) are
rejected before write.
id: >-
persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
- content: >-
Change the panel admin username and password. Requires the current
id: persist-every-setting-at-once-the-body-mirrors-the-shape-returned-by-all-invalid-values-bad-ports-missing-cert-pairs-etc-are-rejected-before-write
- content: Change the panel admin username and password. Requires the current
credentials for verification. The session is refreshed with the new
values on success.
id: >-
change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
- content: >-
Restart the entire 3x-ui process after a 3-second grace period. The
id: change-the-panel-admin-username-and-password-requires-the-current-credentials-for-verification-the-session-is-refreshed-with-the-new-values-on-success
- content: Restart the entire 3x-ui process after a 3-second grace period. The
connection drops immediately; the panel comes back online ~5-10
seconds later.
id: >-
restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
- content: >-
Test SMTP connection with stage-by-stage reporting (connect, auth,
id: restart-the-entire-3x-ui-process-after-a-3-second-grace-period-the-connection-drops-immediately-the-panel-comes-back-online-5-10-seconds-later
- content: Test SMTP connection with stage-by-stage reporting (connect, auth,
send). Returns structured result with stage and message.
id: >-
test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
- content: >-
Test Telegram bot connection by sending a test message to the
id: test-smtp-connection-with-stage-by-stage-reporting-connect-auth-send-returns-structured-result-with-stage-and-message
- content: Test Telegram bot connection by sending a test message to the
configured chat.
id: >-
test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
- content: >-
Return the built-in default Xray JSON config template that ships with
id: test-telegram-bot-connection-by-sending-a-test-message-to-the-configured-chat
- content: Return the built-in default Xray JSON config template that ships with
this panel version.
id: >-
return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
contents: []
---
@@ -1,59 +1,46 @@
---
title: Subscription Server
description: >-
A separate HTTP/HTTPS server that serves proxy subscription links (standard,
JSON, and Clash) to clients. The server listens on its own port (default
10882) and is configured in Settings → Subscription. Paths are configurable;
defaults are shown below. All subscription endpoints set response headers for
client apps to read traffic/expiry info.
description: A separate HTTP/HTTPS server that serves proxy subscription links
(standard, JSON, and Clash) to clients. The server listens on its own port
(default 10882) and is configured in Settings → Subscription. Paths are
configurable; defaults are shown below. All subscription endpoints set
response headers for client apps to read traffic/expiry info.
full: true
_openapi:
preload:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return base64-encoded subscription links for all enabled clients
title: 'Return base64-encoded subscription links for all enabled clients
matching the subscription ID. When the request has an Accept: text/html
header or ?html=1, renders a styled info page instead. Default path:
/sub/:subid.
url: >-
#return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-default-path-subsubid
/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'
- depth: 2
title: >-
Return subscription as a JSON array of proxy configs (one per enabled
title: 'Return subscription as a JSON array of proxy configs (one per enabled
client). Only when JSON subscription is enabled in settings. Default
path: /json/:subid.
url: >-
#return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
path: /json/:subid.'
url: '#return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid'
- depth: 2
title: >-
Return subscription as a Clash/Mihomo-compatible YAML config, including
title: 'Return subscription as a Clash/Mihomo-compatible YAML config, including
configured global Clash routing rules. Only when Clash subscription is
enabled in settings. Default path: /clash/:subid.
url: >-
#return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
enabled in settings. Default path: /clash/:subid.'
url: '#return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid'
structuredData:
headings:
- content: >-
Return base64-encoded subscription links for all enabled clients
- content: 'Return base64-encoded subscription links for all enabled clients
matching the subscription ID. When the request has an Accept:
text/html header or ?html=1, renders a styled info page instead.
Default path: /sub/:subid.
id: >-
return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-default-path-subsubid
- content: >-
Return subscription as a JSON array of proxy configs (one per enabled
Default path: /sub/:subid.'
id: return-base64-encoded-subscription-links-for-all-enabled-clients-matching-the-subscription-id-when-the-request-has-an-accept-texthtml-header-or-html1-renders-a-styled-info-page-instead-default-path-subsubid
- content: 'Return subscription as a JSON array of proxy configs (one per enabled
client). Only when JSON subscription is enabled in settings. Default
path: /json/:subid.
id: >-
return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
- content: >-
Return subscription as a Clash/Mihomo-compatible YAML config,
path: /json/:subid.'
id: return-subscription-as-a-json-array-of-proxy-configs-one-per-enabled-client-only-when-json-subscription-is-enabled-in-settings-default-path-jsonsubid
- content: 'Return subscription as a Clash/Mihomo-compatible YAML config,
including configured global Clash routing rules. Only when Clash
subscription is enabled in settings. Default path: /clash/:subid.
id: >-
return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
subscription is enabled in settings. Default path: /clash/:subid.'
id: return-subscription-as-a-clashmihomo-compatible-yaml-config-including-configured-global-clash-routing-rules-only-when-clash-subscription-is-enabled-in-settings-default-path-clashsubid
contents: []
---
@@ -1,7 +1,6 @@
---
title: WebSocket
description: >-
Real-time status updates via WebSocket. Connect once at
description: Real-time status updates via WebSocket. Connect once at
<code>ws://<panel>/ws</code> to receive a stream of JSON messages without
polling. Requires an authenticated session cookie (Bearer token auth is not
supported). Each message has a <code>type</code> field that identifies the
@@ -12,22 +11,18 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Upgrade an HTTP connection to a WebSocket. Requires an authenticated
title: Upgrade an HTTP connection to a WebSocket. Requires an authenticated
session cookie (Bearer token auth is not supported here). Returns 101
Switching Protocols on success. The server then pushes JSON messages
described below.
url: >-
#upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
url: '#upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below'
structuredData:
headings:
- content: >-
Upgrade an HTTP connection to a WebSocket. Requires an authenticated
- content: Upgrade an HTTP connection to a WebSocket. Requires an authenticated
session cookie (Bearer token auth is not supported here). Returns 101
Switching Protocols on success. The server then pushes JSON messages
described below.
id: >-
upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
id: upgrade-an-http-connection-to-a-websocket-requires-an-authenticated-session-cookie-bearer-token-auth-is-not-supported-here-returns-101-switching-protocols-on-success-the-server-then-pushes-json-messages-described-below
contents: []
---
@@ -1,7 +1,7 @@
---
title: Xray Settings
description: >-
Xray configuration template, outbound management, Warp/Nord integration, and
Xray configuration template, outbound management, Warp/Nord/PIA integration, and
config testing. All endpoints under /panel/api/xray.
full: true
_openapi:
@@ -9,236 +9,168 @@ _openapi:
- ./public/openapi.json
toc:
- depth: 2
title: >-
Return the Xray config template (JSON string), available inbound tags,
title: Return the Xray config template (JSON string), available inbound tags,
client reverse tags, and the configured outbound test URL in one
response.
url: >-
#return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
url: '#return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response'
- depth: 2
title: >-
Return the built-in default Xray config shipped with the panel
(identical to /panel/api/setting/getDefaultJsonConfig).
url: >-
#return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
title: Return the built-in default Xray config shipped with the panel (identical
to /panel/api/setting/getDefaultJsonConfig).
url: '#return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig'
- depth: 2
title: >-
Return traffic statistics for every outbound. Each outbound shows
title: Return traffic statistics for every outbound. Each outbound shows
up/down/total counters.
url: >-
#return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
url: '#return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters'
- depth: 2
title: >-
Return the most recent Xray process stdout/stderr output. Useful to
check for startup errors or runtime warnings.
url: >-
#return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
title: Return the most recent Xray process stdout/stderr output. Useful to check
for startup errors or runtime warnings.
url: '#return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings'
- depth: 2
title: >-
Save the Xray JSON config template and optionally the outbound test URL.
title: Save the Xray JSON config template and optionally the outbound test URL.
Both are sent as form fields.
url: >-
#save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
url: '#save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields'
- depth: 2
title: >-
Manage Cloudflare Warp integration. The action parameter selects the
title: Manage Cloudflare Warp integration. The action parameter selects the
operation.
url: >-
#manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
url: '#manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Manage NordVPN integration. The action parameter selects the operation.
url: '#manage-nordvpn-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Manage PIA WireGuard integration. The action parameter selects the operation.
url: '#manage-pia-wireguard-integration-the-action-parameter-selects-the-operation'
- depth: 2
title: Reset traffic counters for a specific outbound by tag.
url: '#reset-traffic-counters-for-a-specific-outbound-by-tag'
- depth: 2
title: >-
Test an outbound configuration. Sends the outbound JSON (required),
title: Test an outbound configuration. Sends the outbound JSON (required),
optionally all outbounds (to resolve sockopt.dialerProxy dependencies),
and a mode flag.
url: >-
#test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
url: '#test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag'
- depth: 2
title: >-
Test a batch of outbounds (max 50) through one shared temp xray
instance. Returns an array of results in input order, each with the
outbound tag, delay, HTTP status and a connect/TLS/TTFB timing
breakdown.
url: >-
#test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
title: Test a batch of outbounds (max 50) through one shared temp xray instance.
Returns an array of results in input order, each with the outbound tag,
delay, HTTP status and a connect/TLS/TTFB timing breakdown.
url: '#test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown'
- depth: 2
title: >-
Live state of routing balancers in the running core
title: 'Live state of routing balancers in the running core
(RoutingService.GetBalancerInfo): current override and the targets the
strategy prefers. Returns a map keyed by balancer tag.
url: >-
#live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
strategy prefers. Returns a map keyed by balancer tag.'
url: '#live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag'
- depth: 2
title: >-
Force a balancer in the running core to always pick one outbound
title: Force a balancer in the running core to always pick one outbound
(RoutingService.OverrideBalancerTarget). Applied live without a restart;
cleared automatically when Xray restarts.
url: >-
#force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
url: '#force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts'
- depth: 2
title: >-
Ask the running core which outbound its router would pick for a
synthetic connection (RoutingService.TestRoute). No traffic is sent.
url: >-
#ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
title: Ask the running core which outbound its router would pick for a synthetic
connection (RoutingService.TestRoute). No traffic is sent.
url: '#ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent'
- depth: 2
title: >-
List all outbound subscriptions (remote URLs that supply additional
title: List all outbound subscriptions (remote URLs that supply additional
outbounds), newest first.
url: >-
#list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
url: '#list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first'
- depth: 2
title: >-
Create an outbound subscription. The URL is fetched, parsed into
title: Create an outbound subscription. The URL is fetched, parsed into
outbounds with stable tags, and merged additively into the running Xray
config.
url: >-
#create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
url: '#create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config'
- depth: 2
title: >-
Update an existing outbound subscription by id. Accepts the same form
title: Update an existing outbound subscription by id. Accepts the same form
fields as create.
url: >-
#update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
url: '#update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create'
- depth: 2
title: Delete an outbound subscription by id.
url: '#delete-an-outbound-subscription-by-id'
- depth: 2
title: >-
Delete an outbound subscription by id (POST alias of DELETE for
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
url: '#delete-an-outbound-subscription-by-id-post-alias-of-delete-for-axios-friendly-clients'
- depth: 2
title: >-
Force an immediate re-fetch of the subscription and return the parsed
title: Force an immediate re-fetch of the subscription and return the parsed
outbounds. Signals Xray to reload.
url: >-
#force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
url: '#force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload'
- depth: 2
title: >-
Reorder a subscription one step up or down in priority (controls its
title: Reorder a subscription one step up or down in priority (controls its
position in the merged outbounds).
url: >-
#reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
url: '#reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds'
- depth: 2
title: >-
Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.
url: >-
#preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
title: 'Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.'
url: '#preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything'
structuredData:
headings:
- content: >-
Return the Xray config template (JSON string), available inbound tags,
- content: Return the Xray config template (JSON string), available inbound tags,
client reverse tags, and the configured outbound test URL in one
response.
id: >-
return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
- content: >-
Return the built-in default Xray config shipped with the panel
id: return-the-xray-config-template-json-string-available-inbound-tags-client-reverse-tags-and-the-configured-outbound-test-url-in-one-response
- content: Return the built-in default Xray config shipped with the panel
(identical to /panel/api/setting/getDefaultJsonConfig).
id: >-
return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
- content: >-
Return traffic statistics for every outbound. Each outbound shows
id: return-the-built-in-default-xray-config-shipped-with-the-panel-identical-to-panelapisettinggetdefaultjsonconfig
- content: Return traffic statistics for every outbound. Each outbound shows
up/down/total counters.
id: >-
return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
- content: >-
Return the most recent Xray process stdout/stderr output. Useful to
id: return-traffic-statistics-for-every-outbound-each-outbound-shows-updowntotal-counters
- content: Return the most recent Xray process stdout/stderr output. Useful to
check for startup errors or runtime warnings.
id: >-
return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
- content: >-
Save the Xray JSON config template and optionally the outbound test
id: return-the-most-recent-xray-process-stdoutstderr-output-useful-to-check-for-startup-errors-or-runtime-warnings
- content: Save the Xray JSON config template and optionally the outbound test
URL. Both are sent as form fields.
id: >-
save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
- content: >-
Manage Cloudflare Warp integration. The action parameter selects the
operation.
id: >-
manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
- content: >-
Manage NordVPN integration. The action parameter selects the
id: save-the-xray-json-config-template-and-optionally-the-outbound-test-url-both-are-sent-as-form-fields
- content: Manage Cloudflare Warp integration. The action parameter selects the
operation.
id: manage-cloudflare-warp-integration-the-action-parameter-selects-the-operation
- content: Manage NordVPN integration. The action parameter selects the operation.
id: manage-nordvpn-integration-the-action-parameter-selects-the-operation
- content: >-
Manage PIA WireGuard integration. The action parameter selects the
operation.
id: manage-pia-wireguard-integration-the-action-parameter-selects-the-operation
- content: Reset traffic counters for a specific outbound by tag.
id: reset-traffic-counters-for-a-specific-outbound-by-tag
- content: >-
Test an outbound configuration. Sends the outbound JSON (required),
- content: Test an outbound configuration. Sends the outbound JSON (required),
optionally all outbounds (to resolve sockopt.dialerProxy
dependencies), and a mode flag.
id: >-
test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
- content: >-
Test a batch of outbounds (max 50) through one shared temp xray
id: test-an-outbound-configuration-sends-the-outbound-json-required-optionally-all-outbounds-to-resolve-sockoptdialerproxy-dependencies-and-a-mode-flag
- content: Test a batch of outbounds (max 50) through one shared temp xray
instance. Returns an array of results in input order, each with the
outbound tag, delay, HTTP status and a connect/TLS/TTFB timing
breakdown.
id: >-
test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
- content: >-
Live state of routing balancers in the running core
id: test-a-batch-of-outbounds-max-50-through-one-shared-temp-xray-instance-returns-an-array-of-results-in-input-order-each-with-the-outbound-tag-delay-http-status-and-a-connecttlsttfb-timing-breakdown
- content: 'Live state of routing balancers in the running core
(RoutingService.GetBalancerInfo): current override and the targets the
strategy prefers. Returns a map keyed by balancer tag.
id: >-
live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
- content: >-
Force a balancer in the running core to always pick one outbound
strategy prefers. Returns a map keyed by balancer tag.'
id: live-state-of-routing-balancers-in-the-running-core-routingservicegetbalancerinfo-current-override-and-the-targets-the-strategy-prefers-returns-a-map-keyed-by-balancer-tag
- content: Force a balancer in the running core to always pick one outbound
(RoutingService.OverrideBalancerTarget). Applied live without a
restart; cleared automatically when Xray restarts.
id: >-
force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
- content: >-
Ask the running core which outbound its router would pick for a
id: force-a-balancer-in-the-running-core-to-always-pick-one-outbound-routingserviceoverridebalancertarget-applied-live-without-a-restart-cleared-automatically-when-xray-restarts
- content: Ask the running core which outbound its router would pick for a
synthetic connection (RoutingService.TestRoute). No traffic is sent.
id: >-
ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
- content: >-
List all outbound subscriptions (remote URLs that supply additional
id: ask-the-running-core-which-outbound-its-router-would-pick-for-a-synthetic-connection-routingservicetestroute-no-traffic-is-sent
- content: List all outbound subscriptions (remote URLs that supply additional
outbounds), newest first.
id: >-
list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
- content: >-
Create an outbound subscription. The URL is fetched, parsed into
id: list-all-outbound-subscriptions-remote-urls-that-supply-additional-outbounds-newest-first
- content: Create an outbound subscription. The URL is fetched, parsed into
outbounds with stable tags, and merged additively into the running
Xray config.
id: >-
create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
- content: >-
Update an existing outbound subscription by id. Accepts the same form
id: create-an-outbound-subscription-the-url-is-fetched-parsed-into-outbounds-with-stable-tags-and-merged-additively-into-the-running-xray-config
- content: Update an existing outbound subscription by id. Accepts the same form
fields as create.
id: >-
update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
id: update-an-existing-outbound-subscription-by-id-accepts-the-same-form-fields-as-create
- content: Delete an outbound subscription by id.
id: delete-an-outbound-subscription-by-id
- content: >-
Delete an outbound subscription by id (POST alias of DELETE for
- content: Delete an outbound subscription by id (POST alias of DELETE for
axios-friendly clients).
id: >-
delete-an-outbound-subscription-by-id-post-alias-of-delete-for-axios-friendly-clients
- content: >-
Force an immediate re-fetch of the subscription and return the parsed
id: delete-an-outbound-subscription-by-id-post-alias-of-delete-for-axios-friendly-clients
- content: Force an immediate re-fetch of the subscription and return the parsed
outbounds. Signals Xray to reload.
id: >-
force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
- content: >-
Reorder a subscription one step up or down in priority (controls its
id: force-an-immediate-re-fetch-of-the-subscription-and-return-the-parsed-outbounds-signals-xray-to-reload
- content: Reorder a subscription one step up or down in priority (controls its
position in the merged outbounds).
id: >-
reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
- content: >-
Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.
id: >-
preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
id: reorder-a-subscription-one-step-up-or-down-in-priority-controls-its-position-in-the-merged-outbounds
- content: 'Preview a subscription URL: fetch and parse it into outbounds without
persisting anything.'
id: preview-a-subscription-url-fetch-and-parse-it-into-outbounds-without-persisting-anything
contents: []
---
@@ -251,7 +183,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/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,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,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. */}
+22 -22
View File
@@ -22,28 +22,28 @@ The panel uses standard Go `html/template` to render the subscription page.
When rendering the template, the following variables are injected into the template context (`{{ .variable }}`):
* `{{ .sId }}`: Subscription ID (UUID).
* `{{ .enabled }}`: Whether the subscription/client is enabled (boolean).
* `{{ .isOnline }}`: Whether the subscription's client has a live connection right now (boolean). Computed from the panel's online-client tracking (local Xray plus any remote nodes) at render time.
* `{{ .download }}`: Formatted download traffic (e.g. "2.5 GB").
* `{{ .upload }}`: Formatted upload traffic.
* `{{ .total }}`: Formatted total traffic limit.
* `{{ .used }}`: Formatted used traffic (download + upload).
* `{{ .remained }}`: Formatted remaining traffic.
* `{{ .expire }}`: Expiration time as an int64 Unix timestamp in **seconds** (`0` means never). Multiply by 1000 for a JavaScript `Date`.
* `{{ .lastOnline }}`: Last online time as an int64 Unix timestamp in **milliseconds** (`0` means never seen).
* `{{ .downloadByte }}`: Download traffic in exact bytes (int64).
* `{{ .uploadByte }}`: Upload traffic in exact bytes (int64).
* `{{ .totalByte }}`: Total traffic limit in exact bytes (int64).
* `{{ .subUrl }}`: The URL of the subscription page.
* `{{ .subJsonUrl }}`: The URL for the JSON configuration of the subscription.
* `{{ .subClashUrl }}`: The URL for the Clash/Mihomo configuration.
* `{{ .subTitle }}`: The subscription title configured in the panel (Subscription → Information). Useful for page branding/headings. May be empty.
* `{{ .subSupportUrl }}`: The support URL configured in the panel. Useful for a "Contact support" link. May be empty.
* `{{ .links }}`: A list (slice) of string configurations (VMess, VLESS, etc. URLs). You can loop through them using `{{ range .links }} ... {{ end }}`.
* `{{ .emails }}`: A list (slice) of client emails, parallel to `links` — the email at index *i* owns the link at index *i*. May contain duplicates when one client has several links.
* `{{ .announce }}`: The announcement text configured in the panel (Settings → Subscription → Announce). May be empty.
* `{{ .datepicker }}`: Current calendar format used by the panel (e.g. "gregorian" or "jalali").
- `{{ .sId }}`: Subscription ID (UUID).
- `{{ .enabled }}`: Whether the subscription/client is enabled (boolean).
- `{{ .isOnline }}`: Whether the subscription's client has a live connection right now (boolean). Computed from the panel's online-client tracking (local Xray plus any remote nodes) at render time.
- `{{ .download }}`: Formatted download traffic (e.g. "2.5 GB").
- `{{ .upload }}`: Formatted upload traffic.
- `{{ .total }}`: Formatted total traffic limit.
- `{{ .used }}`: Formatted used traffic (download + upload).
- `{{ .remained }}`: Formatted remaining traffic.
- `{{ .expire }}`: Expiration time as an int64 Unix timestamp in **seconds** (`0` means never). Multiply by 1000 for a JavaScript `Date`.
- `{{ .lastOnline }}`: Last online time as an int64 Unix timestamp in **milliseconds** (`0` means never seen).
- `{{ .downloadByte }}`: Download traffic in exact bytes (int64).
- `{{ .uploadByte }}`: Upload traffic in exact bytes (int64).
- `{{ .totalByte }}`: Total traffic limit in exact bytes (int64).
- `{{ .subUrl }}`: The URL of the subscription page.
- `{{ .subJsonUrl }}`: The URL for the JSON configuration of the subscription.
- `{{ .subClashUrl }}`: The URL for the Clash/Mihomo configuration.
- `{{ .subTitle }}`: The subscription title configured in the panel (Subscription → Information). Useful for page branding/headings. May be empty.
- `{{ .subSupportUrl }}`: The support URL configured in the panel. Useful for a "Contact support" link. May be empty.
- `{{ .links }}`: A list (slice) of string configurations (VMess, VLESS, etc. URLs). You can loop through them using `{{ range .links }} ... {{ end }}`.
- `{{ .emails }}`: A list (slice) of client emails, parallel to `links` — the email at index _i_ owns the link at index _i_. May contain duplicates when one client has several links.
- `{{ .announce }}`: The announcement text configured in the panel (Settings → Subscription → Announce). May be empty.
- `{{ .datepicker }}`: Current calendar format used by the panel (e.g. "gregorian" or "jalali").
## Live Status JSON (`?format=info`)
-21
View File
@@ -1,21 +0,0 @@
import coreWebVitals from 'eslint-config-next/core-web-vitals';
import typescript from 'eslint-config-next/typescript';
/** @type {import('eslint').Linter.Config[]} */
const config = [
{
ignores: [
'.next/**',
'.source/**',
'out/**',
'node_modules/**',
'next-env.d.ts',
// Generated API reference pages (fumadocs-openapi output)
'content/docs/**/reference/api/**',
],
},
...coreWebVitals,
...typescript,
];
export default config;
+12 -1
View File
@@ -2,7 +2,15 @@ import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
import { Heart } from 'lucide-react';
import { Logo } from '@/components/logo';
import { TelegramIcon } from '@/components/icons';
import { appName, productRepoUrl, telegramChannel, telegramChannelUrl, donateUrl, siteUrl } from './shared';
import { DocsThemeSwitch } from '@/components/theme-switch';
import {
appName,
productRepoUrl,
telegramChannel,
telegramChannelUrl,
donateUrl,
siteUrl,
} from './shared';
import { getSiteMessages } from './site-i18n';
// Build locale-aware shared layout options. With `hideLocale: 'default-locale'`,
@@ -12,6 +20,9 @@ export function baseOptions(lang: string): BaseLayoutProps {
const m = getSiteMessages(lang);
return {
slots: {
themeSwitch: DocsThemeSwitch,
},
nav: {
title: (
<span className="inline-flex items-center gap-2 font-semibold">
+2 -1
View File
@@ -222,7 +222,8 @@ const zh: SiteMessages = {
},
{
title: '自托管且可脚本化',
description: '单个 Go 二进制文件或 Docker 镜像、SQLite/PostgreSQL 后端,以及用于自动化的完整 REST API。',
description:
'单个 Go 二进制文件或 Docker 镜像、SQLite/PostgreSQL 后端,以及用于自动化的完整 REST API。',
},
],
licenseBefore: '基于 ',
+20 -6
View File
@@ -31,7 +31,7 @@ const base = {
describe('buildCurl', () => {
it('GET emits the Bearer header, a single-quoted URL, and no body flag', () => {
const cmd = buildCurl({ ...base, method: 'GET' });
expect(cmd).toContain("-X GET");
expect(cmd).toContain('-X GET');
expect(cmd).toContain("-H 'Authorization: Bearer TKN'");
expect(cmd).toContain("'https://panel.example.com:2053/panel/api/inbounds/list'");
expect(cmd).not.toContain('--data');
@@ -39,14 +39,23 @@ describe('buildCurl', () => {
});
it('POST with a body emits --data and a JSON content type', () => {
const cmd = buildCurl({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
const cmd = buildCurl({
...base,
method: 'POST',
path: '/panel/api/inbounds/add',
body: '{"up":0}',
});
expect(cmd).toContain('-X POST');
expect(cmd).toContain("--data '{\"up\":0}'");
expect(cmd).toContain("Content-Type: application/json");
expect(cmd).toContain('--data \'{"up":0}\'');
expect(cmd).toContain('Content-Type: application/json');
});
it('POST without a body omits --data', () => {
const cmd = buildCurl({ ...base, method: 'POST', path: '/panel/api/inbounds/resetAllTraffics' });
const cmd = buildCurl({
...base,
method: 'POST',
path: '/panel/api/inbounds/resetAllTraffics',
});
expect(cmd).not.toContain('--data');
});
});
@@ -60,7 +69,12 @@ describe('buildFetchSnippet', () => {
});
it('POST with a body includes a JSON.stringify body', () => {
const snip = buildFetchSnippet({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
const snip = buildFetchSnippet({
...base,
method: 'POST',
path: '/panel/api/inbounds/add',
body: '{"up":0}',
});
expect(snip).toContain("method: 'POST'");
expect(snip).toContain('body: JSON.stringify(');
});
+6 -1
View File
@@ -160,7 +160,12 @@ describe('buildOutbound — wireguard & warp', () => {
const ob = buildOutbound({
kind: 'wireguard',
tag: 'wg',
wireguard: { secretKey: 'sk', address: ['10.0.0.2/32'], publicKey: 'pk', endpoint: 'host:51820' },
wireguard: {
secretKey: 'sk',
address: ['10.0.0.2/32'],
publicKey: 'pk',
endpoint: 'host:51820',
},
});
const s = ob.settings as Record<string, unknown>;
expect(s.secretKey).toBe('sk');
+5 -1
View File
@@ -162,7 +162,11 @@ function buildSettings(o: OutboundInput): Record<string, unknown> {
],
};
case 'trojan':
return { servers: [{ address: s?.address ?? '', port: toPort(s?.port), password: s?.password ?? '' }] };
return {
servers: [
{ address: s?.address ?? '', port: toPort(s?.port), password: s?.password ?? '' },
],
};
case 'shadowsocks':
return {
servers: [
+6 -1
View File
@@ -18,7 +18,12 @@ describe('buildBalancer', () => {
});
it('includes fallbackTag when set', () => {
const b = buildBalancer({ tag: 'lb', selector: ['a'], strategy: 'random', fallbackTag: 'direct' });
const b = buildBalancer({
tag: 'lb',
selector: ['a'],
strategy: 'random',
fallbackTag: 'direct',
});
expect(b.fallbackTag).toBe('direct');
});
});
+4 -1
View File
@@ -121,7 +121,10 @@ export function buildRouting(input: RoutingInput): Record<string, unknown> {
if (input.observatory) {
Object.assign(out, buildObservatory(input.observatory));
} else if (input.balancers.some((b) => b.strategy === 'leastLoad')) {
Object.assign(out, buildObservatory({ mode: 'burst', subjectSelector: uniqueSelectors(input.balancers) }));
Object.assign(
out,
buildObservatory({ mode: 'burst', subjectSelector: uniqueSelectors(input.balancers) }),
);
} else if (input.balancers.some((b) => b.strategy === 'leastPing')) {
Object.assign(
out,
+10 -2
View File
@@ -214,12 +214,20 @@ function proxyOutbound(c: SubClient): Record<string, unknown> {
};
break;
case 'trojan':
settings = { servers: [{ address: c.address, port: c.port, password: c.password ?? '', level: 8 }] };
settings = {
servers: [{ address: c.address, port: c.port, password: c.password ?? '', level: 8 }],
};
break;
case 'ss':
settings = {
servers: [
{ address: c.address, port: c.port, password: c.password ?? '', level: 8, method: c.method || '' },
{
address: c.address,
port: c.port,
password: c.password ?? '',
level: 8,
method: c.method || '',
},
],
};
break;
+12 -5
View File
@@ -36,7 +36,10 @@ describe('parseAdminIds', () => {
});
it('accepts negative group ids and captures invalid entries', () => {
expect(parseAdminIds('-1001234567, abc, 42')).toEqual({ ids: [-1001234567, 42], invalid: ['abc'] });
expect(parseAdminIds('-1001234567, abc, 42')).toEqual({
ids: [-1001234567, 42],
invalid: ['abc'],
});
});
it('returns empty for blank input', () => {
@@ -78,9 +81,9 @@ describe('telegramApiBase', () => {
describe('renderMessageTemplate', () => {
it('substitutes known variables', () => {
expect(renderMessageTemplate('Host {{host}} up {{uptime}}', { host: 'srv', uptime: '3d' })).toBe(
'Host srv up 3d',
);
expect(
renderMessageTemplate('Host {{host}} up {{uptime}}', { host: 'srv', uptime: '3d' }),
).toBe('Host srv up 3d');
});
it('leaves unknown variables literal', () => {
@@ -90,7 +93,11 @@ describe('renderMessageTemplate', () => {
describe('buildBotConfigSummary', () => {
it('emits the panel settings keys with admin ids joined', () => {
const s = buildBotConfigSummary({ token: VALID_TOKEN, adminIds: '111, 222', runTime: '@daily' });
const s = buildBotConfigSummary({
token: VALID_TOKEN,
adminIds: '111, 222',
runTime: '@daily',
});
expect(s.tgBotEnable).toBe(true);
expect(s.tgBotToken).toBe(VALID_TOKEN);
expect(s.tgBotChatId).toBe('111,222');
+4 -1
View File
@@ -43,7 +43,10 @@ export function validateBotToken(token: string): TokenValidation {
export function parseAdminIds(raw: string): AdminIdsResult {
const ids: number[] = [];
const invalid: string[] = [];
for (const part of raw.split(',').map((s) => s.trim()).filter(Boolean)) {
for (const part of raw
.split(',')
.map((s) => s.trim())
.filter(Boolean)) {
// Telegram chat ids are integers; group/channel ids are negative.
if (/^-?\d+$/.test(part)) ids.push(Number(part));
else invalid.push(part);
+20 -21
View File
@@ -11,42 +11,41 @@
"postinstall": "fumadocs-mdx",
"gen:api": "node scripts/gen-openapi.ts",
"typecheck": "fumadocs-mdx && next typegen && tsc --noEmit",
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "oxlint .",
"format": "oxfmt .",
"format:check": "oxfmt --check .",
"test": "vitest run",
"test:watch": "vitest"
},
"dependencies": {
"@orama/orama": "^3.1.18",
"fumadocs-core": "^16.11.5",
"fumadocs-core": "^16.14.5",
"fumadocs-docgen": "^3.1.0",
"fumadocs-mdx": "^15.2.0",
"fumadocs-openapi": "^11.2.2",
"fumadocs-ui": "^16.11.5",
"lucide-react": "^1.25.0",
"mermaid": "^11.16.0",
"next": "16.2.11",
"fumadocs-mdx": "^15.3.0",
"fumadocs-openapi": "^11.2.4",
"fumadocs-ui": "^16.14.5",
"lucide-react": "^1.33.0",
"mermaid": "^11.17.0",
"next": "16.3.1",
"next-themes": "^0.4.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-qr-code": "^2.2.0",
"tailwind-merge": "^3.6.0",
"zbsearch": "4.0.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.3",
"@types/mdx": "^2.0.14",
"@types/node": "^26.1.1",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"eslint": "^9.39.5",
"eslint-config-next": "16.2.11",
"postcss": "^8.5.21",
"prettier": "^3.9.6",
"@types/node": "^26.2.0",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"oxfmt": "0.64.0",
"oxlint": "1.79.0",
"postcss": "^8.5.26",
"tailwindcss": "^4.3.3",
"typescript": "^6.0.3",
"vitest": "^4.1.10"
"typescript": "7.0.2",
"vitest": "^4.1.11"
},
"packageManager": "pnpm@11.15.1+sha512.81350b07e53c9538a02f1f2303b4290fa2d7be04e56e2a970c4cc4b417dc761de196edabd49d55c7dc9580db81007c44143e4e3d7e462b3000d23c255122d065"
"packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621"
}
+1564 -3629
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -8,5 +8,8 @@ overrides:
'postcss@<8.5.10': '^8.5.15'
'sharp@<0.35.0': '^0.35.3'
minimumReleaseAgeExclude:
- '@mermaid-js/parser@1.2.0'
- mermaid@11.16.0
- '@mermaid-js/parser@1.2.1'
- mermaid@11.17.0
- lucide-react@1.33.0
- postcss@8.5.26
- fumadocs-mdx@15.3.0
+343 -8
View File
@@ -1033,17 +1033,25 @@
"ApiToken": {
"properties": {
"createdAt": {
"format": "int64",
"type": "integer"
},
"enabled": {
"type": "boolean"
},
"expiresAt": {
"format": "int64",
"type": "integer"
},
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"scope": {
"type": "string"
},
"token": {
"description": "SHA-256 hash; the plaintext is shown only once at creation",
"type": "string"
@@ -1052,8 +1060,10 @@
"required": [
"createdAt",
"enabled",
"expiresAt",
"id",
"name",
"scope",
"token"
],
"type": "object"
@@ -1062,12 +1072,18 @@
"properties": {
"createdAt": {
"example": 1736000000,
"format": "int64",
"type": "integer"
},
"enabled": {
"example": true,
"type": "boolean"
},
"expiresAt": {
"example": 0,
"format": "int64",
"type": "integer"
},
"id": {
"example": 2,
"type": "integer"
@@ -1076,6 +1092,10 @@
"example": "central-panel-a",
"type": "string"
},
"scope": {
"example": "admin",
"type": "string"
},
"token": {
"example": "new-token-string",
"type": "string"
@@ -1084,8 +1104,10 @@
"required": [
"createdAt",
"enabled",
"expiresAt",
"id",
"name"
"name",
"scope"
],
"type": "object"
},
@@ -2243,7 +2265,7 @@
},
{
"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 Server",
@@ -4954,8 +4976,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": {
@@ -5130,6 +5153,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",
@@ -8817,7 +8841,7 @@
"tags": [
"API Tokens"
],
"summary": "Mint a new API token. Name must be unique and 1-64 characters; the token string is server-generated and returned only in this response — it is stored hashed and cannot be retrieved later.",
"summary": "Mint a scoped API token. The server-generated plaintext is returned only once and stored as a hash.",
"operationId": "post_panel_api_setting_apiTokens_create",
"requestBody": {
"required": true,
@@ -8829,14 +8853,26 @@
"name": {
"type": "string",
"description": "Human-readable label, e.g. \"central-panel-a\"."
},
"scope": {
"type": "string",
"description": "admin (default), monitor, or node-sync."
},
"expiresAt": {
"type": "integer",
"description": "Future Unix milliseconds, or 0 for no expiry."
}
},
"required": [
"name"
"name",
"scope",
"expiresAt"
]
},
"example": {
"name": "central-panel-a"
"name": "central-panel-a",
"scope": "node-sync",
"expiresAt": 1798761600000
}
}
}
@@ -8865,8 +8901,10 @@
"obj": {
"createdAt": 1736000000,
"enabled": true,
"expiresAt": 0,
"id": 2,
"name": "central-panel-a",
"scope": "admin",
"token": "new-token-string"
}
}
@@ -8916,6 +8954,28 @@
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"expectedScope": {
"type": "string",
"description": "Stored scope expected by the operator."
}
},
"required": [
"expectedScope"
]
},
"example": {
"expectedScope": "node-sync"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
@@ -8970,14 +9030,20 @@
"enabled": {
"type": "boolean",
"description": "New enabled state."
},
"expectedScope": {
"type": "string",
"description": "Stored scope expected by the operator."
}
},
"required": [
"enabled"
"enabled",
"expectedScope"
]
},
"example": {
"enabled": false
"enabled": false,
"expectedScope": "node-sync"
}
}
}
@@ -9249,6 +9315,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": [
@@ -10106,6 +10213,234 @@
}
}
}
},
"/panel/api/nodes/mtls/reloadClient": {
"post": {
"tags": [
"Nodes"
],
"summary": "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.",
"operationId": "post_panel_api_nodes_mtls_reloadClient",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/inbounds/{id}/subSortIndex": {
"post": {
"tags": [
"Inbounds"
],
"summary": "Set only the subscription sort order. Reads the stored inbound, so a reorder cannot carry a stale client list over a concurrent edit.",
"operationId": "post_panel_api_inbounds_id_subSortIndex",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Inbound ID.",
"schema": {
"type": "integer"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"subSortIndex": 2
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/clients/hwids/{email}": {
"post": {
"tags": [
"Clients"
],
"summary": "List registered HWID devices for a client. Hashes are not exposed.",
"operationId": "post_panel_api_clients_hwids_email",
"parameters": [
{
"name": "email",
"in": "path",
"required": true,
"description": "Client email.",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": [
{
"id": 1,
"firstSeen": 1735000000000,
"lastSeen": 1735100000000,
"userAgent": "Happ/1.0",
"deviceOs": "android",
"osVersion": "15",
"deviceModel": "Pixel 9"
}
]
}
}
}
}
}
},
"delete": {
"tags": [
"Clients"
],
"summary": "Clear all registered HWID devices for a client so new devices can register again.",
"operationId": "delete_panel_api_clients_hwids_email",
"parameters": [
{
"name": "email",
"in": "path",
"required": true,
"description": "Client email.",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/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": {}
}
}
}
}
}
}
}
}
}
}
+57
View File
@@ -0,0 +1,57 @@
# PWA installability verification
This change adds a network-only PWA surface to the login and panel pages. It
does not cache panel data, API responses, credentials, or WebSocket traffic.
## Local checks
Run these commands from the repository root after installing the pinned Node
and Go toolchains:
```text
cd frontend
npm run typecheck
npm run lint
npx vitest run --project unit
npx vitest run --project components
npm run build
cd ..
go test ./...
go build ./...
```
The built binary must serve these paths beneath the configured `webBasePath`:
- `manifest.webmanifest`
- `pwa-register.js`
- `service-worker.js`
- `icons/3x-ui-16.png`
- `icons/3x-ui-24.png`
- `icons/3x-ui-32.png`
- `icons/3x-ui-64.png`
- `icons/3x-ui-192.png`
- `icons/3x-ui-512.png`
The login and panel HTML must contain a manifest link and registration script
whose URLs begin with the same runtime base path. The manifest must contain
`display: "standalone"`, relative `start_url` and `scope`, and all six icon
entries.
## Live rollout checks
Before replacing a server binary, record the current x-ui binary checksum and
create a timestamped copy of the binary and `/etc/x-ui/x-ui.db`. Restart only
the `x-ui` service after the candidate is staged. Because x-ui manages Xray as
a child process, the restart can briefly interrupt VPN connections.
After the restart, verify:
1. `x-ui` is active and its child Xray process is running.
2. The existing panel URL serves HTML with the PWA manifest link.
3. The manifest, registration script, worker, and all six icons return `200`.
4. Login, authenticated API requests, panel navigation, logout, and the panel
WebSocket all work.
5. At least one VPN client can complete a fresh connection cycle.
If any check fails, restore the exact binary backup, restart x-ui once, and
repeat the checks against the original build.
+10 -10
View File
@@ -14,11 +14,11 @@ list, and multi-node sync — so once it is set, everything downstream just work
Open an inbound → **Transport / Stream Settings** → enable **Sockopt** → use the
**Real client IP** preset selector:
| Preset | What it does | Use for |
|---|---|---|
| **Off / direct** | Clears both fields. | Inbound reachable directly by clients. |
| **Cloudflare CDN** | Sets `sockopt.trustedXForwardedFor = ["CF-Connecting-IP"]`. | WebSocket / HTTPUpgrade / XHTTP behind Cloudflare's CDN (orange cloud). |
| **L4 relay / Spectrum (PROXY)** | Sets `acceptProxyProtocol = true`. | An L4 tunnel/relay in front, or Cloudflare **Spectrum**. |
| Preset | What it does | Use for |
| ------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------- |
| **Off / direct** | Clears both fields. | Inbound reachable directly by clients. |
| **Cloudflare CDN** | Sets `sockopt.trustedXForwardedFor = ["CF-Connecting-IP"]`. | WebSocket / HTTPUpgrade / XHTTP behind Cloudflare's CDN (orange cloud). |
| **L4 relay / Spectrum (PROXY)** | Sets `acceptProxyProtocol = true`. | An L4 tunnel/relay in front, or Cloudflare **Spectrum**. |
The raw `Proxy Protocol` switch and `Trusted X-Forwarded-For` list stay visible below the preset
selector for manual / advanced tuning — the presets just fill them in for you.
@@ -65,16 +65,16 @@ and XHTTP; **not** on mKCP. The front must be configured to send the header, e.g
## Transport support matrix
| Mechanism | TCP/RAW | mKCP | WebSocket | gRPC | HTTPUpgrade | XHTTP |
|---|:--:|:--:|:--:|:--:|:--:|:--:|
| `trustedXForwardedFor` (header) | | | ✅ | | ✅ | ✅ |
| `acceptProxyProtocol` (PROXY) | ✅ | – | ✅ | ✅ | ✅ | ✅ |
| Mechanism | TCP/RAW | mKCP | WebSocket | gRPC | HTTPUpgrade | XHTTP |
| ------------------------------- | :-----: | :--: | :-------: | :--: | :---------: | :---: |
| `trustedXForwardedFor` (header) | | | ✅ | | ✅ | ✅ |
| `acceptProxyProtocol` (PROXY) | ✅ | – | ✅ | ✅ | ✅ | ✅ |
The form shows a warning when you select a preset that the current transport cannot honor.
> **Use one, not both.** `acceptProxyProtocol` and `trustedXForwardedFor` are independent — the
> first reads the real IP from the L4 PROXY header, the second from an HTTP request header. On
> WebSocket / HTTPUpgrade / XHTTP, xray applies the HTTP header *last*, so a stale
> WebSocket / HTTPUpgrade / XHTTP, xray applies the HTTP header _last_, so a stale
> `trustedXForwardedFor` would override (and defeat) a PROXY-protocol setup. The presets are
> mutually exclusive and clear the other field for you; only mix them by hand if you know your
> upstream chain needs it.
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"ignorePatterns": [
"node_modules",
"src/generated",
"public",
"tools/oxlint/__fixtures__"
]
}
+72
View File
@@ -0,0 +1,72 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"node_modules/**"
],
"plugins": [
"typescript",
"react",
"jsx-a11y"
],
"jsPlugins": [
"./tools/oxlint/input-number-guard.mjs"
],
"categories": {
"correctness": "error"
},
"env": {
"browser": true,
"es2022": true
},
"rules": {
"typescript/no-explicit-any": "error",
"typescript/no-unused-vars": [
"warn",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}
],
"typescript/ban-ts-comment": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-namespace": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-unused-expressions": "warn",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/triple-slash-reference": "error",
"no-empty": [
"error",
{
"allowEmptyCatch": true
}
],
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "error",
"jsx-a11y/no-autofocus": "off",
"input-number/no-synthetic-clear": "off",
"jsx-a11y/prefer-tag-over-role": "off"
},
"overrides": [
{
"files": [
"src/pages/settings/**/*.tsx",
"src/pages/xray/**/*.tsx"
],
"rules": {
"input-number/no-synthetic-clear": "error"
}
},
{
"files": [
"src/pages/xray/**/*Modal.tsx"
],
"rules": {
"input-number/no-synthetic-clear": "off"
}
}
]
}
+3 -2
View File
@@ -31,8 +31,9 @@ The `@` import alias maps to `src/`.
Form *state* runs on React Hook Form (`src/components/form/rhf/`), not Ant
Design's `Form` store.
- Function components + hooks only; no class components.
- No `//` line comments in committed TS/TSX. HTML comments are fine.
- TS strict; `no-explicit-any` is an error. Build forms with `useZodForm` +
- Comments in committed TS/TSX: 2 lines MAX per comment block, spent on the
*why* a name cannot hold (same rule as root CLAUDE.md). HTML comments are fine.
- TS strict; oxlint's `typescript/no-explicit-any` is an error. Build forms with `useZodForm` +
`FormField` from `@/components/form/rhf` (wrap the tree in `FormProvider`);
validate through the `zodResolver` or per-field
`rules={{ validate: rhfZodValidate(Schema.shape.field) }}` — messages are Zod
+27 -11
View File
@@ -33,7 +33,10 @@ production-style links work without round-tripping through Go.
| `npm run build` | Regenerates OpenAPI + Zod, then builds into `../internal/web/dist/` |
| `npm run preview` | Serve the built bundle locally |
| `npm run typecheck` | `tsc --noEmit` (strict, no emit) |
| `npm run lint` | ESLint flat config (`@typescript-eslint` + `react-hooks`) |
| `npm run lint` | oxlint over `src/` + `tools/` (`.oxlintrc.json`) |
| `npm run lint:deprecated` | Type-aware sweep for JSDoc `@deprecated` APIs (on demand) |
| `npm run format` | oxfmt (`.oxfmtrc.json`) — rewrites `src/` + `tools/` in place |
| `npm run format:check` | oxfmt in check mode (no writes) |
| `npm run test` | Vitest single run (schema fixtures, link parsers, …) |
| `npm run test:watch` | Vitest watch mode |
| `npm run storybook` | Storybook dev server on `:6006` (component workbench + autodocs) |
@@ -41,8 +44,8 @@ production-style links work without round-tripping through Go.
| `npm run gen:api` | Build `public/openapi.json` from `pages/api-docs/endpoints.ts` |
| `npm run gen:zod` | Run the Go-side openapigen tool → `src/generated/{zod,types}.ts` |
CI runs `typecheck`, `lint`, `test`, `build`, and `build-storybook` on
every PR (see `../.github/workflows/ci.yml`).
CI runs `typecheck`, `lint`, `format:check`, `test`, `build`, and
`build-storybook` on every PR (see `../.github/workflows/ci.yml`).
### One-off: scan for deprecated APIs
@@ -51,12 +54,13 @@ with the JSDoc `@deprecated` tag (AntD prop renames, Zod renames,
removed Web APIs, etc.):
```sh
npx eslint --config eslint.deprecated.config.js src
npm run lint:deprecated
```
It's a type-aware ESLint run against `eslint.deprecated.config.js`
and is not wired into `npm run lint` because typed linting triples
the wall-clock time.
It is oxlint's type-aware mode (`oxlint-tsgolint`, which drives the
TypeScript 7 `typescript-go` checker) narrowed to `no-deprecated`, and
is not wired into `npm run lint` because typed linting needs a full
type-check pass.
## Production build
@@ -70,15 +74,27 @@ react-query into separate vendor bundles to keep the per-page
initial JS small. The Go binary embeds this directory at compile
time and `internal/web/controller/dist.go` serves the per-page HTML.
### PWA mode
The login and panel pages expose a minimal network-only Progressive Web App.
The manifest, service worker, registration script, and icons are embedded with
the frontend and served under the runtime `webBasePath`. The service worker
does not use Cache Storage, does not intercept requests, and does not provide
offline access; panel authentication, API calls, and WebSocket traffic remain
normal network requests.
## Layout
```
frontend/
├── index.html, login.html, subpage.html # 3 Vite entries
├── tsconfig.json
├── eslint.config.js
├── eslint.deprecated.config.js # On-demand type-aware lint config that flags
│ # usages of APIs marked with JSDoc @deprecated
├── .oxlintrc.json # oxlint config (replaces the ESLint flat config)
├── .oxfmtrc.json # oxfmt config (Prettier-compatible settings)
├── tools/oxlint/
│ └── input-number-guard.mjs # oxlint JS plugin: the #6121/#6127 cleared-
│ # InputNumber guard (oxlint has no
│ # no-restricted-syntax)
├── vitest.config.ts
├── vite.config.js
├── .storybook/ # Storybook config (main.ts, preview.tsx)
@@ -146,7 +162,7 @@ Patterns:
- Wire request: `Schema.parse(payload)` inside `mutationFn` — throws,
because a malformed payload here is always a developer bug
- **No `.loose()` or `[key: string]: any`** in production schemas.
`@typescript-eslint/no-explicit-any: error` is enforced.
`typescript/no-explicit-any: error` is enforced by oxlint.
## Form pattern (Pattern A)
-89
View File
@@ -1,89 +0,0 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import globals from 'globals';
export default [
{ ignores: ['node_modules/**', '../internal/web/dist/**'] },
js.configs.recommended,
...tseslint.configs.recommended.map((config) => ({
...config,
files: ['**/*.{ts,tsx}'],
})),
{
files: ['**/*.{ts,tsx}'],
plugins: {
'react-hooks': reactHooks,
},
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
globals: {
...globals.browser,
},
},
rules: {
...reactHooks.configs.recommended.rules,
'@typescript-eslint/no-unused-vars': ['warn', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
}],
// Zod migration goal (Step 7): every production module is held to
// strict no-explicit-any. The two legacy class files at the bottom
// of the rule list keep their existing file-level eslint-disable
// until DBInbound is migrated off Inbound.toInbound() — see the
// migration spec Non-Goals section.
'@typescript-eslint/no-explicit-any': 'error',
'no-empty': ['error', { allowEmptyCatch: true }],
'react-hooks/set-state-in-effect': 'off',
'react-hooks/purity': 'off',
'react-hooks/react-compiler': 'off',
'react-hooks/preserve-manual-memoization': 'off',
'react-hooks/immutability': 'off',
'react-hooks/refs': 'off',
},
},
{
files: ['**/*.tsx'],
plugins: { 'jsx-a11y': jsxA11y },
rules: {
...jsxA11y.flatConfigs.recommended.rules,
'jsx-a11y/no-autofocus': 'off',
},
},
{
// The settings and xray pages write numeric InputNumber changes straight
// into state, so a null-collapsing handler (`Number(v) || N`, or the
// ternary `typeof v === 'number' ? v : N`) turns a cleared field into a
// stored N — the cleared-port bug, #6121. Handlers here go through
// onNumber() (src/utils/onNumber.ts) instead. Known limit: a handler
// extracted into a variable and passed as onChange={handler} is not
// matched; the inline shapes below are the ones that drift in practice.
files: ['src/pages/settings/**/*.tsx', 'src/pages/xray/**/*.tsx'],
rules: {
'no-restricted-syntax': ['error', {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] LogicalExpression[operator="||"] > CallExpression[callee.name="Number"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}, {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] ConditionalExpression[test.left.operator="typeof"][alternate.type="Literal"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}, {
selector: 'JSXElement[openingElement.name.name="InputNumber"] JSXAttribute[name.name="onChange"] LogicalExpression[operator="??"][right.type="Literal"]',
message: 'A cleared InputNumber must not write a synthetic value; wrap the handler with onNumber() from @/utils/onNumber (see #6127).',
}],
},
},
{
// The xray form modals (OutboundFormModal, BalancerFormModal,
// DnsServerModal, WarpModal, …) stage values behind Zod validation like
// the clients/inbounds modals do, and some of their fields carry a
// deliberate clear-means-zero semantic — the direct-write rule above
// does not apply to them.
files: ['src/pages/xray/**/*Modal.tsx'],
rules: {
'no-restricted-syntax': 'off',
},
},
];
-26
View File
@@ -1,26 +0,0 @@
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
export default [
{ ignores: ['node_modules/**', '../internal/web/dist/**', 'src/generated/**'] },
{
files: ['**/*.{ts,tsx}'],
plugins: {
'@typescript-eslint': tseslint.plugin,
'react-hooks': reactHooks,
},
languageOptions: {
parser: tseslint.parser,
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
'@typescript-eslint/no-deprecated': 'warn',
},
linterOptions: {
reportUnusedDisableDirectives: 'off',
},
},
];
+2191 -3501
View File
File diff suppressed because it is too large Load Diff
+36 -34
View File
@@ -12,7 +12,11 @@
"dev": "vite",
"build": "npm run gen:api && vite build",
"preview": "vite preview",
"lint": "eslint src",
"lint": "oxlint src tools",
"lint:fix": "oxlint --fix src tools",
"lint:deprecated": "oxlint --type-aware -A all -D typescript/no-deprecated src",
"format": "oxfmt src tools",
"format:check": "oxfmt --check src tools",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
@@ -24,64 +28,61 @@
"prepare": "cd .. && husky frontend/.husky || true"
},
"lint-staged": {
"src/**/*.{ts,tsx}": "eslint --fix"
"src/**/*.{ts,tsx}": [
"oxfmt",
"oxlint --fix"
]
},
"dependencies": {
"@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3",
"@hookform/resolvers": "^5.5.7",
"@noble/hashes": "^2.2.0",
"@hookform/resolvers": "^5.9.1",
"@noble/hashes": "^2.3.0",
"@tanstack/react-query": "^5.101.4",
"@tanstack/react-query-devtools": "^5.101.4",
"antd": "^6.5.2",
"antd": "^6.6.1",
"codemirror": "^6.0.2",
"dayjs": "^1.11.21",
"dayjs": "^1.11.23",
"i18next": "^26.3.6",
"otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.5",
"persian-calendar-suite": "^1.5.6",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-hook-form": "^7.83.0",
"react-hook-form": "^7.85.0",
"react-i18next": "^17.0.11",
"react-router": "^8.3.0",
"swagger-ui-react": "^5.32.11",
"swagger-ui-react": "^5.32.14",
"uplot": "^1.6.32",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@storybook/addon-a11y": "^10.5.5",
"@storybook/addon-docs": "^10.5.5",
"@storybook/addon-vitest": "^10.5.5",
"@storybook/react-vite": "^10.5.5",
"@storybook/addon-a11y": "^10.5.9",
"@storybook/addon-docs": "^10.5.9",
"@storybook/addon-vitest": "^10.5.9",
"@storybook/react-vite": "^10.5.9",
"@testing-library/dom": "^10.4.1",
"@testing-library/react": "^16.3.2",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.0.4",
"@vitest/browser-playwright": "4.1.10",
"@vitest/coverage-v8": "^4.1.10",
"eslint": "^10.8.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react-hooks": "^7.1.1",
"globals": "^17.8.0",
"@vitejs/plugin-react": "^6.0.5",
"@vitest/browser-playwright": "4.1.11",
"@vitest/coverage-v8": "^4.1.11",
"husky": "^9.1.7",
"jsdom": "^30.0.1",
"lint-staged": "^17.2.0",
"lint-staged": "^17.3.0",
"msw": "^2.15.0",
"playwright": "^1.62.0",
"storybook": "^10.5.5",
"typescript": "6.0.3",
"typescript-eslint": "^8.65.0",
"vite": "8.1.5",
"vitest": "^4.1.10"
"oxfmt": "0.64.0",
"oxlint": "1.79.0",
"oxlint-tsgolint": "^7.0.2001",
"playwright": "^1.62.1",
"storybook": "^10.5.9",
"typescript": "7.0.2",
"vite": "8.2.1",
"vitest": "^4.1.11"
},
"overrides": {
"eslint-plugin-jsx-a11y": {
"eslint": "$eslint"
},
"dompurify": "^3.4.11",
"react-copy-to-clipboard": "^5.1.1",
"react-inspector": "^9.0.0",
@@ -89,7 +90,8 @@
"react": "^19.0.0"
},
"swagger-ui-react": {
"js-yaml": "^4.2.0"
"js-yaml": "^4.2.0",
"brace-expansion": "^5.0.9"
},
"@typeschema/valibot": {
"valibot": "^1.1.0"
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

+41
View File
@@ -0,0 +1,41 @@
{
"name": "3x-ui",
"short_name": "3x-ui",
"start_url": "./",
"scope": "./",
"display": "standalone",
"background_color": "#0f172a",
"theme_color": "#1677ff",
"icons": [
{
"src": "icons/3x-ui-16.png",
"sizes": "16x16",
"type": "image/png"
},
{
"src": "icons/3x-ui-24.png",
"sizes": "24x24",
"type": "image/png"
},
{
"src": "icons/3x-ui-32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "icons/3x-ui-64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "icons/3x-ui-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/3x-ui-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+21 -9
View File
@@ -7,8 +7,8 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.14.7'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const PACKAGE_VERSION = '2.15.0'
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
@@ -137,8 +137,18 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
if (client && activeClientIds.has(client.id)) {
const serializedRequest = await serializeRequest(requestCloneForEvents)
// Omit the body of server-sent event stream responses.
// Cloning such responses would prevent client-side stream cancelations
// from reaching the original stream (a teed stream only cancels its
// source once both of its branches cancel) and would buffer the
// entire stream into the unconsumed clone indefinitely.
const isEventStreamResponse = response.headers
.get('content-type')
?.toLowerCase()
.startsWith('text/event-stream')
// Clone the response so both the client and the library could consume it.
const responseClone = response.clone()
const responseClone = isEventStreamResponse ? null : response.clone()
sendToClient(
client,
@@ -151,15 +161,17 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
...serializedRequest,
},
response: {
type: responseClone.type,
status: responseClone.status,
statusText: responseClone.statusText,
headers: Object.fromEntries(responseClone.headers.entries()),
body: responseClone.body,
type: response.type,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
body: responseClone ? responseClone.body : null,
},
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
responseClone && responseClone.body
? [serializedRequest.body, responseClone.body]
: [],
)
}
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
(() => {
if (!('serviceWorker' in navigator)) return;
const script = document.currentScript;
if (!(script instanceof HTMLScriptElement)) return;
const scriptUrl = new URL(script.src, window.location.href);
const baseUrl = new URL('./', scriptUrl);
const workerUrl = new URL('service-worker.js', baseUrl);
navigator.serviceWorker.register(workerUrl.pathname, {
scope: baseUrl.pathname,
}).catch(() => {});
})();
+9
View File
@@ -0,0 +1,9 @@
self.addEventListener('install', (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', () => {});
+12 -2
View File
@@ -40,6 +40,7 @@ function extractPathParams(openApiPath) {
function mapType(t) {
const v = String(t || '').toLowerCase();
if (v.endsWith('[]')) return 'array';
if (v === 'number' || v === 'integer' || v === 'int') return 'integer';
if (v === 'float' || v === 'double') return 'number';
if (v === 'boolean' || v === 'bool') return 'boolean';
@@ -48,6 +49,15 @@ function mapType(t) {
return 'string';
}
function schemaFromType(t) {
const v = String(t || '').toLowerCase();
if (v.endsWith('[]')) {
const itemType = v.slice(0, -2);
return { type: 'array', items: { type: mapType(itemType) } };
}
return { type: mapType(v) };
}
function tryParseJson(raw) {
if (typeof raw !== 'string') return undefined;
try {
@@ -63,7 +73,7 @@ function paramToOpenApi(p) {
in: p.in,
required: p.in === 'path' ? true : !p.optional,
description: p.desc || '',
schema: { type: mapType(p.type) },
schema: schemaFromType(p.type),
};
if (p.defaultValue !== undefined) out.schema.default = p.defaultValue;
return out;
@@ -109,7 +119,7 @@ function buildOperation(ep, tag) {
const required = [];
for (const bp of bodyParams) {
properties[bp.name] = {
type: mapType(bp.type),
...schemaFromType(bp.type),
description: bp.desc || '',
};
if (!bp.optional) required.push(bp.name);
+3 -1
View File
@@ -79,7 +79,9 @@ function encodeForm(data: unknown): string {
return;
}
if (typeof value === 'object') {
Object.entries(value as Record<string, unknown>).forEach(([k, v]) => append(`${key}[${k}]`, v));
Object.entries(value as Record<string, unknown>).forEach(([k, v]) =>
append(`${key}[${k}]`, v),
);
return;
}
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
+28 -11
View File
@@ -4,7 +4,11 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { HttpUtil, Msg } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { AllSetting } from '@/models/setting';
import { AllSettingSchema, type AllSettingInput } from '@/schemas/setting';
import {
AllSettingResponseSchema,
AllSettingSchema,
type AllSettingInput,
} from '@/schemas/setting';
import { keys } from '@/api/queryKeys';
import { useServerDraft } from '@/hooks/useServerDraft';
@@ -17,7 +21,7 @@ type SettingSaveResult = {
async function fetchAllSetting(): Promise<AllSettingInput | null> {
const msg = await HttpUtil.post('/panel/api/setting/all', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch settings');
const validated = parseMsg(msg, AllSettingSchema, 'setting/all');
const validated = parseMsg(msg, AllSettingResponseSchema, 'setting/all');
return validated.obj;
}
@@ -39,28 +43,41 @@ export function useAllSettings() {
);
const allSetting = draft ?? server;
const updateSetting = useCallback((patch: Partial<AllSetting>) => {
setDraft((prev) => {
const next = new AllSetting(prev ?? server);
Object.assign(next, patch);
return next;
});
}, [server, setDraft]);
const updateSetting = useCallback(
(patch: Partial<AllSetting>) => {
setDraft((prev) => {
const next = new AllSetting(prev ?? server);
Object.assign(next, patch);
return next;
});
},
[server, setDraft],
);
const saveMut = useMutation({
mutationFn: async ({ payload, saved }: { payload: SettingSavePayload; saved?: AllSetting }): Promise<SettingSaveResult> => {
mutationFn: async ({
payload,
saved,
}: {
payload: SettingSavePayload;
saved?: AllSetting;
}): Promise<SettingSaveResult> => {
const next = { ...payload };
const body = AllSettingSchema.partial().safeParse(next);
if (!body.success) {
console.warn('[zod] setting/update body failed validation', body.error.issues);
}
const msg = await HttpUtil.post('/panel/api/setting/update', body.success ? { ...next, ...body.data } : next);
const msg = await HttpUtil.post(
'/panel/api/setting/update',
body.success ? { ...next, ...body.data } : next,
);
return { msg, saved };
},
onSuccess: ({ msg, saved }) => {
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)),
});
}
@@ -6,7 +6,9 @@ import { FactoryDefaultsSchema, type FactoryDefaults } from '@/schemas/setting';
import { keys } from '@/api/queryKeys';
async function fetchFactoryDefaults(): Promise<FactoryDefaults> {
const msg = await HttpUtil.post('/panel/api/setting/factoryDefaults', undefined, { silent: true });
const msg = await HttpUtil.post('/panel/api/setting/factoryDefaults', undefined, {
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch factory defaults');
const validated = parseMsg(msg, FactoryDefaultsSchema, 'setting/factoryDefaults');
const parsed = FactoryDefaultsSchema.safeParse(validated.obj);
@@ -18,7 +18,9 @@ const FAIL_OPEN_STATUS: Fail2banStatus = {
};
async function fetchFail2banStatus(): Promise<Fail2banStatus> {
const msg = await HttpUtil.get<Fail2banStatus>('/panel/api/server/fail2banStatus', undefined, { silent: true });
const msg = await HttpUtil.get<Fail2banStatus>('/panel/api/server/fail2banStatus', undefined, {
silent: true,
});
if (!msg?.success || !msg.obj) throw new Error(msg?.msg || 'Failed to fetch fail2ban status');
return { ...FAIL_OPEN_STATUS, ...msg.obj };
}
+111
View File
@@ -0,0 +1,111 @@
import { keepPreviousData, useMutation, useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { keys } from '@/api/queryKeys';
import {
GeoCategoryPageSchema,
GeoEntryPageSchema,
GeoFileSchema,
GeodataTokenIssueSchema,
} from '@/generated/zod';
import type { GeoCategoryPage, GeoEntryPage, GeoFile, GeodataTokenIssue } from '@/generated/types';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
const GeoFileListSchema = z.array(GeoFileSchema);
const GeodataTokenIssueListSchema = z.array(GeodataTokenIssueSchema);
const EMPTY_CATEGORY_PAGE: GeoCategoryPage = { total: 0, items: [] };
const EMPTY_ENTRY_PAGE: GeoEntryPage = { total: 0, items: [] };
export type GeoTokenKind = 'ip' | 'domain';
export interface ValidateGeoTokensInput {
tokens: string[];
kind: GeoTokenKind;
}
async function fetchGeodataFiles(): Promise<GeoFile[]> {
const msg = await HttpUtil.get('/panel/api/xray/geodata/files', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch geodata files');
const validated = parseMsg(msg, GeoFileListSchema, 'xray/geodata/files');
return Array.isArray(validated.obj) ? validated.obj : [];
}
async function fetchGeodataCategories(file: string, query: string): Promise<GeoCategoryPage> {
const msg = await HttpUtil.get(
'/panel/api/xray/geodata/categories',
{ file, q: query },
{ silent: true },
);
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch geodata categories');
const validated = parseMsg(msg, GeoCategoryPageSchema, 'xray/geodata/categories');
return validated.obj ?? EMPTY_CATEGORY_PAGE;
}
async function fetchGeodataEntries(
file: string,
code: string,
query: string,
offset: number,
limit: number,
): Promise<GeoEntryPage> {
const msg = await HttpUtil.get(
'/panel/api/xray/geodata/entries',
{ file, code, q: query, offset, limit },
{ silent: true },
);
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch geodata entries');
const validated = parseMsg(msg, GeoEntryPageSchema, 'xray/geodata/entries');
return validated.obj ?? EMPTY_ENTRY_PAGE;
}
export function useGeodataFiles(enabled: boolean) {
return useQuery({
queryKey: keys.xray.geodata.files(),
queryFn: fetchGeodataFiles,
enabled,
staleTime: 5 * 60 * 1000,
});
}
export function useGeodataCategories(file: string | undefined, query: string, enabled: boolean) {
return useQuery({
queryKey: keys.xray.geodata.categories(file ?? '', query),
queryFn: () => fetchGeodataCategories(file ?? '', query),
enabled: enabled && !!file,
staleTime: 5 * 60 * 1000,
placeholderData: keepPreviousData,
});
}
export function useGeodataEntries(
file: string | undefined,
code: string | undefined,
query: string,
offset: number,
limit: number,
enabled: boolean,
) {
return useQuery({
queryKey: keys.xray.geodata.entries(file ?? '', code ?? '', query, offset, limit),
queryFn: () => fetchGeodataEntries(file ?? '', code ?? '', query, offset, limit),
enabled: enabled && !!file && !!code,
placeholderData: keepPreviousData,
});
}
export function useValidateGeoTokens() {
return useMutation<GeodataTokenIssue[], Error, ValidateGeoTokensInput>({
mutationFn: async ({ tokens, kind }) => {
const msg = await HttpUtil.post(
'/panel/api/xray/geodata/validate',
{ tokens: tokens.join(','), kind },
{ silent: true },
);
if (!msg?.success) throw new Error(msg?.msg || 'Failed to validate geodata tokens');
const validated = parseMsg(msg, GeodataTokenIssueListSchema, 'xray/geodata/validate');
return Array.isArray(validated.obj) ? validated.obj : [];
},
});
}
+31 -12
View File
@@ -11,50 +11,69 @@ export function useHostMutations() {
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.hosts.root() });
const bulkCreateMut = useMutation({
mutationFn: (payload: BulkAddHostValues) => HttpUtil.post('/panel/api/hosts/bulk/add', payload, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
mutationFn: (payload: BulkAddHostValues) =>
HttpUtil.post('/panel/api/hosts/bulk/add', payload, JSON_HEADERS),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const updateMut = useMutation({
mutationFn: ({ groupId, payload }: { groupId: string; payload: BulkAddHostValues }) =>
HttpUtil.post(`/panel/api/hosts/update/${groupId}`, payload, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const removeMut = useMutation({
mutationFn: (groupId: string) => HttpUtil.post(`/panel/api/hosts/del/${groupId}`),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const setEnableMut = useMutation({
mutationFn: ({ groupId, enable }: { groupId: string; enable: boolean }) =>
HttpUtil.post(`/panel/api/hosts/setEnable/${groupId}`, { enable }),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const reorderMut = useMutation({
mutationFn: (groupIds: string[]) => HttpUtil.post('/panel/api/hosts/reorder', { ids: groupIds }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
mutationFn: (groupIds: string[]) =>
HttpUtil.post('/panel/api/hosts/reorder', { ids: groupIds }, JSON_HEADERS),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const bulkEnableMut = useMutation({
mutationFn: ({ groupIds, enable }: { groupIds: string[]; enable: boolean }) =>
HttpUtil.post('/panel/api/hosts/bulk/setEnable', { ids: groupIds, enable }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const bulkDelMut = useMutation({
mutationFn: (groupIds: string[]) => HttpUtil.post('/panel/api/hosts/bulk/del', { ids: groupIds }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
mutationFn: (groupIds: string[]) =>
HttpUtil.post('/panel/api/hosts/bulk/del', { ids: groupIds }, JSON_HEADERS),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
return {
bulkCreate: (payload: BulkAddHostValues) => bulkCreateMut.mutateAsync(payload),
update: (groupId: string, payload: BulkAddHostValues) => updateMut.mutateAsync({ groupId, payload }),
update: (groupId: string, payload: BulkAddHostValues) =>
updateMut.mutateAsync({ groupId, payload }),
remove: (groupId: string) => removeMut.mutateAsync(groupId),
setEnable: (groupId: string, enable: boolean) => setEnableMut.mutateAsync({ groupId, enable }),
reorder: (groupIds: string[]) => reorderMut.mutateAsync(groupIds),
bulkSetEnable: (groupIds: string[], enable: boolean) => bulkEnableMut.mutateAsync({ groupIds, enable }),
bulkSetEnable: (groupIds: string[], enable: boolean) =>
bulkEnableMut.mutateAsync({ groupIds, enable }),
bulkDel: (groupIds: string[]) => bulkDelMut.mutateAsync(groupIds),
};
}
+29 -14
View File
@@ -30,27 +30,33 @@ export function useNodeMutations() {
};
const createMut = useMutation({
mutationFn: (payload: Partial<NodeRecord>) =>
HttpUtil.post('/panel/api/nodes/add', payload),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
mutationFn: (payload: Partial<NodeRecord>) => HttpUtil.post('/panel/api/nodes/add', payload),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const updateMut = useMutation({
mutationFn: ({ id, payload }: { id: number; payload: Partial<NodeRecord> }) =>
HttpUtil.post(`/panel/api/nodes/update/${id}`, payload),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const removeMut = useMutation({
mutationFn: (id: number) =>
HttpUtil.post(`/panel/api/nodes/del/${id}`),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
mutationFn: (id: number) => HttpUtil.post(`/panel/api/nodes/del/${id}`),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const setEnableMut = useMutation({
mutationFn: ({ id, enable }: { id: number; enable: boolean }) =>
HttpUtil.post(`/panel/api/nodes/setEnable/${id}`, { enable }),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const probeMut = useMutation({
@@ -58,15 +64,23 @@ export function useNodeMutations() {
const raw = await HttpUtil.post(`/panel/api/nodes/probe/${id}`);
return parseMsg(raw, ProbeResultSchema, 'nodes/probe');
},
onSuccess: (msg) => { if (msg?.success) invalidate(); },
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const updatePanelsMut = useMutation({
mutationFn: ({ ids, dev }: { ids: number[]; dev: boolean }) =>
HttpUtil.post<NodeUpdateResult[]>('/panel/api/nodes/updatePanel', { ids, dev }, {
headers: { 'Content-Type': 'application/json' },
}),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
HttpUtil.post<NodeUpdateResult[]>(
'/panel/api/nodes/updatePanel',
{ ids, dev },
{
headers: { 'Content-Type': 'application/json' },
},
),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
return {
@@ -75,7 +89,8 @@ export function useNodeMutations() {
remove: (id: number) => removeMut.mutateAsync(id),
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
probe: (id: number) => probeMut.mutateAsync(id),
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> => updatePanelsMut.mutateAsync({ ids, dev }),
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> =>
updatePanelsMut.mutateAsync({ ids, dev }),
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
const raw = await HttpUtil.post('/panel/api/nodes/test', payload);
return parseMsg(raw, ProbeResultSchema, 'nodes/test');

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