3426 Commits

Author SHA1 Message Date
Gleb Gudkov ed6bc1d898 docs(api): align OpenAPI with runtime contracts (#6409)
Document the cookie-authenticated WebSocket upgrade and its emitted envelopes without exporting pseudo-paths. Align REST response schemas, paged-client filters, and subscription HEAD operations with their runtime implementations, then regenerate frontend and docs artifacts.
dev-latest
2026-09-04 15:23:41 +02:00
Sanaei 3b5273b1d6 fix(amneziawg): reject obfuscation values amneziawg-go's own UAPI rejects
ValidateObfuscation exists, by its own doc comment, so that a bad manual
entry cannot break the embedded device's IpcSet. It was not covering enough
to do that. Auditing the panel against amneziawg-go v3.1.20260828's full
UAPI surface turned up two holes, both confirmed by driving the values
through a real IpcSet:

  S1 = 70000        upstream parses s1-s4 as uint16
  S2 = 70000        (device/uapi.go)
  Jc = -1           jc/jmin/jmax are uint32, so no negatives
  Jmin/Jmax = -5/-1
  Jc = 5000000000   and nothing wider than uint32
  I1 = <rand 100>   newObfChain hard-fails on an unknown tag
  I1 = <r 100       ... and on a missing '>'
  I1 = <>           ... and on an empty one

All eight passed validation and were then rejected by the device. Only S3
and S4 were bounded, which is why the asymmetry went unnoticed. The inbound
saves, the reconcile fails on every tick, and the interface never comes up
with a single log line to say so.

Bound the five numeric fields to the widths upstream actually parses, and
check the I1-I5 chain's <tag value> structure against a tag set mirroring
upstream's own obfBuilders map. Each tag's value grammar stays amneziawg-go's
to enforce -- that is eight builders across several files, and duplicating
them here would drift. So <r abc> still reaches IpcSet, now as the only
remaining class rather than one of four.

Mirror the same bounds in the Zod schema, next to the max() that s3 and s4
already carried, so the form rejects the value instead of the save doing it.

TestValidatedObfuscationAlwaysApplies pins the contract itself: whatever
ValidateObfuscation accepts, a real amneziawg-go device must accept too. It
covers the specs the new grammar check deliberately allows, not just the ones
it rejects, so the allowlist cannot quietly become stricter than upstream.

The rest of the audit found no gaps: all 17 settable device keys reach
buildUAPIConfig, ServerSettings, the Zod schema and all three .conf
emitters. fwmark and persistent_keepalive_interval remain unemitted, both
deliberately -- the panel models no fwmark anywhere, and keepAlive is carried
client-side where WireGuard puts it.
2026-09-04 14:57:29 +02:00
Sanaei be5ee3e0e1 fix(amneziawg): three defects in the embedded relay's connection handling
Half-close. Both TCP relays -- RelayTCP into Xray's SOCKS5 inbound and
relayTCPForward into a peer's tunnel address -- waited on a single `done`
receive and then closed both sides. A client that finished sending and shut
down its write side therefore had the connection torn down before the
response came back. pipeBothWays now runs both directions to completion and
propagates the half-close via CloseWrite (which *net.TCPConn and
*gonet.TCPConn both implement), falling back to a full Close for anything
that does not.

Waiting for both directions reintroduces the risk the old single-receive was
implicitly avoiding: a peer that vanishes mid-transfer would pin the pair
forever. guardedReader bounds that, but as an idle window rather than a
total one -- the deadline is re-armed on every read once armed -- so a slow
transfer is never cut, while a silent peer is. Two minutes matches the idle
window UDPRelay.pump and portForwardUDPIdleTimeout already use.

UDP session retirement. pump's teardown deleted the map entry by key alone,
so a session that lost a create race evicted whichever session currently
held that source, orphaning a live flow. It now retires only its own entry,
and Handle keeps the already-published session when it loses the race. The
map is keyed on netip.AddrPort rather than src.String(), matching
udpForwardListener next door and dropping one allocation per relayed
datagram.

SOCKS5 reply decoding. bytesReader had a value receiver, so each Read
restarted at the head of the slice, and receive never advanced past a
domain-form address because its switch only handled ATYP 0x01 and 0x04 -- a
0x03 reply decoded to a wrong source, port and payload. splitSocks5Addr
replaces it: all three address forms, length-checked at every step, with the
domain form accepting only a literal. Resolving there would have put a
blocking DNS lookup on the receive path, and a datagram's own source is an
address already. Unreachable against Xray's own inbound, which always
answers with an IP, so this is a latent-bug fix rather than an observed one.
2026-09-04 14:57:11 +02:00
Sanaei 24cb6bfe1f perf(amneziawg): return gVisor's pooled buffers on the embedded data path
Every packet crossing the embedded AmneziaWG interface allocated instead of
reusing gVisor's pools, in both directions. stackTun.Write injected each
decrypted packet and never called DecRef, so the packet buffer and its chunk
were never returned; stackTun.Read copied each view out and never released
it. gVisor's own link endpoints settle the ownership question -- loopback.go
and sharedmem.go both DecRef immediately after DeliverNetworkPacket, because
the injector owns the buffer.

AttachUDPHandler compounded it by cloning a packet buffer it then dropped on
the floor, on top of a Data().AsRange().ToSlice() that already returns an
owned copy, so the clone bought nothing and stranded a pooled buffer plus a
cloned view per datagram.

Measured with the benchmarks added here:

  stackTunWrite (upload)     794ns -> 107ns   4 -> 0 allocs
  stackTunRead  (download)   707ns -> 129ns   3 -> 0 allocs
  UDP datagram, end to end  2.69us -> 1.58us  8 -> 2 allocs

The remaining UDP allocation is the ToSlice copy itself. Through a real
handshaked tunnel -- both devices in one process over loopback, so
ChaCha20-Poly1305 and the UDP syscalls dominate -- it is worth -48% bytes/op
and -33% allocs/op, and about +4.8% throughput in each direction (n=18,
p<=0.01). On a small VPS, where the allocation pressure is not spread over
24 idle cores, the throughput share should be larger; that part is reasoning,
not something measured here.

The three regression tests assert allocations per packet rather than timing,
since the defect is the pool miss, not the nanoseconds. Thresholds leave room
for the extra allocation -race adds.
2026-09-04 14:56:54 +02:00
Sanaei d34ec97f62 perf(node): push a client edit to every node at once, not one after another
Editing, deleting or detaching a client on a master with several nodes took
one node round-trip per node, added end to end. Create and Attach already
fanned their per-inbound applies out through fanoutInboundClientAdds, but
Update, Delete, Detach and DeleteByEmail's record-less fallback still walked
their inbounds in a plain sequential loop, and each iteration blocks on a
node RPC (10s timeout, more when a node is slow or has just gone unreachable
and the heartbeat has not marked it offline yet).

Measured with a node runtime injecting 100ms per RPC, before:

  nodes=1  create=101ms  update=101ms  delete=101ms
  nodes=3  create=102ms  update=303ms  delete=302ms
  nodes=5  create=202ms  update=504ms  delete=504ms

after, all three track create:

  nodes=3  create=102ms  update=102ms  delete=101ms
  nodes=5  create=203ms  update=203ms  delete=203ms

Generalize the existing helper into fanoutInboundApplies over an inboundApply
list and route the four remaining loops through it, so they inherit the same
concurrency cap, per-inbound panic recovery and joined errors. Each caller
still builds its payloads sequentially first: fillProtocolDefaults mints the
shared credentials on the first inbound and every later one reuses them, so
that order has to stay deterministic. Only the applies overlap; their DB work
still serializes through the single traffic writer, and the per-inbound
mutation lock is unchanged, which is exactly what Create has relied on.

Behaviour change: one failing inbound no longer aborts the remaining ones,
matching what Create already does. The error still names each failed inbound
and the record-level writes are still skipped when any inbound failed.

The snapshot merge on the same serialized writer was measured as a second
suspect and cleared: ~43ms per node at 500 clients, an order of magnitude
below the RPC serialization.
2026-09-04 11:39:56 +02:00
Sanaei 3ef06b7000 docs(readme): refresh all seven READMEs for the current feature set
The READMEs had not moved since 2026-07-07, 341 commits ago, and had
drifted far enough to misdescribe the panel: AmneziaWG and MTProto
inbounds were missing from the protocol list entirely, the outbound
list predated PIA, and the API section still advertised Swagger rather
than scoped, optionally expiring tokens.

Add the two missing protocols plus a bullet each for what makes them
notable — AmneziaWG runs on the embedded userspace netstack, so unlike
the DKMS/awg-quick shape it originally shipped with there is nothing to
install, and MTProto client edits hot-apply through the mtg-multi
management API instead of bouncing the process. Fold the smaller
additions into the bullets they belong to (HWID device limits, IP-limit
exemptions, renewal cycles, inbound cloning, balancer-to-balancer
fallback, geosite/geoip browsing, named subscription formats) and add
one for PWA installability.

Point documentation at docs.sanaei.dev, which the panel sidebar already
links to and which supersedes the wiki, using each README's own locale
where the docs site has one (fa/ru/zh). Bump the pinned install example
to the current stable tag, note the .sha256 verification install.sh and
update.sh now perform, and document XUI_NODE_TOKEN_KEY_FILE /
XUI_NODE_TOKEN_KEY, which no markdown in the repo covered.

All seven files move together so the language picker keeps pointing at
equivalent documents.
2026-09-04 09:49:25 +02:00
Sanaei 2e81865a02 style(node): tighten the comments and probe assertion from the QA pass
Two follow-ups on the preceding fixes, no behaviour change:

- The sweep comment in inbound_node.go had grown to a contiguous six-line
  block, over the two-line maximum. The prefix rationale it carried is
  already stated by nodeSelectedTagSet itself and by 6f40a51d's message.
- The probe cap test asserted only that an error came back, which cannot
  tell a size rejection from a transport failure or a success=false
  envelope. It now pins LastError to the decode rejection.

Both remain red-first: neutralizing maxProbeBodyBytes still fails the probe
test on the new assertion.
2026-09-04 02:48:44 +02:00
Sanaei 5fc4b9f463 fix(node): let a node-reported tag outrank a stale adopted alias
The alias re-application added in 0775fcaa wrote every adoptedAliases entry
onto the rebuilt map unconditionally, so an alias could override the id the
node itself reported for that same central tag. adoptedAliases is never
pruned — cacheDel clears remoteIDByTag and pushedFP only — so the entry
outlives the pairing that created it.

That inverts the intended precedence: once a push renames a node inbound to
the central tag, the node reports it directly, and a stale alias pointing at
some other inbound reusing the old name would win. Every state-changing op on
that inbound then targets the wrong one, overwriting or deleting an inbound
the operator created separately.

The alias now only fills a gap: a central tag the node already reports is
left alone.
2026-09-04 02:48:35 +02:00
Sanaei ab4229534e fix(node): cap the status body the heartbeat probe decodes
probe decoded the node status response with json.NewDecoder(resp.Body) and no
size limit. encoding/json buffers the whole value before decoding, so the
allocation was dictated by the peer regardless of how few fields the envelope
declares — and the heartbeat job probes up to 32 nodes concurrently on a 4s
budget with no client-level timeout.

The sibling RPC path already caps every node response at 64 MiB
(readCappedBody in internal/web/runtime), so this was the one uncapped read
of node-controlled data. A status envelope holds a handful of scalars, so the
cap here is 1 MiB rather than the RPC figure.

The peer is untrusted in the skip and pin TLS modes, and the same decode is
reachable from the nodes test and probe endpoints.
2026-09-04 02:35:11 +02:00
Sanaei 0775fcaad2 fix(node): keep an adopted inbound alias across a remote id cache refresh
AdoptInboundAlias maps a central tag onto a node inbound that carries a
different name, recording the pairing in both remoteIDByTag and
adoptedAliases. refreshRemoteIDs then rebuilt remoteIDByTag from the tags the
node reports and nothing else, so the central-tag entry was dropped on the
next cache miss for any other tag.

After that every op on the adopted inbound failed to resolve, and UpdateInbound
falls back to AddInbound — creating a duplicate inbound on the node at the same
port. cacheGetTag only recovers an n<id>- prefix flip, never an arbitrary
alias, so the pairing could not be rediscovered until a master restart.

The rebuild now re-applies adoptedAliases onto the fresh map, which keeps the
map the single place a tag is resolved from.
2026-09-04 02:35:02 +02:00
Sanaei 6f40a51d62 fix(node): sweep a selected inbound the node reports without its prefix
In "selected" sync mode the reconcile sweep built its set of managed tags
verbatim from node.InboundTags. A panel-created node inbound is stored with
an n<id>- prefix (composeInboundTag) and pushed to the node with that prefix
stripped (wireInbound), so the tag the node reports never matched the set and
the sweep skipped it.

The effect is the case the sweep exists for: an operator deletes a node
inbound while the node is offline, and the node keeps serving it — and its
clients — indefinitely. Only unprefixed tags were unaffected, which is why
the existing selected-mode test did not catch it.

nodeSelectedTagSet already builds both tag forms for exactly this reason and
is used by the snapshot filter; the sweep now uses it too, so the two agree.
2026-09-04 02:34:53 +02:00
Sanaei f6bfcfe759 refactor(ci): make the Claude workflow review pull requests and nothing else
claude-bot.yml ran three jobs: the pull-request review, an @claude mention
responder, and a conflict resolver that committed and pushed to contributor
branches. Only the review is wanted, so the other two are gone and the file
is renamed to say what is left.

Consequences worth knowing:

- secrets.CLAUDE_BOT_PAT is no longer referenced by any workflow. It was the
  only push credential handed to an agent in this repository and can now be
  deleted from the repository settings.
- @claude goes unanswered everywhere. claude-issue-analyst.yml deliberately
  excludes mentions (!contains(body, '@claude')) so the two jobs would not
  both reply; with the mention job gone, only `@claude review` on a pull
  request still reaches anything. Dropping that clause from the analyst would
  restore mention answering on issues.
- The workflow display name changes, so a branch protection rule keyed on
  "Claude Bot / review" has to become "Claude PR Review / review". The job
  name, which is what statusCheckRollup reports, is unchanged.

The review job itself is byte-identical. The workflow-level permission drops
to issues: read, which is all the remaining job needs - it already declares
its own.
2026-09-04 02:09:50 +02:00
Sanaei 41db85a096 docs(claude): teach the bot briefings about AmneziaWG and PIA
`grep -ci amneziawg` returned 0 in both .github/claude/repo-context.md and
REVIEW.md while CLAUDE.md has carried the protocol for releases. The issue
analyst and the review bot could not name internal/amneziawg/,
internal/amneziawgnet/ or internal/pia/, and the mention job's inline map
enumerated ten protocols with amneziawg missing from the list.

The 3.1 obfuscation parameters are generated twice - GenerateObfuscation31 in
internal/amneziawg/params.go and generateAwgObfuscation in
frontend/src/lib/xray/amneziawg-obfuscation.ts - so REVIEW.md now names that
pair as a divergence surface next to the three link implementations. Commit
bd1c27b0 was already a bug in exactly that pair.

Also corrects the CLAUDE.md CLI list, which omitted encrypt-tokens.
2026-09-04 02:09:28 +02:00
Sanaei 63b46cd612 perf(clients): apply a multi-inbound client create concurrently
Creating or attaching a client across N inbounds called AddInboundClient
once per inbound, strictly one after another. When those inbounds live on
different nodes each call is a full node round-trip bounded by the 10s
remote timeout, so the request cost the SUM of every node's latency: two
nodes felt instant, three took ~13s and timed out bot callers, which is
how it surfaced as "two out of four account creations fail".

Split the per-inbound preparation from the apply. Preparation stays
ordered and single-threaded because fillProtocolDefaults mints the shared
credentials on the first inbound and every later one reuses them; the
applies then run concurrently, capped at inboundFanoutConcurrency. A
4-node create measured 1.205s -> 0.307s with peak overlap 1 -> 4.

Consequences of no longer aborting at the first failing inbound:

- Every apply error is tagged with its inbound and the failures are
  joined, so all of them reach the caller instead of just the first.
- The fanout goroutines recover their own panics. Off the request
  goroutine gin's Recovery no longer covers them, and an unrecovered
  panic would kill the panel rather than fail one inbound.
- A partly-applied call commits clients on the inbounds that succeeded,
  so the controller and the LDAP job now read needRestart before the
  error check; otherwise Xray was never flagged for the work that landed.
- limitHwid is applied only when every inbound succeeded. Applying it
  after a failure rewrites limit_hwid and trims the registered devices of
  an email that already existed, which is silent data loss on an
  operation the panel reported as failed.

Update the API docs for the new partial-application contract and the
inbound-tagged error strings.
2026-09-04 01:01:20 +02:00
duqigit 2ddcf53020 Feature/fix external subscription client expiry (#6333)
* fix(sub): honor client expiry for external links

* fix(ui): show client expiry on external links

* fix(sub): address external expiry review
2026-09-03 22:32:05 +02:00
Sanaei 13e87a18c8 chore(ci): give the race job a 25m test timeout
The race job failed with "panic: test timed out after 10m0s" in
internal/web/service (FAIL at 600.106s) while every other package passed
and the non-race go-test job ran the same package in 57s.

Nothing hung. The race detector costs this repo ~8.5-10x (internal/database
8.4s -> 73s, internal/sub 17.8s -> 149s), and internal/web/service has 671
tests, ~40 of which each pay a full InitDB + AutoMigrate. That puts it right
on go test's 10-minute default per-package timeout: the last four race jobs
finished in 10m10s-10m28s before this one crossed the line.

Pass -timeout 25m in ci.yml and `make race` so the largest package has real
headroom while a genuine deadlock is still bounded. Verified locally:
ok internal/web/service 265.425s, 658 tests, no data races.
2026-09-03 21:57:38 +02:00
kuzzrus bd1c27b03d fix(amneziawg): H1-H4 generator + queue-depth throughput fixes (#6330)
* fix(amneziawg): stop H1-H4 generator misclassifying transport packets

Both the Go generator and its frontend mirror picked a random *range*
per H1-H4 field with only a minimum width enforced (no maximum).
amneziawg-go's packet classifier only ever compares a fixed-size
ciphertext prefix against these bounds, so a wide range buys no DPI
resistance -- the boundaries themselves are never observable on the
wire. It does cost real throughput: with randomTrailers on (the
default here), the handshake-size checks relax from == to >, so a
wide H-range misclassifies a proportional fraction of ordinary
transport packets as handshakes and silently drops them
(amnezia-vpn/amneziawg-go#183). A single value per field is strictly
safer than any range, with no obfuscation trade-off.

Live-tested: narrowing H1-H4 alone took AmneziaWG upload from
2-3 Mbit/s to 200+ Mbit/s on one box, and ~20 Mbit/s to 120-156 Mbit/s
on another, single-variable, no other change.

* fix(amneziawgnet): raise tunQueueDepth to absorb slow-start bursts

1024 was sized for a single-connection buffering problem (the
gVisor-to-amneziawg-go TUN handoff channel needing slack for the
download direction). tcpip.Stack.Stats() during a real many-connection
download (20-28 concurrent TCP flows, e.g. a segmented speed test)
showed SlowStartRetransmits jump by ~770 in a single second the moment
CurrentEstablished crossed ~20 -- consistent with many connections'
simultaneous slow-start growth briefly exceeding 1024 outstanding
packets and gVisor treating the resulting silent drops as real network
loss.

* fix(amneziawg): trim comment blocks to the repo's 2-line cap

Review feedback: four comment blocks in the previous commits exceeded
CLAUDE.md's 2-line-per-block hard rule (up to 13 lines). Trimmed each to
the one non-obvious fact plus the amneziawg-go#183 reference; the fuller
rationale already lives in the commit message. Also refreshed the stale
H1-H4 range example in docs/content/docs/en/config/amneziawg.mdx to match
the new single-value generator output.
2026-09-03 21:50:23 +02:00
ilyusha 0ff3c23948 fix(api-docs): generate request bodies for all encodings (#6296)
* fix(api-docs): generate request bodies for all encodings

The OpenAPI generator only recognized generic body parameters, so JSON, form, and multipart declarations disappeared into empty application/json objects. Generate the declared media type and schema, preserve optionality and conditional requirements, and encode repeated form arrays the way Gin expects. Correct the request metadata exposed by the complete schemas and keep the panel and docs specifications synchronized.

* fix(api-docs): align alternative request schemas

Keep non-empty constraints on the selected request-body alternative without rejecting empty values for the alternatives that panel requests also include. Allow null client IP lists because model serialization emits them while cleared rows await pruning.

* fix(api-docs): send object urlencoded fields as JSON, document the inbound update body

Four defects the request-body rework exposed or left behind:

- An object-typed field in an x-www-form-urlencoded body got no encoding
  entry, so OpenAPI 3.0 serialized it form-style. Swagger "Try it out"
  and generated clients sent memberWeights=3&memberWeights=0.2 to
  /panel/api/sub-balancers, and parseSubBalancerForm json.Unmarshals the
  raw field, so every such call failed with "invalid memberWeights".
  Emit encoding.<name>.contentType = application/json instead.
- bodyRequiredOneOf names were never checked against the declared body
  params: a typo emitted an anyOf branch requiring a property that does
  not exist — unsatisfiable — and make gen still passed. Throw now, and
  extend the requestSchema guard to reject bodyRequiredOneOf as well.
- /panel/api/inbounds/update/:id advertised no request body although its
  own summary says the shape mirrors /add and updateInbound binds one.
  Both entries now share an inboundBody const so they cannot drift.
- The mixed-locations error was the only buildOperation throw without
  the method and path, aborting make gen without naming the offender.

Regenerated frontend/public/openapi.json and copied it to
docs/public/openapi.json. No MDX regeneration: no summary changed.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-09-03 21:20:38 +02:00
ilyusha f294e1806d feat(release): publish SHA-256 sums and verify them in install.sh/update.sh (#6393)
* feat(release): publish SHA-256 sums and verify them in install.sh/update.sh

The installer and updater fetched the release archive and extracted it
after checking only that the file is not empty, and the release workflow
published no checksums. TLS protects the transport, not the bytes: a
truncated or swapped asset, a bad mirror or a TLS-terminating proxy was
installed as root. #5396 added this verification for the Xray archive;
the panel's own archive was the remaining unverified download.

Publish <asset>.sha256 next to every release archive (Linux and Windows)
and verify it before extracting. A mismatch aborts the install; a missing
sidecar, which every release before this change has, only warns, so
installing older tags keeps working.

Assisted-by: Claude Code:claude-fable-5-1

* fix(install): fail closed when the checksum sidecar cannot be fetched

Review follow-up. Any curl failure on the sidecar (5xx, reset, DNS) was
treated as "no checksum published", so whoever can swap the archive
could also drop the 90-byte sidecar request and skip the check. Only a
404, which every release before the sidecar existed returns, is still
tolerated with a warning; every other outcome aborts and removes the
downloaded archive.

Assisted-by: Claude Code:claude-fable-5-1

* fix(install): restore the closing brace lost in the main merge
2026-09-03 20:44:00 +02:00
ilyusha 4019f47de2 fix(x-ui.sh): put the fail2ban backend override in jail.d, not jail.conf (#6392)
* fix(x-ui.sh): put the fail2ban backend override in jail.d, not jail.conf

create_iplimit_jails switched the global fail2ban backend to systemd on
Debian 12+ and Ubuntu 22.04+ with sed on /etc/fail2ban/jail.conf. That
file is the package's conffile: the next fail2ban upgrade either drops
the edit or keeps a stale jail.conf, depending on the conffile prompt.

Write the same override to /etc/fail2ban/jail.d/3x-ipl-backend.conf,
which fail2ban reads after jail.conf and which upgrades leave alone, and
remove it together with the other 3x-ipl files on uninstall. The 3x-ipl
jail itself keeps its explicit backend=auto.

Assisted-by: Claude Code:claude-fable-5-1

* fix(x-ui.sh): only override the stock fail2ban backend, keep it on partial removal

Review follow-ups. The old sed only rewrote a literal 'backend = auto'
in jail.conf's [DEFAULT], so an operator's own backend survived it; the
override file was written unconditionally. Write it only when jail.conf
still carries the stock value. And keep the file when only the IP-limit
jail is removed: the sed was never reverted either, and deleting a
[DEFAULT] override there would flip every inheriting jail back to auto
on the restart in the same branch. The full /etc/fail2ban removal path
still deletes it.

Assisted-by: Claude Code:claude-fable-5-1
2026-09-03 20:42:14 +02:00
Sanaei 8411b1dd9e chore: upgrade Vitest to v5
Update frontend dev tooling to Vitest 5 by bumping `vitest`, `@vitest/browser-playwright`, and `@vitest/coverage-v8`, plus `@types/react-dom`. Add an override for `@storybook/addon-vitest` to pin Vitest-related packages to compatible versions and avoid dependency mismatch issues. Also bump the Go toolchain patch version from `1.27.0` to `1.27.1` in `go.mod`.
2026-09-03 20:37:10 +02:00
Sanaei a31fa9abfa fix(node): refuse a node's claim on another inbound's client
The sync adopts each node's reported clients through SyncInbound, which resolves
a client record by email alone — and clients.email is globally unique. A node
reporting a colliding email therefore overwrote that client's UUID even when the
client is attached only to a master inbound, and the master then rebuilt its own
Xray config with the node-supplied credential: the real user locked out.

Skip a reported client whose record is attached only to inbounds of other nodes.
A record attached nowhere stays adoptable, so the soft-orphan reattach path a
flapping node depends on is unaffected.
2026-09-03 18:06:35 +02:00
Sanaei f17e4684e0 fix(sub): apply the device limit to ?view=raw
subJsons and subClashs served the raw body and returned before enforceHwid ran,
so appending ?view=raw to a JSON or Clash subscription URL handed out a complete,
client-consumable config however many devices were already registered. The branch
exists to stop a browser's Accept: text/html from being answered with the info
page, not to skip the gate.

Gate the raw branch and leave the other gate where it was, below
maybeServeSubPage, so the HTML info page stays ungated as before.
2026-09-03 18:06:35 +02:00
Sanaei f9de0226fe fix(xray): confine log paths written under any key case
resolveXrayLogPaths looked the log object up by the exact keys "access" and
"error", but xray-core decodes that object with encoding/json, which falls back
to a case-insensitive field match. "Access": "/tmp/pwn.log" therefore reached
AccessLog untouched and Xray — root, in a standard install — created the file
there, reopening the arbitrary write that GHSA-jm48-m3rr-9hgg closed.

Fold every case variant onto the canonical key before confining it. When both a
canonical key and a variant are present the canonical value wins, so a
"none" cannot be overridden by a smuggled "Access" path.
2026-09-03 18:06:15 +02:00
Sanaei 25d0c06f89 fix(ci): skip a head the review bot already reviewed, and report a refused run
Ten review runs fired in under two hours on 3 September and every one after
11:25 came back rejected: the five-hour usage window was at 100 percent
(overageStatus rejected, org_level_disabled) while the seven-day window sat at
29. Two of them reviewed the same head SHA and one pull request was reviewed
four times, because a draft/ready toggle re-fires pull_request_target and the
skip decision is only reachable after a full checkout and a model boot.

Settle it in the workflow instead: a bot comment carrying "Reviewed head:" and
the pinned SHA means this head is done, so the pr-head checkout, the brief and
the action are all skipped. An explicit "@claude review" is exempt, so a
maintainer can still force one.

A refused run also failed the job twice over - the action's exit 1 plus "the
review posted nothing" - with nothing on the pull request to say why, which
reads as a broken bot rather than an exhausted budget. The job now classifies
its own transcript: a rejected rate_limit_event, or a 529 that survived every
retry, posts one line on the pull request and stays green. Anything else still
fails loudly.

Also tightens that check, which counted ANY bot comment quoting the head SHA as
a legitimate skip; the conflict-resolution job quotes SHAs too, so a dead run
could go green on one.
2026-09-03 17:26:00 +02:00
MRVX 47964afbc5 fix(clients): render all tunnel configs for multi-inbound client (#6346) (#6349)
When a client belongs to multiple AmneziaWG or WireGuard inbounds (e.g. across
remote nodes), findAmneziaWGInbounds and findWireguardInbounds only returned the
first matching inbound. Consequently, ClientInfoModal and ClientQrModal rendered
only one config block, making other inbounds' configs unreachable.

- Add findAmneziaWGInbounds and findWireguardInbounds returning all matching inbounds
- Add formatTunnelConfigMeta helper to unify label, fileName, and qrRemark resolution
- Support addressOverride in buildWireguardClientConfig from tunnelAllowedIPs
- Render all tunnel configs in ClientInfoModal and ClientQrModal with node remarks
- Distinguish download filenames with inbound remark suffix to avoid collisions
- Add component integration tests covering multi-inbound modal rendering
2026-09-03 17:03:48 +02:00
Mapioe de18c5a006 fix: do not type successfull login twice (#6374)
Co-authored-by: Mapioe <Mapioe@users.noreply.github.com>
2026-09-03 17:00:25 +02:00
ilyusha 195988bdc1 fix(install): fetch x-ui.sh and unit files from the installed release tag (#6391)
* fix(install): fetch x-ui.sh and unit files from the installed release tag

install.sh and update.sh pin the panel archive to a release tag but always
took x-ui.sh, x-ui.rc and the service units from main, so the management
script and the binary of one installation came from different commits:
the fail2ban templates and setting flags the script writes drift silently
against an older binary, two installs of the same tag differ, and a
reviewed or digest-pinned installer still runs unreviewed code from main.

Use the same ref as the archive, keeping main only for the rolling
dev-latest build. The menu's "update menu" and update_shell paths now
fetch the script matching the installed version and fall back to main
with a visible notice when no script is published for it.

Assisted-by: Claude Code:claude-fable-5-1

* fix(install): fall back to main for files a pinned tag does not publish

Review follow-ups. install.sh accepts tags down to v2.3.5, but x-ui.rc
only exists from v2.8.4 and the split x-ui.service.* files are newer
still, so pinning those to the tag made an Alpine install of an old tag
404 after the previous install was already removed. Probe the tag for
each file and fall back to main with a notice when it is missing, as
the menu already does for x-ui.sh.

The fail2ban auto-setup probe also trusted the exit status of
'x-ui setup-fail2ban', but scripts before v3.4.0 have no such
subcommand and exit 0 from the usage banner, so the installer reported
a setup that never ran. Skip with a notice when the installed script
does not know the subcommand.

Assisted-by: Claude Code:claude-fable-5-1

* fix(install): refuse a tag that does not publish a needed script

Falling back to main reintroduced the binary/script mismatch the tag
pinning exists to remove, and it fired at points where install.sh and
update.sh have already stopped and removed the previous installation --
so the quiet path was also the one that could not be undone.

Probe the tag instead, before anything is touched, for every file that is
always fetched from GitHub (x-ui.sh, plus x-ui.rc on Alpine), and abort
with the HTTP status when one is missing. The unit files stay unprobed:
they are only fetched when the release tarball omits them, so an old tag
that ships x-ui.service inside its tarball still installs. Their existing
failure message now names the ref it tried.

Also tighten the setup-fail2ban probe to the dispatcher's case arm rather
than any mention of the string, which also matches a comment.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 16:50:53 +02:00
ilyusha 23511108bf fix(database): keep the SQLite store owner-only (#6390)
* fix(database): keep the SQLite store owner-only

InitDB created the data directory 0755 and let SQLite create x-ui.db
and its -wal/-shm side files under the default umask, so on a stock
install they are world-readable. The store holds client UUIDs, Reality
private keys and the admin password hash, so any local account could
read them.

Create the directory 0700 and chmod the database files to 0600 right
after opening. SQLite gives -wal/-shm the mode of the main file, so
files created later inherit it; existing installs are tightened on the
next start. PostgreSQL deployments are untouched.

Assisted-by: Claude Code:claude-fable-5-1

* fix(database): tolerate chmod failures, keep the dump and install dir owner-only

Review follow-ups. A store the panel cannot chmod (root_squash NFS, a
foreign uid in a container) refused to start, which is worse than the
0644 it had before; log and continue instead, as the backup-directory
cleanup above already does. install.sh reset /etc/x-ui to 0755 right
after the binary created it 0700, so the directory hunk was inert on
real installs; create it 0700 there too. The migrate-db dump in the same
directory is a plaintext copy of the same secrets and was written 0644.

Assisted-by: Claude Code:claude-fable-5-1
2026-09-03 16:37:35 +02:00
Rouzbeh† 540caa4e93 fix(hysteria): standard geco share links and persistent uTLS None (#6325)
- Export standard gecko obfs query params in hysteria2 share links
- Enforce packet size bounds across Go and TypeScript link handlers
- Persist uTLS None explicitly and initialize new TLS inbounds to chrome
- Tear down stackTun safely without closeMu deadlock against WriteNotify

Co-authored-by: rqzbeh <rqzbeh@users.noreply.github.com>
2026-09-03 16:35:07 +02:00
ilyusha f9898e0b24 fix(sub): randomize fresh panel subscription paths (#6375)
* fix(sub): randomize fresh panel subscription paths

Seed distinct cryptographically random paths for base64, JSON, and Clash subscriptions when a panel database is first created. Persist them so restarts keep published URLs stable while upgrades preserve existing settings.

Generated-by: OpenCode:gpt-5.6-sol

* fix(sub): regenerate paths on settings reset

Keep subscription paths unpredictable after a factory reset, close the test database on failure, and update the builder, OpenAPI, and localized docs to describe panel-specific paths instead of obsolete fixed defaults.

Generated-by: OpenCode:gpt-5.6-sol
2026-09-03 16:34:37 +02:00
dawn ded2aa150c fix(frontend): isolate subscription language preference (#6394)
* fix(frontend): isolate subscription language preference

* fix(frontend): defer date locale resolution
2026-09-03 16:33:37 +02:00
dawn 0c72dd8384 fix(sub): restore compatible SOCKS subscription inbound (#6395) 2026-09-03 16:33:14 +02:00
dawn 04e8458054 fix(frontend): improve dense QR readability (#6396)
Dense AmneziaWG configs crossed a QR version boundary at the fixed display size, and the generated symbol had no quiet zone. Use low error correction and a four-module margin to reduce module density while keeping the payload unchanged.
2026-09-03 16:32:27 +02:00
dawn e95fe80fc4 fix(amneziawg): avoid manager lock inversion (#6397)
* fix(amneziawg): avoid manager lock inversion

Packet handlers re-entered the manager mutex while device reconfiguration and teardown held it and waited for receiver goroutines. Publish immutable peer indexes atomically so the data path can finish without participating in lifecycle locking.

* test(amneziawg): exercise UDP relay hit path
2026-09-03 16:31:53 +02:00
Sanaei 65b9bfed8b fix(ci): stop the review bot handing over fixes in prose
The `suggestion` blocks stopped once the briefing moved into its own file, but
the carve-out that survived — "one clause naming where the fix belongs" — was
being stretched from a location into an instruction. #6397 dictated what to
write in a comment and which existing test to copy; #6394 named the fix
outright. The clause now permits a file, a function, a symbol or a layer and
nothing about what happens there, and closes the stretch three ways: prose is
a patch the moment a verb describes the change, so is holding up an existing
symbol as the model to copy, and a clause the maintainer could apply as
written is the fix however it is punctuated.

Three rules the rubric was missing, none of which existed anywhere. A 🔴 or 🟡
says in one clause what the change did to the code it is about, the way a 🟣
already says it predates it — otherwise nothing in the comment shows the
marker was earned. A claim about a caller or a callee needs that file read:
the dispatch-rule violation this repo cares most about sits a frame outside
the diff, and the skill is told to avoid reading past the changes. And nothing
pads the comment.

The briefing's one named override aimed at a step that does not exist. The
plugin the job loads defines no `--comment` flag and mentions suggestions
nowhere, so `max --comment <target>` is inert trailing text. Replaced with the
six overrides that are real: the skill calls pre-existing issues and unmodified
lines false positives, drops every finding its confidence pass scores under 80
and then posts nothing at all (a nitpick scores 50, so that filter empties all
five nit slots), says to avoid emojis against a severity system that is three
of them, mandates a "Found N issues" format, and forbids reading build signal.
2026-09-03 13:42:48 +02:00
Sanaei 38dd9bcc70 Bump Go dependency versions
Refresh the Go module set in go.mod and go.sum to newer patch/minor releases, including xray-related dependencies, gRPC, WireGuard, and supporting indirect libraries. This keeps the project aligned with upstream fixes and compatibility updates without changing application code.
2026-09-02 21:59:39 +02:00
Sanaei e264ea89c1 chore(deps): bump docs and frontend deps
Update dependency versions across `docs` and `frontend`, including Next/Fumadocs packages in docs and Ant Design, React Query, Storybook, and related tooling in frontend. Also updates lint/format tool versions (`oxlint`, `oxfmt`), bumps docs `pnpm` package manager version, and refreshes workspace release-age exclusions for the newly upgraded docs packages.
2026-09-02 21:37:55 +02:00
Sanaei ac193cd9d3 refactor(ci): split the issue analyst out and brief the review job from a file
The issue analyst moves verbatim from claude-bot.yml into its own
claude-issue-analyst.yml, so claude-bot.yml now holds only the pull-request
side: review, @claude mentions and conflict resolution.

The review job's briefing was a single 2,600-character quoted string inside
claude_args, unreadable and unreviewable. It now lives in
.github/claude/review-job.md, assembled at run time with a "This run"
section that hands the reviewer the pinned head SHA, the pull request and
the exact check-runs command, and reaches the CLI through
--append-system-prompt-file. The agent-mode action sets no system-prompt
append of its own, so the file flag cannot collide with one.

Findings no longer carry the fix: REVIEW.md and the brief both forbid
suggestion blocks, patches and replacement snippets, overriding the
code-review skill's --comment step, which attaches a committable suggestion
to any small fix. A finding states what is wrong, where, what triggers it
and what breaks; the maintainer decides the change.
2026-09-02 21:06:58 +02:00
Sangeeth Thilakarathna c62ee0bbd8 fix(outbound): test VLESS vnext endpoints (#6358)
Co-authored-by: sanmaxdev <sanmaxdev@users.noreply.github.com>
2026-09-02 20:46:49 +02:00
dawn 8abe87b625 fix(outbounds): preserve stable subscription tags (#6345)
An inserted link could claim a previous positional tag before the existing identity that owned it was processed. The owner was then suffixed and the swapped mapping persisted across refreshes.

Reserve tags for identities still present in the batch so positional fallback, fresh allocation, and collision suffixes cannot take them.
2026-09-02 20:46:20 +02:00
Matt Van Horn f64453041a fix: preserve per-inbound WireGuard peer addresses (#6344)
Clients are stored once per email in the client table, so when the same email
exists on more than one WireGuard inbound the shared record's AllowedIPs and
PreSharedKey win for every inbound. A client present on both a WG and an AWG
tunnel was emitted with one tunnel's address on both, so the second tunnel's
peer got the wrong allowedIPs.

Read the per-inbound client settings for WireGuard inbounds and, when the
inbound carries its own entry for that email, use its AllowedIPs and
PreSharedKey when building the peer.
2026-09-02 20:45:11 +02:00
dawn b81216135d fix(clients): sync auto-renewal across inbounds (#6339)
* fix(clients): sync auto-renewal across inbounds

Propagate the renewed shared traffic state to every inbound that carries the same client email. Restore each affected runtime user while keeping renewal counters and quota resets single-counted.

* fix(clients): preserve manual disable during renewal
2026-09-02 20:39:03 +02:00
Matt Van Horn 71607e3861 fix: Prevent node snapshots from resurrecting bulk-deleted clients (#6382)
Fixes #6356

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-09-02 20:25:40 +02:00
Sentiago 1bf078c51e feat(routing): add panel-only comment field to routing rules (#6361)
Can annotate rules with a human-readable note for easier management.
The comment is stripped before sending the config to xray-core (same
pattern as the existing 'enabled' flag).

Backend: stripDisabledRules now removes 'comment' from generated config.
Frontend: input field in RuleFormModal, column in desktop table, chip
with tooltip in mobile card list. Schema and type definitions updated.
2026-09-02 20:22:50 +02:00
DIMFLIX 7100fbcd08 feat(sub): leastLoad member weights for subscription balancers (#6304)
* feat(model): add MemberWeights to SubBalancer

Per-inbound leastLoad weights, stored with the same gorm json serializer
as InboundIds so AutoMigrate adds the text column on every dialect
(postgresModelSettled sees the missing column and re-runs). Absent
entries mean weight 1.0; only meaningful for strategy leastLoad.

* feat(sub): accept memberWeights on the sub-balancer API

Parsed as one JSON form field (gin cannot bind bracket-keyed maps from
urlencoded bodies). validate() rejects weights under any strategy but
leastLoad — xray would silently ignore costs there, so storing them
would pretend a knob exists. Non-positive weights error instead of
defaulting: a zero usually means a typo'd "never pick this node".
Entries for inbounds no longer selected are dropped on save.

* feat(sub): emit leastLoad strategy costs from member weights

costs[] is built after the tagging loop reuses the exact retagged tags
(bal-N-protocol[-k]) and each member's owning inbound id. Members
without a configured weight default to 1.0, but costs are omitted
entirely unless at least one explicit weight survives — an all-1.0
array would bloat every subscription response for no effect.

* feat(sub-balancers): leastLoad member weight inputs

Weight fields render only under leastLoad and hide on strategy change
without dropping their values, so an accidental toggle away and back
loses nothing until save; non-leastLoad submits strip them entirely
because xray would ignore costs. Weights travel as one JSON form field
(gin cannot bind bracket-keyed maps) and every locale gets the three
new keys in the same commit per the dead-keys rule.

* docs(api): document memberWeights on sub-balancers

leastLoad-only JSON form field; update notes that omitting it clears
stored weights. Regenerated openapi artifacts via make gen + the docs
copy/gen:api step nothing checks automatically.

* fix(api-docs): use the allowed object ParamType for memberWeights

* fix(sub-balancers): cap the member-weight list height

Many selected inbounds pushed the modal body past the viewport. The
weight rows now scroll inside a 220px viewport, mirroring the inbound
picker's listHeight so both lists read the same.

* fix(sub): anchor leastLoad cost matches to exact member tags

Verified against xray-core: without regexp, WeightManager matches costs
by substring (strings.Index), so the bare tag "bal-1-vless" also hits
the deduplicated "bal-1-vless-2" and both members get the first
entry's weight. Anchored ^tag$ regexps make every cost entry match only
its own member. Also confirmed value<=0 makes xray derive a weight from
the first digit of the matched tag — validating weights > 0 server-side
was the right call.

* fix(sub-balancers): keep member weights across the enabled toggle

The table's toggleEnabled re-posted a full-row payload without
memberWeights, and the update path treats an absent key as "erase" —
flipping the switch silently dropped every configured weight. Round-trip
the stored weights through the toggle payload, and prove persistence
with a re-Get in the weight-validation test (the returned struct alone
would stay green even if Save skipped the column).

* fix(sub-balancers): address review on member weights

- omitempty on MemberWeights: the panel sends null for every pre-existing
  and non-leastLoad balancer, which failed the hand-written zod response
  schema on every fetch (zod .optional() accepts undefined only; switched
  to .nullish() per repo convention) and drifted the generated contract.
  Regenerated openapi artifacts + docs copy + MDX.
- Bound weights to the positive float32 range: xray decodes costs as
  float32, so an over-range value makes clients reject the whole
  subscription document and an underflow decays to the tag-digit
  fallback weight. Tests for both directions.
- Trim six comment blocks to the 2-line cap from CLAUDE.md.

---------

Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
2026-09-02 20:21:27 +02:00
Masterain f9cfd87cb2 feat(nord): support multi-server NordLynx outbounds (#6311)
* feat(nord): support multi-server NordLynx outbounds

* fix(nord): address verified PR review findings

Tighten the NordVPN multi-outbound implementation and its regression
coverage based on the verified review feedback.

- remove the redundant Xray validation test that duplicated the base
  branch and did not exercise multiple outbounds
- make NordModal tests wait for server loading and assert the modal close
  callback, duplicate-server state, and endpoint behavior
- add coverage for resolving the NordLynx public key from technology
  metadata instead of a numeric technology ID
- use a real httptest server for Nord integration tests through an
  injectable API base URL
- represent the All Cities sentinel consistently as null and reset it
  when a country changes

The existing NordVPN API contracts and persisted outbound schema remain
unchanged.
2026-09-02 20:20:10 +02:00
Sanaei f727d04f65 v3.7.0 v3.7.0 2026-08-24 15:07:15 +02:00
Sanaei fcf60eb2e2 chore: bump dependencies and clear deprecated frontend APIs
Routine dependency refresh: telego 1.11.2, go-sqlite3 1.14.50, grpc 1.83.1,
miekg/dns 1.1.73, sing 0.8.14 and the usual indirect churn on the Go side;
react-query 5.102.2, i18next 26.4.0, react-hook-form 7.86.0, Storybook
10.5.10 and vite 8.2.2 on the frontend, which also lifts the private frontend
package to 1.0.0.

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

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

Closes #6286
2026-08-24 13:27:40 +02:00