Commit Graph

4144 Commits

Author SHA1 Message Date
Hamed 1e1b32247e perf(clients): avoid repeated inbound settings reads (#7312)
Reduce repeated inbound settings materialization with a protocol-aware preparation projection that retains node_id. Reuse the locked validation/mutation snapshot while preserving the transaction-time settings reread and three-way rebase. Gate effective Create/Attach Flow before grouped payload construction; retain public Add and bulk/copy semantics.

Preserve #7367 grouped Create, intended-payload fingerprint CAS, ordered turns, cancellation, metadata ordering, durable delete/reattachment safeguards, node outcomes and PostgreSQL lock ordering. Add a mandatory PostgreSQL gate for nine read/protocol regressions without weakening the existing 21 ordering/grouped-create cases.

Validation: all 12 CI jobs passed on 9062e5cf94 (run 46971334865), including PostgreSQL 9/9 and 21/21 focused gates, race, and all four version pairings. Author-reported paired PostgreSQL 16 fixture: 44 -> 22 full reads, 64.82 -> 32.41 MiB materialized per local Create, p95 497.0 -> 400.9 ms; contended Create p95 994.2 -> 633.5 ms and Update 1118.4 -> 937.5 ms. Single-node grouped Create stays one RPC. Necessary protocol/Flow reads and Attach preparation remain; no WAL redesign or production latency claim.

Refs #7300
2026-12-03 00:56:57 +03:30
Hamed 91d5ff400d perf(clients): batch client creation by destination node (#7367)
Group compatible client creates by destination and effective payload via the existing clients/add API. Resolve node-local inbound IDs, preserve distinct flow/address/credential payloads, bound delivery concurrency and use a shared four-second remote delivery budget after local commits.

Advance reconciliation fingerprints only for acknowledged intended settings, retaining previous-fingerprint CAS rather than stamping unrelated rebased changes. Preserve FIFO turns, node-wide barriers, dirty generations, durable delete supersession, partial and uncertain delivery recovery and downstream outcomes. Protect later reattachments in final Delete cleanup and complete Create metadata before remote delivery.

Validation: all 12 CI jobs passed on 63e70cda38 (run 46935177853). PostgreSQL logs confirm 21 ordering/grouped-create tests and prior reporter-lock, reconciliation and traffic contention gates; node E2E confirms all four version pairings. Author reports SQLite/PostgreSQL race tests, make verify and isolated full make race.

Author-reported paired PostgreSQL 18 benchmark: 11 -> 1 RPC, fixed 200 ms peer delay 11-target p95 1552.0 -> 731.9 ms, timeout probe 12.41–12.42 -> 4.41–4.50 s. Size-dependent peer cost can instead cause pending delivery (1.74 -> 4.51 s with 0.74 s recovery); four stalled nodes can defer a fifth. Monitor production convergence and pending rate. No general production latency or allocation improvement claimed.

Refs #7299
2026-12-03 00:08:12 +03:30
Hamed 32e4b8bcfe perf(ip-sync): batch node client IP attribution writes (#7347)
Batch changed node_client_ips rows in bounded deterministic 190-row statements with snapshot CAS, affected-row/replacement-ID checks, whole-GUID rollback and retry, insert-only RETURNING id and guarded pruning. Preserve exact timestamps, canonical no-op skipping, GUID scoping and flat IP-limit behavior.

Integrate independent node polling with transactional reporter eligibility and identity fences. Avoid the reproduced PostgreSQL flat-IP/node ABBA cycle by ordering flat IP DML before reporter validation at commit; retain node-before-attribution ordering for GUID writes and node deletion. Prelock rename and bulk cleanup targets in byte order and reject stale email CAS attempts. Preserve SQLite immediate write transactions, ordered dispatch, durable deletion and existing traffic reconciliation. No network I/O under the new DB locks or global IP-sync serialization.

Validation: all 12 CI jobs passed on c2831ca52f (run 46915194728). PostgreSQL logs confirm delete/rename/bulk lock order, independent reporter progress, lifecycle rollback on disable/delete/endpoint/GUID changes, guarded prune, scanner enforcement and existing durable-delete/reconciliation regressions. Author reports RED SQLSTATE 40P01 on af77a55d, focused SQLite/PostgreSQL race tests, make verify and all four node E2E version pairings.

Author-reported PostgreSQL 16 fixture: 552 -> 4 UPSERTs/round, unchanged 70,656 affected rows, merge p95 387.8–391.1 -> 72.3–81.4 ms, handler p95 16.9–19.5 -> 8.9–11.7 ms. Contention: 2 -> 0 observed deadlocks; corrected 192/192 reports succeeded. Loaded-host tails increased; idle-host repeats did not show a consistent material regression. WAL reduction and production latency improvement are not established. Monitor lock waits and CRUD tail latency separately.

Fixes #7298
2026-12-02 19:46:44 +03:30
Hamed 7a5a25fae2 perf(nodes): reuse client link changes during full reconciliation (#7344)
Reuse client records and successful link diffs during full node snapshot reconciliation. Preserve master-owned comments on existing records while importing new comments; omit comment writes so concurrent operator updates survive. Deduplicate detached IDs across successful inbound savepoints and mark only globally unattached clients in bounded 400-ID batches inside the existing transaction; roll back on orphan-mark write failure.

Integrate against current main while preserving #7314 target-node pending-delete cancellation and cross-node recreation guarantees, #7315 staged traffic and batched baseline writes, and #7308 serialized eligibility checks. Preserve orphan recovery, degraded-inbound safeguards and idempotent snapshot replay.

Validation: all 12 CI jobs passed on 51e627739e (run 46895213148). PostgreSQL logs confirm four new reconciliation tests, both contention/baseline regressions and eight ordering/durable-delete regressions. Author reports focused SQLite/PostgreSQL 18 race tests, make verify and all four mixed-version node E2E pairings.

Author-reported controlled 4096-client PostgreSQL 18 fixture: idle SQL statements 350 -> 270, changing-counter statements 552 -> 472, rows read 151832 -> 102680. Idle writer p50/p95 490/597 -> 430/466 ms; counter writer 489/521 -> 449/519 ms. Idle cycle p50/p95 1118/1277 -> 1015/1050 ms; counter cycle 1121/1172 -> 1046/1135 ms. Worst counter cycle effectively unchanged. These fixture results are not independent production measurements. Production tail latency, shared-client compact-cache reuse and migration coordination remain separate follow-ups.

Refs #7305
2026-12-02 17:44:17 +03:30
Hamed 0db9503228 fix(nodes): isolate traffic sync and report client apply outcomes (#7308)
Isolate traffic synchronization with bounded round-robin per-node workers, independent maintenance and publication, cancellation and ordered shutdown drain. Recheck online eligibility inside the serialized writer before merging snapshots and retain the latest valid speed sample per node, with expiry and explicit empty publication.

Report direct per-node applied/pending/failed outcomes without changing local-save success semantics. Propagate downstream pending separately from direct ACKs so acknowledged batch items do not abort subsequent work. Integrate live admission into the existing #7314 ordered dispatcher with separate four-second queue and batch budgets, retaining monotonic dirty generations, exclusive full-delete/reconcile turns, durable deletion outbox, generation-matched settlement, cross-node recreation safeguards and targeted fingerprint invalidation. Preserve legacy peer compatibility and update generated API documentation.

Validation: all 12 CI jobs and Docs CI passed on reviewed head d13850474f (runs 46871519847 and 46871519831). PostgreSQL logs confirm eight ordering regressions, including saturation, lost ACK, cross-node recreation and bulk recovery. Author reports make verify, focused SQLite/PostgreSQL race tests, four mixed-version node E2E pairings and Xray E2E. No independent production-scale latency measurement or universal HTTP timeout guarantee.

Residual follow-ups: possible conservative false-pending result when a final full delete settles an intermediate superseded intent on the same node; add per-logical-operation settlement regression. Verify shutdown drain under a blocked writer/maintenance worker. These static-review concerns remain open for follow-up, not demonstrated data loss or a new deadlock.

Refs #7293
2026-12-02 16:47:26 +03:30
Hamed 2e0c751a80 fix(nodes): order client pushes outside inbound mutation locks (#7314)
Release inbound mutation locks after durable local commit and reserve conflicting remote dispatch turns in writer commit order. Allow independent inbounds to progress concurrently while reconciliation and full client deletes retain node-wide ordering. Bound queue waits and live batches separately, advance dirty revisions strictly, and invalidate only affected remote fingerprints.

Persist permanent-delete intents transactionally per node/email and replay bounded pages during reconciliation. Match acknowledgements to the queued generation and retain failed/ambiguous deliveries. Supersede pending deletes only when the client is desired on the target node, so recreation on another node does not leave an old orphan record. Preserve pending rows during database migration and accept legacy backups without the outbox table.

Validation: reproduced the cross-node orphan on the previous head; fixed regression passed locally on Lenovo with focused SQLite (9/9) and PostgreSQL 16 (7/7). All 12 CI jobs passed on 5459316fbd (run 46862646487), including race, PostgreSQL migration and durable-first, and node/Xray E2E. PostgreSQL logs confirm all seven ordering tests including cross-node recreation, lost acknowledgement and bulk recovery after database reopen. Branch is up to date with main. No measured production latency claim; requests still wait for their own bounded ordered remote apply. Coordinate overlapping #7308 before its integration.

Fixes #7304.
2026-12-02 14:23:45 +03:30
Hamed bdddb08249 fix(nodes): shorten the traffic merge lock window (#7315)
Stage existing client traffic updates in snapshot order and flush them after client reconciliation to shorten PostgreSQL row-lock lifetime. Keep configuration, traffic counters, renewals and baselines atomic in the same serialized transaction, preserve concurrent last_sub_fetch updates, and retain rollback and idempotent replay semantics.

Batch baseline upserts by (node_id, email) within SQLite parameter limits. Decode snapshot claims before opening the transaction while retaining transactional ownership checks. Add debug metrics for queue wait, writer execution and transaction duration.

Validation: all 12 GitHub CI jobs passed on reviewed head 6dc504b675, including race, PostgreSQL, node and Xray E2E. PostgreSQL CI logs explicitly confirm both contention and baseline batching regressions. The author reports PostgreSQL 16/18 validation, rollback/replay coverage and a reduction from 4,187 baseline upserts to 28 in a local fixture.

Scope: this resolves the reproduced subscription row-lock window, not the full serialized writer hold, shared-client cache restriction, historical 41-second SQL tail or cross-process migration/restore deadlock. These require follow-up. No independent production measurements or successful CI run on the exact latest combined revision were verified before merge.

Refs #7305
2026-12-02 13:02:15 +03:30
Hamed 9f483d9465 fix(inbounds): check WebSocket snapshot size before loading (#7309)
Avoid materializing full inbound settings and client statistics only to discard the snapshot above the existing 5,000-row WebSocket cutoff. Probe user-scoped direct and sibling-backed traffic rows with bounded SQL before loading the snapshot; skip work without subscribers, fall back to invalidation on probe failure, and retain the post-read guard for concurrent growth.

Coalesce WebSocket invalidations by resource in a 200 ms window so paired Inbounds and Clients events refresh both query roots without duplicate same-resource refetches.

Regression coverage exercises the real inbound mutation route and WebSocket hub at and above the cutoff, shared traffic, user scoping, no subscribers, and frontend paired invalidations. All 12 CI jobs passed on the reviewed PR head. The author also reports SQLite/PostgreSQL 16 validation and make verify. Static review of the current merge candidate found no overlapping file changes with main; CI on that exact combined revision was not independently run before merge.

The reported synthetic SQLite notification benchmark (30 inbounds, 7,101 clients, 115,041 associations) improved from 323.87 ms to 0.24 ms and from 324,751,126 to 5,393 allocated bytes per operation. These figures do not establish production HTTP or browser latency improvements.

Fixes #7297
2026-12-02 12:30:15 +03:30
Hamed b2d7a9bb08 fix(panel): break Xray restart deadlock and bound panel reload (#7346)
Fix the production-confirmed ABBA lock inversion introduced in v3.12.0: Xray restart held the lifecycle mutex while synchronously waiting for the serialized traffic writer, which needed the same mutex to amend the committed live configuration snapshot. This blocked API writes and node synchronization, and made panel reload wait indefinitely for cron shutdown.

Run traffic maintenance before acquiring the Xray lifecycle mutex, keep config generation free of writer submissions, and retain the live-snapshot generation guard. Bound panel-only reload with one 75-second deadline across shutdown and startup; fence replacement workers until the old generation drains, and exit nonzero for supervised recovery on failure. Preserve Xray on healthy reloads, gracefully handle termination signals, log phase timings and bounded function-only stack diagnostics, and distinguish accepted restart requests from successful completion.

Validation: all 13 GitHub checks passed on the reviewed head, including Go tests, race, PostgreSQL durable-first/migration, node and Xray E2E, frontend, lint, codegen, vulnerability check and docs. PR validation reports isolated SQLite/PostgreSQL 18 reload tests with 15,844 clients and 30,270 memberships, stable real Xray PIDs, and legacy/current node interoperability.

Addresses the primary deadlock and bounded panel reload; writer cancellation and per-source listener admission diagnostics remain follow-ups. Supervised failure recovery may interrupt Xray sessions.

Fixes #7345
2026-12-02 11:40:21 +03:30
Sanaei 267379456a chore(wirecodec): pin the node encoder's retained-memory budget
Two of the three options that bound the encoder had no test. With the
worker cap removed, or zstd's low-memory mode dropped, every test stayed
green while an encoder built for 64 CPUs retained 154 MiB or 13.7 MiB
instead of 9.1 MiB. Only the 1 MiB window was pinned, through the frame
header.

Build the encoder in newEncoder(cpus) so a test can size it for a
many-core host whatever machine runs it, warm every pooled workspace and
fail above 12 MiB.
2026-11-30 23:20:38 +03:30
Hamed Sanaei bd8648de73 perf(wirecodec): bound node envelope compression memory (#7275)
The shared zstd encoder for master-to-node request bodies was built with
library defaults: one workspace per CPU, each holding a 16 MiB history for
the default 8 MiB window. The pool hands its workspaces out in rotation and
never frees them, so a 4-vCPU master kept about 70 MiB alive after its
first few pushes and a 16-core one about 280 MiB.

Build it with a 1 MiB window, at most four workers and zstd's low-memory
mode, which retains about 10 MiB whatever the CPU count. Callers queue for
a worker on a slot channel, so a cancelled push stops waiting instead of
blocking inside EncodeAll. Frames stay standard zstd: capability
negotiation, the SHA-256 of the uncompressed body and the node's decode
bounds are unchanged.

Closes #7274
2026-11-30 23:16:52 +03:30
Hamed 4a680cb859 fix(sub): export Loon REALITY with the Chrome 147 profile (#7248)
* fix(sub): export Loon REALITY with the Chrome 147 profile

* fix(sub): detect Loon on the default subscription URL

* docs(sub): translate the Loon REALITY import section into fa, ru and zh

The Loon section added to the English REALITY page had no counterpart in
the other three locales, so readers of those pages never learned that the
default subscription URL now serves Loon's native format, or that
format=loon and format=raw select it by hand.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-11-30 22:54:25 +03:30
delifer 6e2589e6c9 Add LibreSpeed functionality to x-ui.sh (#7224)
* Add LibreSpeed functionality to x-ui.sh

I have applied the fixes we discussed earlier to the current version of the PR; please let me know if you have any further questions or comments.

A hashsum check has been added, and the application itself runs with very restricted privileges, as it should.

* Update selection range in x-ui.sh to 0-29
2026-11-30 22:08:05 +03:30
Sanaei 15feed9ea7 chore(security): run the scanner's real-core tests against the go.mod core
The OSS Scanner image pointed XRAY_E2E_BINARY at the release binary that
DockerInit.sh downloads, while CI's `make xray-e2e` builds the core from the
commit go.mod pins. The two are the same commit today (v26.11.9), but they
part whenever go.mod moves to an unreleased commit, and the scanner's baseline
would then run the gRPC tests against a core the panel code was not written for.

The image now builds that core as xray-e2e and points the variable at it; the
release binary stays as /usr/local/bin/xray, which is what a live panel runs.
The comment also named two of the three packages the variable turns on.
2026-11-29 23:37:40 +03:30
Sanaei 6171245fb1 docs(security): rewrite the OSS Scanner threat model against the current code
The model predated several boundaries the scanner should test. It listed only
the monitor and node-sync token scopes, so node-admin, the three route
allowlists and the mTLS-certificate identity were unstated, and it never named
validatePushedInbound, the guard that keeps a node-sync push away from the
receiving host's files and sockets. The MCP endpoint, the public sponsor
routes, the pre-auth listener code, the LDAP login path and the subscription
headers persisted into client_hwids were missing as entry points.

It now states the default configuration a finding may assume, splits each
attacker into the routes and files that serve them, covers third-party content
the panel fetches, and rates end-user limit evasion and revoked-client access
in the severity rubric. The exercise section names each fuzz target's package
and how to mint a restricted token on a live panel.
2026-11-29 23:33:09 +03:30
Sanaei 2bf368e4c1 chore(ci): build the Windows release with the MSYS2 UCRT64 toolchain
setup-msys2 now flags the MINGW64 environment as deprecated and warns on
every Windows build. Move the job to UCRT64 and its matching
mingw-w64-ucrt-x86_64 packages; the compiler triplet is the same, so CC
is unchanged.

The binary now links the Universal CRT instead of msvcrt.dll. UCRT ships
with Windows 10 and later, which is already the floor the Go toolchain
supports.
2026-11-29 23:25:44 +03:30
Sanaei 0ed4e0355c v3.12.0 v3.12.0 2026-11-29 23:08:14 +03:30
Sanaei 645a114d03 chore(deps): update go, frontend, docs and toolchain dependencies
Go: quic-go/quic-go 0.65.0 -> 0.66.0, grpc 1.86.0-dev -> 1.87.0-dev, and
the indirect pion/transport/v5 5.1.6, segmentio/asm 1.2.1, x/oauth2
0.38.0, blake3 1.5.3, x/exp, x509roots/fallback and genproto rpc.
apernet/quic-go, gvisor and xtls/reality stay where xray-core pins them.

Frontend: vite 8.3.8 -> 8.4.0, oxlint 1.90.0 -> 1.95.0, oxfmt 0.78.0 ->
0.80.0, the vitest group 5.1.1 -> 5.1.2 with its @storybook/addon-vitest
overrides, and patch moves of storybook, react-router, react-query,
i18next, msw, @hookform/resolvers, @types/react, lint-staged and
oxlint-tsgolint. fsevents joins allowScripts as denied: it ships a
prebuilt binding, and npm warned about it on every install.

Docs: lucide-react 1.83.0, mermaid 12.4.0, oxlint 1.95.0, oxfmt 0.80.0,
vitest 5.1.2 and patch moves. pnpm appended no release-age waiver and
gen:api leaves the API reference untouched.

Toolchain: pnpm 12.16.1 -> 12.23.0 in docs packageManager with its
sha512 hash. Go 1.27.4 and Node 26 are already current.

oxlint 1.95.0 puts the React Compiler rules in the correctness category
and reported 15 errors in 12 files, fixed here rather than silenced:

- The log, version, geodata and API-token loaders fetch inside their
  effect and drop a reply the user has already moved past, so a slow
  response no longer overwrites a newer one (test added for LogModal).
- ClientsPage, ClientFormModal, CloneInboundModal and DnsTab reset
  state while rendering instead of in an effect; on the clients page a
  filter change no longer issues a request for the stale page first.
- Refs are no longer written during render: the clients row lookup and
  the advanced JSON editors seed them outside it, and
  OutboundSubtreeJsonForm reports through useEffectEvent.
- The mobile client card's info action is a real Button, like the
  action next to it.

Four antd props that lint:deprecated already rejected on main are
replaced too: Space direction, and filterOption / optionFilterProp
outside showSearch.
2026-11-29 22:47:27 +03:30
Sanaei 99b3363c28 chore(deps): mark go.uber.org/atomic as indirect
Nothing imports it directly since the lifecycle change moved the pending
restart flags to sync/atomic (#7264); go mod tidy has wanted this line moved
ever since.
2026-11-29 22:05:42 +03:30
Sanaei 772270c7e6 fix(xray): refuse a config whose new socket the core cannot bind at all
The guard that keeps a working core from being replaced by a config it cannot
bind only knew one reason: another process holds the port. An inbound whose
listen address the host does not have, or whose port the panel is not allowed
to bind, went the same way as that one did: the new core exited at start and
the watchdog restarted it every two seconds with every inbound down.

The probe now names those two failures as well. A tproxy inbound is excused
from the address check: IP_TRANSPARENT lets the core bind an address the host
does not hold, which the probe cannot do. The permission check assumes what
the shipped units give: the core is the panel's child with the same
privileges. A core granted file capabilities the panel lacks would be refused
a port it could bind.

Checked against the pinned core on its own: it exits 255 on a missing address
and on a denied port, and starts on the missing address with tproxy. On a
running panel an inbound on 192.0.2.1 was refused with the core's PID and the
other inbound untouched, and came up by hot apply once its listen was fixed.

The case that left a missing address to the core is replaced: that was the
previous commit's scope, not a rule.
2026-11-29 22:05:42 +03:30
Sanaei 07e41c8287 fix(xray): keep the running core when another process holds a new inbound's port
A config the core cannot bind must never replace one that works: the new core
exits at start and the watchdog then restarts it every two seconds with every
inbound down. The guard only looked for two inbounds of the same config sharing
a socket, so an inbound saved on a port some other process holds went through:
the hot apply failed, the restart followed, and the panel looped on
"address already in use" until the inbound was removed.

Before replacing a running core, bind each socket the new config adds the way
the core will (it sets SO_REUSEPORT on every listener) and refuse the config
when the address is in use. Sockets the running config already serves are the
core's own and are not probed. The refusal is reported like the existing bind
conflict, on the status page and in the log, and the next tick applies the
config once the port is free.

Run on a panel with the real core: with the port held, the core kept its PID
and the other inbound kept serving with no failed probe in 60 s; the inbound
came up by hot apply on the first tick after the port was released.

A listen address the host does not have, or a port the panel may not bind, is
still left to the core's own error.
2026-11-29 21:49:04 +03:30
Sanaei d4ce11954d fix(clients): end a removed client's sessions without waiting on a config diff
With restart-on-client-disable on, a client the API removes from a running
inbound must be followed by a core restart: the removal drops the credential
only. The apply layer asked for that restart by setting the generic
need-restart flag, and the tick then restarted only when the generated config
differed from the running-config snapshot. A client added over the API is not
in that snapshot, so disabling or deleting it before any reconcile diffed as
"no change" and its live session kept passing traffic.

The removal now queues the session-drop restart itself, through the request
the depletion path already uses, so the tick replaces the core whatever the
snapshot holds. Detaching a client and bulk delete removed clients the same
way without asking for anything; they queue it too. WireGuard is left out: its
session ends with the peer.

The pending flag and the protocol predicate lose "depletion" from their names
now that manual removals share them.

Run on a panel with the real core: a client added after the core started,
holding a stream open, was cut and the core replaced within one tick of its
disable; before the change the stream ran on and the core kept its PID.
2026-11-29 21:48:57 +03:30
Sanaei 1526e118df test(xray): judge only the log lines the rejected hot apply adds
The test counted every hot_apply_failed restart in the package's shared log
buffer and required exactly one. Any other test that makes a core restart for
that reason, or the same test run twice with -count, made it fail for a line
it did not write. It now compares the buffer before and after its own restart
and checks the newest entry.
2026-11-29 21:48:47 +03:30
Hamed c7f5850e5f test(node): cover counter resets on PostgreSQL (#7272)
The three regressions for a node counter that restarts below its baseline, and the migration test for the column that fix added, shared fixed node ids and inbound tags. Run as a group against PostgreSQL, the database in the report, the second one failed on a duplicate key before reaching the code under test.

Give each case its own PostgreSQL schema and run all four in the PostgreSQL CI job, requiring four passes. No panel code changes; the fix itself is already on main in 408fd682.

Refs #7271
2026-11-29 18:55:46 +03:30
Hamed 1ec55aed30 perf(node-sync): avoid redundant full inbound snapshots (#7014)
Every five seconds the master fetched each node's complete inbound list, settings JSON and enrichment included, parsed it and reconciled every client, whether anything had changed or not.

A node that advertises traffic-snapshot-v1 now answers a revisioned endpoint: counters and lifecycle state on every poll, inbound configuration and attachments only when its revision changed. The master skips structural parsing and client reconciliation while the node's revision, its own rows for that node, the lifecycle state and the full remote-to-central inbound mapping are all unchanged; anything else falls back to the full merge. Old and new panels keep talking through the previous endpoints.

Revisions come from a hidden per-row token on inbounds and clients, maintained by database triggers on SQLite and PostgreSQL so that direct and background writes count too. Counter and timestamp updates leave it alone. The triggers are dropped before migrations and recreated after them, and the previous build runs unchanged on a database that carries them.

Measured here at 20,000 clients on one node, per idle poll: master SQL statements 551 -> 44, node statements 55 -> 4, transfer 23.0 MB -> 4.8 MB. When every client is shared between nodes the ownership checks keep the full master merge, so only the node and the transfer get cheaper. The node still reads every membership and counter on each poll.

Closes #7007
2026-11-29 18:38:51 +03:30
Hamed a9d22498c2 feat(traffic): separate depletion restarts from client disables (#7267)
One switch decided two things: whether Xray restarts when a client is disabled or deleted by hand, and whether it restarts when a client runs out of quota or expires. A panel that takes many API deletes had to choose between a restart on each of them and leaving depleted clients' open connections alive.

Add a switch for the quota and expiry case. It inherits the old switch until it is saved, and older settings clients may omit it. A depletion asks for one restart per affected running core per committed batch: the local core when a local inbound served the client, and each affected node through the node API. A master whose nodes alone served the client is not restarted. With the new switch off, a depleted client is still removed from the running core and from its config snapshot, so a later reconcile does not restart for it either.

Also add a node traffic fetch timeout setting (1 to 30 seconds, default 4).

Run on a panel with real cores: with the old switch off and the new one on, a stream through a client that crossed its quota was cut within one poll and the lifecycle log names client_depletion; with them swapped, the stream and the core survived. A depletion a node detects itself follows that node's own switches.

Refs #7145
2026-11-29 18:25:19 +03:30
Hamed be2a2e9e71 perf(nodes): scope expiry repair to activated clients (#7241)
Every node snapshot merge ran a table-wide UPDATE that copies a node-activated deadline onto client records still holding the start-after-first-use duration, whether or not that snapshot activated anyone.

A merge now repairs only the clients it activated or renewed in that tick, and a snapshot with no such transition issues no UPDATE. Older drift (legacy imports, a tick whose client reconciliation was skipped) is repaired by the five-minute maintenance job in windows of 4,000 client ids, which also covers standalone panels. A failed repair now fails the merge on SQLite as it always did on PostgreSQL, where the transaction was already aborted.

Verified on SQLite and PostgreSQL 18: the previous code rewrites an unrelated client's expiry on every merge, and without the scoped lift a record on a tick that cannot rebuild client records keeps its negative duration.

Fixes #7233
2026-11-29 18:12:13 +03:30
Hamed b1cec64b18 perf(nodes): target orphan recovery during client reconciliation (#7240)
Every node snapshot merge ran a clear-orphan-marks UPDATE over the whole clients table, marked rows or not. On a PostgreSQL master with thousands of clients that was a full scan every five seconds per node, inside the single serialized writer.

A merge now clears marks only for the clients it reconciled, and an unchanged snapshot issues no orphan statement at all. Marks left on still-attached clients by older builds, restores or imports are repaired by the existing five-minute reaper, in the same transaction that decides what to delete, and a client that loses its last link has its stale mark cleared first so the reaper cannot delete it without a grace period.

Verified on SQLite and PostgreSQL 18: the previous code repairs an unrelated mark on every merge and reaps a legacy-marked client right after it is detached.

Fixes #7231
2026-11-29 17:55:47 +03:30
Hamed 4954b032f1 feat(nodes): show live network throughput (#7249)
Comparing current traffic across nodes meant opening each node's history chart. The heartbeat already carries every node's upload and download rate.

Show both rates in a stacked column of the Nodes table, between Memory and Xray Version, and in the mobile detail dialog, which now follows heartbeat updates. A measured idle link reads 0 B/s; a disabled, offline or transitive node, a peer too old to report throughput, and a sample older than 30 seconds read as a dash. The sample's age is computed on the master and anchored to when the browser received it, so a skewed browser clock does not blank the column.

The probe now records a missing or invalid direction as unavailable where it used to store zero, so such peers also stop adding zero points to the history chart.

Fixes #7238
2026-11-29 17:44:53 +03:30
Hamed 5d2d068484 feat(traffic): make the external traffic inform interval configurable (#7266)
The external traffic webhook was sent from inside the 5-second accounting job: its cadence could not be changed, and a slow receiver held up accounting.

Add an interval setting (5 to 3600 seconds, default 5). The accounting poll only sums each tick's deltas per client email and per inbound or outbound tag; once the interval has passed, the batch is posted from its own goroutine. Accounting, quota enforcement and online updates keep their 5-second cadence.

Delivery semantics are unchanged: each batch is posted once. A failure drops it, warns once with the reason (never the URI) and reports when deliveries resume. Destinations are checked at dial time and redirects are refused. A settings client that omits the interval keeps the stored value.

Fixes #7028
2026-11-29 17:28:55 +03:30
Hamed b13c6d9be9 perf(clients): persist reconciled timestamps in one write (#7242)
Reconciling a client record whose fields changed wrote it twice: Save stamped updated_at with the current time, then a second UPDATE put the agreed timestamp back. A PostgreSQL master with about 7,000 clients counted roughly 179,000 of each in 50 minutes.

Run the Save through a session whose clock returns the agreed timestamp, so GORM's hooks and serializers still run and one UPDATE carries the right value. An unchanged row still writes nothing. Verified on SQLite and PostgreSQL 18: one UPDATE per changed row, where the previous code issues two.

Fixes #7234
2026-11-29 17:17:36 +03:30
Sanaei 8205a5be6a chore(repo): untrack the node_modules link that #7263 carried in
The squash of #7263 included frontend/node_modules as a symlink to a local
path. It was a worktree link that the node_modules/ rule does not ignore: a
trailing slash matches only a real directory. Pulling that commit replaced an
installed, ignored frontend/node_modules directory with the dangling link.

Remove the link and ignore node_modules whether it is a directory or a link.
Anyone who pulled main in between needs npm ci in frontend/ again.
2026-11-29 17:05:44 +03:30
Hamed 783e0c5438 feat(xray): report managed core lifecycle outcomes (#7264)
At the default log level an operator could see the Xray child PID change many times a day without learning which of those changes the panel caused, or why.

Write one xray_lifecycle line for every real start, stop, restart, hot apply, rejected config and unexpected child exit. It carries the old and new PID, the path that asked (manual, watchdog, client depletion, pending restart and its first trigger, ...), a fixed reason, the force flag, the duration, the hot-apply outcome and the previous child's exit code or signal. An unchanged config still emits nothing and restart policy is unchanged.

A hot apply the core refuses also logs the core's own error once, with the inbound tag or client it concerned, so a restart labelled hot_apply_failed can be traced to its cause.

Fixes #7260
2026-11-29 17:03:00 +03:30
Hamed ea80681eb2 perf(traffic): size live client deltas by active rows (#7265)
splitMovedClientTraffics reserved room for every registered client before filtering down to the ones that moved bytes. On a large panel where almost everyone is idle, that was megabytes of unused slices and map buckets on every five-second poll.

Count the moved rows first and size the slices and the email set from that count. Order, set membership, zero-delta filtering and the non-nil empty results are unchanged. Measured here at 50,000 rows with 1% active: 2.95 MB -> 39.6 KB and 109 -> 60 us per call; with every row active it costs about 4% more time for the same allocations.

Fixes #7262
2026-11-29 16:48:36 +03:30
Hamed 47565b71d3 fix(traffic): require a URI for external traffic notifications (#7263)
External Traffic Inform could be saved enabled with a blank URI. Every traffic tick then built the full payload and POSTed it nowhere, logging one "missing port in address" warning per tick (about 17,000 a day in the report).

Refuse the save when the switch is on and the URI is empty. A database that already holds that state skips the notification before the payload is built and warns once per episode, naming why the destination was refused without echoing a malformed URI. Local traffic counters and last-online times are still committed on the skip path.

Fixes #7261
2026-11-29 16:35:47 +03:30
Hamed 075fcb4001 docs(amneziawg): explain boot loading and kernel upgrades (#7247)
The reboot fix from #7194 registers the module in modules-load.d, but hosts installed with an older build still lose kernel mode after a reboot and had no page telling them to rerun install-awg-kernel.

Document how to pick up boot registration, how to tell the installed module from the loaded one, why modinfo's version can differ from the source tag, and why a module update needs a maintenance reboot.
2026-11-29 16:00:29 +03:30
Nikan Zeyaei c9a2e0c237 fix(i18n): relabel Russian 2FA code field for password managers (#7259)
1Password for Safari does not show its Universal Sign-In banner on the
Russian login form, because the label 'Код 2FA' is not recognised as a
one-time-code field. Use 'Одноразовый код' instead; the field already
has autocomplete=one-time-code. The key's only other use is an aria-label
in the 2FA setup dialog.

Fixes #7258
2026-11-29 15:34:46 +03:30
Sanaei 2cfeec3b99 feat(cli): name the inbounds a settings reset leaves on the panel's ports
x-ui setting -reset puts the panel back on its default ports, 2053 and
2096 for the subscription server. An inbound already listening on one of
them then shares a socket with the panel, and Xray cannot start. The
other writers of those ports refuse such a change, but a reset is the
way back into a panel whose port was forgotten, so it must not be
refused.

After the reset the command now lists every enabled local inbound that
collides with a panel socket and says that Xray will not start until one
of the two moves. Disabled inbounds are left out: they bind nothing, and
enabling one is refused by the port check.

Printing the lines from main.go is wiring no test reaches; running
x-ui setting -reset on a database with inbounds on 2053 and 2096 prints
one warning for each.
2026-11-29 15:08:07 +03:30
Sanaei 8849518f50 fix(inbounds): refuse an inbound on a socket the panel itself listens on
The panel binds its web and subscription sockets before Xray starts, so
a local inbound on either leaves Xray unable to listen at all. Nothing
compared an inbound with those two sockets. Restoring a backup with this
machine's settings kept could therefore import a tunnel on the panel's
own port: the database was swapped first, and the failure only showed
when Xray would not start.

The rule is now stated once and every writer goes through it:

- A restore reads the backup's inbounds and the settings that will be in
  force afterwards (this machine's for kept keys, the backup's for the
  rest, XUI_PORT over both) and is refused before Xray is stopped or the
  database touched. All three paths do this: a SQLite file, a SQLite
  file imported into PostgreSQL, and a pg_dump archive, whose two tables
  pg_restore prints as a data script without a connection. Only enabled
  rows refuse a restore, so a backup holding a disabled leftover stays
  usable; enabling that row later is refused by the port check.
- Adding, editing and enabling an inbound run the same check.
- Saving panel settings, and x-ui setting -port / -listenIP, refuse to
  move a panel socket onto an inbound. A collision that already exists
  does not block later saves. The x-ui menu no longer reports a refused
  port or listen address as set.

One existing test put its inbound on 2053, the default panel port, for
no reason of its own; it now uses 2083.

Not covered: x-ui setting -reset and a changed XUI_PORT can still put
the panel on an inbound's port.

The PostgreSQL paths were run against PostgreSQL 18 with its pg_dump and
pg_restore; CI skips those tests. make node-e2e passes.

Closes #7115
2026-11-29 15:00:26 +03:30
Sanaei af917bc0af fix(clients): keep the client form footer inside a phone screen
The "Usage & change history" button made the edit form's footer four
labelled buttons in one row that cannot wrap. On a phone that row is
wider than the modal, so the modal grew past the screen and Cancel and
Save ended up outside it.

Below 768px the two extra actions, Reset Traffic and the history button,
now show only their icon and keep their name as an aria-label, so the
row fits again. The row may also wrap, as a guard for a locale whose
Cancel and Save labels are unusually long. Wider screens are unchanged.

Layout is out of reach of the jsdom tests. Measured in headless Chromium
at 360px on a running panel: before, three of the four buttons lay
outside the viewport; after, all four sit on one row inside it in
en-US, fa-IR and ru-RU, and at 1280px the labels are still shown.
2026-11-29 15:00:25 +03:30
Sanaei c23e1cb231 feat(nodes): show how many clients are online on the node itself
Since a69f2dee a node's online report is cut to the clients linked to
its inbounds on this panel, so a node that also serves inbounds the
panel does not import (inboundSyncMode=selected, or inbounds created on
the node) shows only part of its load, and an operator cannot tell a
busy node from an idle one.

The panel now counts the distinct clients in the node's own entry of
that report before the cut and keeps the number only: the emails of
clients it does not manage are still dropped, so they cannot mark
another client online or reach the IP limit. The count needs no new
node endpoint, so nodes on older builds report it too, and it is
dropped together with the node's online clients when the node is no
longer synced.

The Nodes page shows it as "synced / total" in the online tag when the
node reports more than the synced count. Transitive sub-nodes carry no
total: the panel takes no counts from an intermediate node.
2026-11-29 13:47:59 +03:30
Sanaei 32615e1d76 fix(mtproto): stop claiming mtg auto-detects the public IP for ad-tags
The Public IPv4/IPv6 hint told operators to leave the field blank so mtg
would detect the address itself. mtg-multi has no such detection for the
middle proxy: with the field empty it feeds its socket's local address
into the middle-proxy key schedule, which only matches what Telegram
sees when the public IP sits on the server's own interface.

Behind NAT or a Docker bridge the handshake is refused, so every
connection of an ad-tagged client spends 5-7 seconds on the middle proxy
before falling back to a direct connection, and the sponsored channel
never appears. Measured against real Telegram with a tagged and three
untagged clients; the untagged ones were unaffected.

The hint in all 14 locales now says when blank is correct and when the
address must be entered. The two code comments repeating the claim are
corrected with it.
2026-11-29 13:21:29 +03:30
Sanaei 22fe0c4cd9 feat(mtproto): record client IPs and enforce the IP limit for MTProto clients
Every client the panel serves has its connected addresses recorded and its
IP limit applied, whichever process carries it. MTProto clients are served
by mtg, never by Xray, so the core's online list could not see them: their
IP log stayed empty and a configured limitIp never fired, although the form
offers both for every protocol.

mtg-multi 1.17.0 reports users.<name>.active_ips in /stats. The manager
keeps them from each scrape together with the time an address was first
seen connected, so the scan can keep the newest addresses and ban the
oldest, and the IP scan merges them the way it already merges kernel-mode
AmneziaWG peers. A failed scrape drops the addresses instead of leaving
them live, and loopback addresses (a relay in front of mtg) are skipped as
the core skips them.

Enforcement is the existing fail2ban path. The temporary credential drop
is Xray-only, so on Windows, where it is the only mechanism, an MTProto
limit is recorded but not enforced.
2026-11-29 12:13:19 +03:30
Sanaei 3e1fc3c24f fix(mtproto): stop relaying strangers to the fronting CDN, count fronted traffic
An MTProto inbound must not relay a stranger's connection to a public host
picked by an SNI the panel never configured, and every byte it moves must
show up in the inbound's traffic.

mtg relays whatever it cannot serve as a proxy to the fronting target, byte
for byte, and the target answers by the SNI of that connection. With the
default FakeTLS domain on a CDN, anybody could reach any site of that CDN
through the inbound ("clean IP"). mtg dials the target itself, past the
Xray bridge and outside every secret, so neither the clients nor the
inbound showed that traffic.

- The generated config sets [domain-fronting] require-sni-match (mtg-multi
  1.17.0) unless the fronting IP is a loopback, private or link-local
  address, i.e. the operator's own web server. mtg then relays only a
  ClientHello naming the FakeTLS domain and closes the rest. An older mtg
  ignores the key.
- The /stats "fronting" counters are scraped per process and added to the
  inbound's total, for routed inbounds too.

TestRenderConfig pinned the old rule (a bare config has no
[domain-fronting] section) and now expects the section without a host.
2026-11-29 12:05:06 +03:30
Sanaei 6d9a23feb5 style(tests): clear the editor diagnostics in the service tests
The config scale benchmark used the b.N loop that gopls flags for modernization; it now uses b.Loop, which also makes its ResetTimer and StopTimer calls redundant. assertInboundClientGroup and seedUsageHistoryClient each took a parameter they never read, so the parameters and the arguments passed for them are gone.
2026-11-29 11:31:20 +03:30
Sanaei 408fd682f5 fix(node): count a restarted node counter once while its client is frozen
While a client's lifecycle was frozen (node config_dirty, a push that just landed, a reset the node still owes, or a client the node only reports usage for), a node counter that fell below the stored baseline left that baseline untouched. The other field's growth was still added to the client, and because the baseline never moved the same amount was added again on every sync tick: an idle client gained gigabytes per minute and was cut off. A client whose counters stayed below the old baseline had the opposite problem, and none of its usage was counted.

The baseline was held back on purpose (#6228): the dip is the evidence that the node renewed the client, and it had to survive until an unfrozen tick could judge it. The baseline was doing two jobs. It now always follows the node, so a delta is added once, and the unjudged dip is kept in a new node_client_traffics.dipped_while_frozen column that the first unfrozen tick consumes.

A renewal seen while frozen is now also adopted when the client's usage has since outgrown the pre-renewal baseline; before, that evidence was lost.

Usage already over-counted cannot be recovered and needs a manual reset. A baseline that is stuck at upgrade time adds its delta one last time on the first sync and is correct from then on.
2026-11-29 11:31:20 +03:30
Sanaei 2db45393cf fix(iplimit): install the iptables tools the ban action needs
The 3x-ipl Fail2ban action bans with iptables and ip6tables, but the setup installed only fail2ban and nftables. Debian 12/13 and Ubuntu 22.04/24.04 do not pull iptables in with fail2ban, so on a host without it every ban logged "iptables: not found", showed up in the jail's banned list and applied no rule, while the setup reported success.

A configured 3x-ipl jail now always has its ban tools. Writing the action installs them when they are missing, and so does an update over a jail an earlier release set up, whether the choice is stored or not. A jail that is already running is restarted after the install so bans it recorded without a rule get one. When the tools cannot be installed the setup fails with the reason instead of writing a jail that enforces nothing.

The lifecycle fixture now models the tools as present, so its cases no longer depend on the host running the tests.
2026-11-29 11:02:51 +03:30
Hamed 428dfe7709 fix(iplimit): persist Fail2ban enforcement consent (#7239)
Removing IP Limit from the x-ui menu saved nothing, so the next update, reinstall or panel self-update installed Fail2ban again and re-enabled the host-wide 3x-ipl jail.

The choice is now written to the panel's env file and every later install and update reads it first. A fresh native install asks before enabling enforcement (Enter declines) and an unattended one enables it only with XUI_ENABLE_FAIL2BAN=true; a stored choice wins over the process environment. Hosts that already have the jail configured and nothing stored are left as they are. The menu restarts the panel so it runs with the same value, and OpenRC exports it to the service.

Removal and reload touch only the managed jail, and the package is uninstalled only when 3x-ipl is the sole jail, so a distro-enabled sshd jail keeps Fail2ban installed. The journal backend override for Debian 12+ and Ubuntu 22.04+ now targets the stock sshd jail and leaves operator backend and log settings alone.

Fixes #7222
2026-11-28 18:13:26 +03:30
Hamed 75dc6dc61c fix(inbounds): scale bulk client attachment selection (#7243)
With around 10,000 clients both attach dialogs loaded every client, pre-selected all of them and rendered every row, which locked the browser for minutes.

Both dialogs now ask the server for 100 rows at a time and render only the visible ones. Select All freezes the eligible client IDs that match the current search and group into a small server-issued token; the browser keeps that token plus the clients the operator unticked instead of thousands of emails, and the listing marks each row against the frozen filter so rows outside it stay unselected. On submit the server re-derives the same set and rejects the job before any write when its membership changed; clients created after the freeze stay outside it. The attach runs as a background job the dialog polls for counts.

Requests that post an email list keep their synchronous response. The Postgres job now runs the selection tests, which build their predicates by hand for both dialects.

Fixes #7236
2026-11-28 18:00:53 +03:30
Hamed 9088b8a768 fix(traffic): count the first managed Xray sample (#7246)
The traffic poller treated the first stats reply of every core as a baseline and credited none of it, so whatever clients moved between an Xray start and the first poll never reached their committed usage. A restart on the same API port also kept the previous core's last values, which under-credited the new core by that amount, and by all of it when the new counter had not yet passed the old one.

Track the baseline by process identity instead: a core the panel has just started counts from zero, and the poller keeps its own API client so a restart issued by any other service value cannot leave stale values behind. A panel-only reload keeps the same process and is not counted again. A generic API connection to a core with unknown counter history still takes a baseline first.

Fixes #7211
2026-11-28 17:43:35 +03:30