Commit Graph
210 Commits
  • feat(balancer): add balancer-to-balancer fallback support (#5586)
    * feat(balancer): add balancer-to-balancer fallback support
    
    Xray does not natively support using a balancer as fallbackTag for
    another balancer. This feature automates the loopback workaround:
    when a user selects a balancer as fallback, the panel generates a
    loopback outbound + routing rule in the template.
    
    How it works:
    - User picks fallback balancer from dropdown
    - Panel creates loopback outbound _bl_{target} + routing rule
    - Balancer fallbackTag set to _bl_{target}
    - Traffic: Balancer A → loopback _bl_B → routing rule → Balancer B
    
    Key features:
    - Dedup: multiple balancers sharing same fallback reuse one loopback
    - DFS cycle detection at edit time and on save
    - Self-reference guard (cannot select own balancer)
    - Delete protection (blocks if used as fallback by others)
    - Cleans up routing rules referencing deleted balancers
    - Override resolves balancer tags through loopback mechanism
    - All live status tags resolved for display
    - Internal _bl_ objects filtered from Outbounds/Routing UI
    - Backward-compatible with old _bl_ naming format
    - Translations for all 13 locales
    
    * fix(review): override regression, save payload sync, i18n completeness
    
    - OverrideBalancer: only resolve to loopback when resolution succeeds,
      pass original target through for plain outbound tags
    - onSaveAll: serialize cleaned template before save to ensure the
      healed/cleaned config is what gets persisted
    - Add reservedPrefix translation key to all 12 non-English locales
    - Restore trailing newlines in all 13 translation JSON files
    
    * fix(test): update balancer form modal tests after cycle-detection guard
    
    The okButtonProps disabled guard (added in 56d5825c) prevents the modal
    from firing onOk when the form is invalid. The old tests clicked the
    button expecting validation errors to appear, but antd Modal never calls
    onOk on a disabled button — causing false failures.
    
    Rewrite to test the actual guard behavior:
    - Button starts disabled (empty form)
    - Stays disabled with tag only (selector still empty)
    - Stays disabled for duplicate tag
    - Disabled button does not trigger onConfirm
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(xray): default outbound in basic routing (#5815)
    * feat(xray): default outbound picker in basic routing
    
    Let panel users choose which outbound handles unmatched traffic by
    moving it to the first position in the template outbounds list.
    
    * fix(xray): keep direct/blocked outbounds when changing default
    
    * style(routing): revert incidental whitespace churn
    
    Drop double blank lines and the reformatted function signature so the default-outbound diff stays focused on behavior.
  • fix(inbound): scope port-conflict check to the stored node on update (#5833)
    * fix(inbound): scope port-conflict check to the stored node on update
    
    UpdateInbound called checkPortConflict before restoring the inbound's NodeID
    from the database, so the check used the NodeID from the request body. That
    value is unreliable for edits: clients omit it (nodeId is `json:",omitempty"`)
    and the code already treats the stored NodeID as authoritative — an inbound
    can't be moved between nodes via edit. With a nil request NodeID a node inbound
    was mis-checked as a local/main-panel inbound and falsely collided with an
    unrelated inbound that happened to reuse the same port on the central panel (or
    another node). Symptom: editing a node inbound's listen address was rejected
    with "port <p> (tcp) already used by inbound ... " and silently discarded.
    
    Load the old inbound and restore inbound.NodeID *before* checkPortConflict, so
    the check runs against the node the inbound actually lives on. checkPortConflict
    already scopes candidates by node (sameNode); it was simply being fed the wrong
    NodeID.
    
    Add a regression test that seeds a main-panel and a node inbound on the same
    port and asserts the node inbound stays editable (fails before this change with
    the exact "already used" rejection).
    
    * style(inbound): trim inline comments from port-conflict scoping
    
    Repo convention forbids // line comments in committed Go; keep the scoping fix self-documenting.
  • fix(wireguard): build peers in GenXrayInboundConfig so node reconcile keeps clients (#5684)
    Adding a WireGuard client on the master broke every WireGuard connection on
    the sub-node until Xray was manually restarted on the node. Adding the same
    client directly on the node worked.
    
    Root cause: the panel stores WireGuard clients under the settings key
    `clients` (the shape every other protocol uses), but xray-core's wireguard
    inbound is configured with `peers`. The `clients`->`peers` conversion lived
    only in the full-config generation path (XrayService.GetXrayConfig), which
    runs on a full Xray restart. The live gRPC AddInbound path goes through
    (*Inbound).GenXrayInboundConfig, which passed the WireGuard settings verbatim
    - with `clients` and no `peers`.
    
    Why the master path broke it and the node path did not:
    - Adding on the node is a single safe operation: AddInboundClient -> AddUser
      -> AlterInbound{AddUser} -> wireguard.Server.AddUser, which appends one peer
      via IPC without touching the others. The inbound is local (NodeID == nil),
      so nothing is marked dirty and no reconcile runs.
    - Adding on the master does two things: it pushes the client to the node
      (the same safe hot-add, which succeeds), and it marks the node dirty. The
      reconcile then pushes panel/api/inbounds/update/:id to the node, whose
      InboundService.UpdateInbound applies it live via DelInbound + AddInbound
      (buildRuntimeInboundForAPI -> Local.AddInbound -> GenXrayInboundConfig).
      That re-adds the wireguard inbound with zero peers, wiping the device and
      dropping every connected client. A manual restart regenerated the full
      config, converted clients to peers, and restored them - hence "only a
      restart fixes it".
    
    Fix: convert WireGuard `clients` to `peers` in GenXrayInboundConfig itself,
    the single chokepoint for every live AddInbound (create, edit, node
    reconcile). WireguardClientsToPeers always rebuilds `peers` from `clients`
    (matching GetXrayConfig field for field) and drops the `clients` key. It does
    not gate on `peers` being absent: the panel seeds every WireGuard inbound with
    an empty `peers: []` placeholder (frontend inbound-defaults), so a
    "skip if peers present" guard would match that placeholder and make the
    conversion never run, leaving the live path emitting zero peers. The
    conversion stays idempotent by removing `clients`, so a second call - or an
    inbound with no `clients` - is a no-op, leaving the full-config path
    unaffected. This also fixes plain WireGuard inbound edits on a standalone
    panel, which went through the same peerless rebuild.
  • feat(hosts): bulk-add multiple hosts to multiple inbounds (#5677)
    * feat(hosts): bulk-add multiple hosts to multiple inbounds
    
    Allow users to select multiple inbound IDs and enter multiple host
    addresses (with optional per-host port override) in a single form
    submission.
    
    - Add BulkAddHostReq entity and POST /panel/api/hosts/bulk/add endpoint
    - Add AddHostsBulk service with GORM transaction safety
    - Add parseHostAndPort helper (IPv4, bracketed/bracketless IPv6, port)
    - Update HostFormModal to multi-select inbounds and tag-input hosts
    - Wire bulkCreate mutation in HostsPage with existing-host suggestions
    - Register endpoint in api-docs/endpoints.ts and regenerate OpenAPI/Zod
    
    * feat(hosts): group override records by group_id and support group editing
    
    * fix: import Popover in HostList
    
    * fix: use messageApi in HostFormModal
    
    * fix(hosts): resolve 4 bugs found in host-group code review
    
    - fix(schema): allow empty hosts array in BulkAddHostSchema so users can
      save a host without an address (inherits inbound endpoint). The old
      .min(1) was never enforced at runtime since the schema is only used for
      type inference, but the type was incorrect.
    
    - fix(service): validate new inbound IDs in UpdateHostGroup before deleting
      old rows, matching the same check already present in AddHostGroup. Prevents
      orphaned host rows when an invalid inbound ID is supplied on edit.
    
    - fix(service): replace full-table scan in GetHostsByInbound with two
      targeted queries (DISTINCT group_id WHERE inbound_id=?, then
      WHERE group_id IN ?) to avoid loading every host in the DB.
    
    - fix(mutations): remove unused createMut / create export from
      useHostMutations. The /hosts/add endpoint is identical to /hosts/bulk/add;
      only bulkCreate is used by the UI.
    
    * fix(hosts): address code review feedback (optimize bulk inserts, add validation tests, and remove comments)
    
    * fix(fmt): apply gofumpt formatting to model.go and db.go
    
    The previous merge commit incorrectly applied gofmt (tab-aligned) to
    these files. The repository's golangci config requires gofumpt+goimports
    which produces space-aligned struct fields. This commit restores the
    correct gofumpt formatting that matches upstream/main.
    
    * chore(frontend): regenerate API schemas and update lockfile
    
    * fix
    
    * refactor(hosts): dedupe host-group service and tidy frontend
    
    AddHostGroup and UpdateHostGroup shared an identical ~35-field
    model.Host construction and hand-rolled transaction boilerplate
    (tx.Begin plus a committed flag plus a deferred recover/rollback).
    Extract buildHostRows, validateInboundsExist and formatHostAddr, and
    run every mutation through db.Transaction. groupHosts collapses its
    duplicated address/port formatting and create/append fork into one
    path using slices.Contains. Behavior-preserving: host.go drops ~90
    lines with the existing service/controller tests green.
    
    Frontend: drop the Partial union and two as-casts in HostsPage.onSave
    (the modal always passes a full BulkAddHostValues), and remove the
    movable index map in HostList in favor of the table render index arg.
    
    ---------
    
    Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(inbounds): apply runtime changes after the DB commit (#5768)
    * fix(inbounds): apply runtime changes after commit
    
    * ci: fix staticcheck findings
  • refactor: modernize Go with strings.SplitSeq and maps.Copy
    Replace strings.Split loops with strings.SplitSeq iterators in the CSV
    parsers (reality_scan and the scale-test helpers) and swap a manual map
    copy for maps.Copy in the MTProto traffic collector. No behavior change;
    these are the fixes the modernize analyzer reports.
  • fix(clients): surface bulk-reset auto-enable failures (#5763)
    * fix(clients): surface bulk-reset auto-enable failures
    
    BulkResetTraffic re-enables a disabled client before resetting its
    traffic, but discarded the s.Update result with `_, _ =`, so a failed
    re-enable was silent: the client stayed disabled with nothing logged,
    unlike the single-client ResetTraffic path which already warns on the
    same call. Check the error and log a warning to match, and add a
    regression test covering BulkResetTraffic's previously-untested
    re-enable path.
    
    * ci: update Go toolchain for govulncheck
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(clients): parse only settings.clients across protocols (#5855)
    * fix(clients): parse only settings.clients across protocols
    
    Several inbound settings readers decoded the whole settings object into map[string][]model.Client. Real protocol settings include scalar keys such as VLESS decryption and Hysteria version, so that shape can fail before callers reach settings.clients or leave them relying on decoder side effects.
    
    Add one shared helper that extracts only the clients field through json.RawMessage, then use it from GetClients, SearchClientTraffic and the IP-limit job fallback paths. Regression tests cover VLESS and Hysteria settings with scalar protocol fields.
    
    * fix(clients): reject empty inbound settings
  • fix(inbound): reject finalmask + REALITY combo (crashes Xray-core) (#5861)
    * fix(inbound): reject finalmask configured together with REALITY security
    
    finalmask wraps the connection before REALITY's own handshake takes
    over (TcpmaskManager.WrapListener -> WrapConnServer runs at Accept()
    time, ahead of reality.Server()). reality.Server() does an unchecked
    type assertion assuming a raw *net.TCPConn; with finalmask in front,
    that assertion panics and takes down the entire xray-core process on
    the very first connection to the inbound - not just that connection.
    
    Upstream (XTLS/Xray-core#6453) confirmed this will be documented as
    unsupported rather than made graceful, so the panel needs to stop this
    combination from being saved rather than relying on docs.
    
    AddInbound/UpdateInbound now reject streamSettings with
    security=reality and a non-empty finalmask.tcp/udp with a clear error
    instead of letting it reach Xray.
    
    Related: MHSanaei/3x-ui#5857
    
    * fix(inbound): heal legacy rows and narrow the finalmask+REALITY guard
    
    Per review feedback on #5861:
    
    - Narrow the check to finalmask.tcp only. xray-core's TcpmaskManager
      (the thing that wraps the TCP listener ahead of REALITY's handshake,
      the actual cause of the panic) is only constructed when tcp masks
      are present; a finalmask.udp-only config never touches that accept
      path and doesn't reproduce the crash, so it shouldn't be rejected.
      Extracted the shared check into finalMaskRealityTcpMasks() so both
      the save-time guard and the config-build heal below use one
      definition of "dangerous".
    
    - Heal already-saved bad rows in GetXrayConfig(), the same way
      liftXhttpSessionIDKeys and HealShadowsocksClientMethods heal other
      legacy data at config-build time. AddInbound/UpdateInbound only cover
      the two save paths - a row that already carries this combination
      (saved before this guard existed, synced from a node, restored from
      a backup, or edited directly in the DB) would still crash Xray-core
      on the next restart without this.
    
    - Add end-to-end tests exercising AddInbound, UpdateInbound, and
      GetXrayConfig directly (seeding rows through the real DB) rather
      than only unit-testing the extracted helper in isolation, so a
      wiring regression in any of the three call sites gets caught.
  • fix(routing): allow dns.servers on private IPs past the geoip:private block rule (#5774)
    * fix(routing): allow dns.servers on private IPs past the geoip:private block rule
    
    Xray's own DNS client traffic is dispatched through the same routing
    table as proxied client traffic. When dns.servers points at a private
    IP (e.g. a self-hosted AdGuard Home / Pi-hole reachable on the same
    Docker network as Xray) and the panel's default geoip:private block
    rule is active, Xray's own DNS lookups get silently dropped. Xray then
    falls back to dialing destinations by raw hostname once its internal
    DNS attempt times out (~4s), so proxied connections still work, just
    with a multi-second stall added to every new domain-based connection,
    with no error surfaced anywhere.
    
    EnsureDnsServerRouting keeps a managed "direct" allow-rule for any
    private literal IP found in dns.servers, inserted immediately before
    the geoip:private block rule (matched by shape, not position). It only
    acts when both ingredients are present, keeps the managed rule in sync
    as dns.servers changes across saves, and never touches manually
    authored rules.
    
    Fixes #5773
    
    * fix(routing): scope the DNS allow-rule to its port, guard against reorder/UI drift
    
    Addresses three review findings on the initial fix:
    
    1. The allow-rule now carries a "port" matcher (grouped by the
       dns.servers entries that share it), instead of opening every port
       on the private DNS IP to proxy-client traffic. A private resolver
       that also exposes an unauthenticated admin UI on the same address
       would otherwise become reachable through the proxy too.
    
    2. EnsureDnsServerRouting now strips every previously-managed rule and
       rebuilds the current set fresh, reinserted immediately before the
       (re-indexed) geoip:private block rule on every save. Comparing IP
       content alone missed the case where an admin drags the rule below
       the block rule in the Routing tab (or reorders something else and
       incidentally moves it) — silently reintroducing the exact stall
       this fix addresses, with nothing to notice or correct it.
    
    3. dnsAllowRuleShape now tolerates an "enabled" key as long as it's
       true, matching the existing EnsureStatsRouting precedent
       (xray_setting.go's `delete(apiRule, "enabled")`). The Routing tab's
       rule editor writes that key on every save regardless of whether
       anything changed, and its enabled switch writes it on a plain
       toggle — without this, either action permanently disowns the rule
       from management and a duplicate gets inserted next save. A rule
       explicitly disabled (enabled=false) is left alone and a fresh one
       is (re-)created, respecting the admin's choice instead of silently
       re-enabling it.
    
    No-op detection now compares rebuilt rules against the original
    routing.rules JSON (both decoded through encoding/json to a common
    type) rather than reflect.DeepEqual on the parsed Go values, which
    falsely reported changes for identical content stored as []any vs
    []string.
    
    5 new tests cover multi-port grouping, position drift, and both
    enabled-key cases; existing tests updated for the port field.
    
    * fix: avoid size-computation overflow in allocation hint
    
    CodeQL flagged make([]map[string]any, 0, len(clean)+len(managed)) as a
    potential integer-overflow risk in the capacity computation. Drop the
    addition and hint with len(clean) alone — it already covers most of
    the eventual size, and append still grows correctly for the rest.
    
    ---------
    
    Co-authored-by: Volov <volovdata@google.com>
  • fix(ldap): convert default total GB to bytes when auto-creating clients (#5854)
    * fix(ldap): convert default total GB to bytes when auto-creating clients
    
    LdapSyncJob.buildClient stored ldapDefaultTotalGB directly into
    Client.TotalGB without the GB-to-bytes conversion every other client
    creation path applies (client form's gbToBytes, tgbot's
    limitTraffic*1024^3, client_inbound_apply.go's totalGB*1024^3). A
    "Default total (GB)" of 10 was persisted as 10 bytes, depleting the
    client almost immediately.
    
    Closes #5852
    
    * test(ldap): pin the GB-to-bytes conversion in buildClient
    
    Per review feedback on #5854: the existing test only exercised
    defGB=0, so it wouldn't have caught the missing conversion.
  • feat(mtproto): enforce per-client quota & expiry via mtg-multi limits
    Map each mtproto client's totalGB and expiryTime onto mtg-multi's new
    [secret-limits] (quota/expires): emit them into the generated config and
    hot-apply through PUT /secrets so live connections survive. Quota is
    written as an exact "<n>B" byte count that round-trips through both the
    config and API parsers without the precision loss of a base-2 unit.
    
    The sidecar's quota counter is not pruned when a secret is dropped, so a
    panel-side traffic reset re-pushes the client's secret and then calls
    POST /secrets/{name}/reset-quota (wired into every reset path) so a
    renewed client is not immediately re-blocked.
    
    Resolve the mtg-multi binary from the fork's latest release tag in
    DockerInit.sh and release.yml instead of a hardcoded version pin, so the
    panel no longer needs a manual bump per fork release.
  • refactor(frontend): replace axios with the native Fetch API
    Drop the axios (and qs) dependencies in favor of a native fetch wrapper.
    axios only ever handled same-origin JSON/form calls, a CSRF header, a 401
    redirect, and a 403-retry, all of which the platform now provides directly.
    
    - New src/api/http-init.ts (replaces axios-init.ts) reimplements the
      request/response interceptors on fetch: base-path prefixing,
      X-Requested-With, same-origin credentials, the CSRF token on unsafe
      methods, a single 403 retry with token refresh, and the 401
      redirect-and-latch. A small encodeForm() reproduces qs's
      arrayFormat:'repeat' encoding, so the request wire format is unchanged.
    - HttpUtil (src/utils/index.ts) keeps its public signatures and the Msg
      envelope, so the ~49 API call sites are untouched. HttpOptions is now
      hand-rolled instead of extending AxiosRequestConfig.
    - PanelUpdateModal drops its lone direct axios.get in favor of HttpUtil.get
      with { silent, timeout }.
    - Add tests for the fetch core (CSRF header, form/JSON/FormData bodies,
      base-path prefix, 403 retry, 401 redirect, tolerant body parse) and for
      HttpUtil's envelope unwrap / toast / error mapping; this logic was
      previously untested.
    - Remove the vendor-axios manualChunks branch and the qs type shim, and
      reword stale "axios" mentions in docs and route comments.
  • fix(logs): limit Xray log growth (#5840)
    * Limit Xray log growth
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: Mahyar Dana <dana.mahyar76@gmail.com>
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • fix(node): start a fresh quota window when a node auto-renews a client
    When a node-hosted client auto-renews, the node extends the deadline
    and zeroes its own counters, but the master treated the counter drop
    like any reset dip (#5456): the delta clamped to zero, the renewed
    expiry was adopted, and the old period's up/down stayed on the master
    row. A "100 GB every 30 days" package never got a fresh quota on the
    master for node inbounds.
    
    Detect the renewal in setRemoteTrafficLocked - reset days configured,
    an absolute deadline that moved forward, and the node counter falling
    below the stored baseline - and on that path adopt the node's
    post-renewal counters and enable state absolutely instead of adding
    the clamped delta, plus clear the email's stale cross-panel
    global-traffic rows, mirroring what the local autoRenewClients path
    already does. A plain counter dip without a deadline move keeps the
    existing clamp behavior, and a deadline extension with rising counters
    keeps accumulating.
    
    Closes #5843
  • fix(ldap): attach auto-created clients to every configured inbound tag
    The sync job built an independent client per configured tag and called
    CreateOne once per tag. Each call generated a fresh random subId, and
    the email-uniqueness check in ClientService.Create only re-admits a
    taken email when the incoming subId matches the stored one - so the
    first tag succeeded and every other tag failed with "email already in
    use", leaving new LDAP users on a single inbound.
    
    Build the client once per email and hand ClientService.Create the full
    list of resolved inbound ids, the same path the panel's own client
    create endpoint uses: one identity (email, subId) attached to all
    configured tags, with per-protocol credentials filled per inbound.
    Unknown tags are now skipped with a warning instead of building
    clients against a nil inbound.
    
    Closes #5846
  • fix(client): clean node_client_traffics rows when deleting a client
    Delete and DeleteByEmail removed client_traffics, global-traffic, and
    inbound_client_ips rows but never the per-node baseline rows in
    node_client_traffics, so every deleted client left orphaned baselines
    behind for each registered node. The shared DelClientStat and
    delClientStatsByEmails helpers already clean that table; mirror the
    same cleanup in both row-cleanup paths so the record-only and
    record-less delete flows stop leaking baselines.
    
    Closes #5841
  • [Feature]: Add a tooltip/hint to the "Password" field in the client form clarifying which protocols use it (#5809)
    * feat(clients): clarify which protocols use the Password and Hysteria Auth fields
    
    Add tooltips to the Password and Hysteria Auth Form.Items in the client
    form, explaining that Password is only consumed by Trojan and Shadowsocks
    (ignored for VLESS, VMess, Hysteria, WireGuard) and that Hysteria Auth is
    the credential Hysteria actually uses. Adds passwordDesc/hysteriaAuthDesc
    keys to all 13 locale files, following the existing limitIpDesc/totalGBDesc
    tooltip convention.
    
    Closes #5803
    
    * test(clients): assert Password/Hysteria Auth tooltip hints render
  • refactor(mtproto): manage ad-tags per client only
    The inbound-level ad-tag duplicated the per-client override for no
    gain: the fork's global tag applied to every secret anyway, so one
    value had two homes and they could drift. The inbound form field, the
    settings key, and the global ad-tag in the generated config and in the
    PUT /secrets body are gone; the tag is set on each client instead.
    Existing inbound-level values are intentionally not migrated; a
    leftover settings key is stripped on the next save.
  • feat(mtproto): per-client ad-tags, management-API auth, and record secret sync
    Catch the panel up to the mtg-multi README (v1.14.0):
    
    - Each client can now carry its own 32-hex advertising tag overriding the
      inbound-level one. The tag lives on the client (settings JSON is the
      source of truth, clients.ad_tag is the UI projection), is rendered into
      the fork's [secret-ad-tags] section for active secrets only (mtg rejects
      a config whose override names an unknown secret), is pushed per entry
      through PUT /secrets, and is part of the reload fingerprint so a tag
      edit hot-applies without dropping connections.
    - The loopback management API can replace the whole secret set, so every
      mtg process now gets a random per-process api-token; the manager sends
      it as a bearer token on PUT /secrets and GET /stats and reuses it across
      config rewrites, because mtg reads the token only at startup.
    - Malformed tags are rejected at every save path and additionally dropped
      in InstanceFromInbound: one bad tag would otherwise fail the whole
      generated config and take every client of the inbound down with it.
    - SyncInbound never copied a re-keyed mtproto secret into the canonical
      clients table, so the clients page and subscription links kept serving
      the old secret, which mtg then rejects. It is now guarded-copied like
      the other credentials.
  • fix(mtproto): stop dropping connections on client/inbound edits; add live updates + ad-tag (#5838)
    * fix(mtproto): split the mtg fingerprint into structural and secrets parts
    
    A reordered clients array in the stored settings used to read as a config
    change because the fingerprint concatenated secrets in array order, and one
    opaque fingerprint could not tell a restart-worthy change (bind address,
    fronting, throttle) from a secret-set change a reload-capable mtg can absorb
    in place. Sort the secret pairs so order stops mattering, and split the value
    so the upcoming hot-reload path can decide between keeping, reloading, and
    restarting the process.
    
    * fix(mtproto): stop restarting mtg on every inbound edit
    
    Saving an mtproto inbound tore down and respawned its mtg sidecar even when
    nothing material changed, dropping every live Telegram connection: the update
    path pushed DelInbound+AddInbound, and Remove deletes the manager's map entry,
    so Ensure's fingerprint no-op gate could never fire. Route mtproto updates
    through a single Ensure call so an edit that leaves the generated TOML alone
    keeps the process, and only real config changes restart it.
    
    Capturing the pre-edit protocol also fixes a latent leak: changing an
    inbound's protocol away from mtproto never stopped the sidecar, because the
    snapshot handed to the runtime already carried the new protocol and the
    removal took the xray branch, leaving an orphaned mtg holding the port.
    
    An mtproto push failure no longer requests an xray restart - xray cannot fix
    the sidecar, and the 10s reconcile job self-heals it.
    
    The regression test fakes mtg by re-executing the test binary, counting
    spawns through a pid file: an unchanged save and a remark-only edit must keep
    the process, a re-keyed secret must restart it.
    
    * fix(mtproto): exclude depleted clients from the reconcile job to match the sync push
    
    The 10s reconcile job derived mtg secret sets from raw inbound settings while
    the interactive push filtered clients through buildRuntimeInboundForAPI, which
    drops client_traffics-disabled (depleted or expired) clients. The two paths
    therefore disagreed on the fingerprint - each disagreement one needless mtg
    restart dropping live connections - and worse, the job kept serving depleted
    clients' secrets indefinitely, so running out of traffic never actually cut an
    mtproto client's access.
    
    DesiredMtprotoInstances now builds the job's desired state with the same
    depletion overlay the push uses (one bulk client_traffics query), drops
    inbounds whose every secret is filtered away so their sidecar stops, and
    AddInbound pushes the filtered payload too so an imported inbound carrying
    disabled stats does not seed a fingerprint the next reconcile disagrees with.
    
    * feat(mtproto): hot-reload mtg secrets in place instead of restarting
    
    A client add, removal, re-key, or enable-toggle changes only the [secrets]
    section of the generated config, yet the panel could apply it only by killing
    and respawning the mtg sidecar, dropping every Telegram connection on that
    inbound. Split the ensure decision three ways: an identical config is a no-op,
    a secrets-only change rewrites the TOML on the same api port and asks mtg to
    hot-swap it via POST /reload, and a structural change (or a failed reload)
    falls back to the full stop-and-start.
    
    The reload endpoint is served by the mhsanaei/mtg-multi fork; against an older
    binary the POST 404s and the manager restarts exactly as before, so panel and
    binary upgrades stay order-independent.
    
    * feat(mtproto): apply single-client edits to the sidecar immediately
    
    Client CRUD on an mtproto inbound was a runtime no-op, so an add, delete,
    re-key, or enable-toggle only reached mtg on the next 10s reconcile. With the
    sidecar now able to hot-reload, push the change straight after the edit commits:
    applyLocalMtproto rebuilds the inbound's filtered client set and re-applies it,
    so a new client works within a moment (and, on a reload-capable binary, without
    disturbing the others) and deleting the last client stops the process.
    
    The three interactive single-client paths (add, update, delete) call it; bulk
    operations still ride the reconcile job, which converges to the same state.
    
    * chore(mtproto): pin mtg-multi to the mhsanaei fork v1.13.3
    
    The reload endpoint the panel now uses lives in the mhsanaei/mtg-multi fork, so
    point the source-build pin (DockerInit.sh + both release.yml matrices) at it and
    bump to v1.13.3. The install still produces the same mtg-multi binary name, so
    the mtg-<os>-<arch> rename and everything downstream are unchanged. Docs and the
    package comment note the hot-reload path and its restart fallback.
    
    * feat(mtproto): apply live secret updates via the management API and add ad-tag
    
    Two capabilities the mhsanaei/mtg-multi v1.13.3 fork exposes are now surfaced by
    the sidecar manager.
    
    Live updates go through PUT /secrets on the fork's management API instead of
    POST /reload: the panel already holds the whole desired set per inbound, so it
    sends secrets and the advertising tag as one JSON call that mtg applies
    atomically, keeping every unchanged connection and closing only removed or
    re-keyed ones. The config file is still written first so a restart or crash
    recovery reproduces the state, and any non-200 (an older binary, a refused
    connection) still falls back to a full restart.
    
    Per-inbound ad-tag adds an optional 32-hex Telegram advertising tag plus
    public-ipv4/public-ipv6 overrides. The ad-tag rides the reloadable secrets
    fingerprint, so changing it hot-applies without dropping connections; the public
    IPs are proxy-construction parameters and sit in the structural fingerprint, so a
    change there restarts the process. Empty public IPs are omitted so mtg
    auto-detects the reachable address.
    
    * feat(inbounds): expose the mtproto ad-tag and public IP in the inbound form
    
    Adds an Ad-tag field (validated as 32 hex characters) plus optional Public IPv4
    and Public IPv6 overrides to the MTProto inbound form, backed by the same-named
    settings the sidecar writes into the mtg config. The public IPs are optional —
    left blank, mtg auto-detects the reachable address the ad-tag middle proxy needs.
    English strings are added to every locale; the non-English ones carry the
    English text until translated and fall back to it meanwhile.
    
    * ci(mtproto): install mtg-multi from prebuilt release binaries
    
    The fork now publishes release archives for every platform we package, so
    download and unpack the matching mtg-multi-<ver>-<os>-<arch> binary instead of
    compiling it from source with go install. Faster builds and no toolchain step,
    and the archive's platform labels line up with our matrix; the produced
    mtg-<os>-<arch> filenames are unchanged.
    
    * i18n(mtproto): localize the ad-tag and public IP strings
    
    The six mtgAdTag*/mtgPublicIp* keys shipped with English text in every locale as
    a placeholder. Translate them into the twelve non-English locales (Arabic,
    Spanish, Persian, Indonesian, Japanese, Portuguese-BR, Russian, Turkish,
    Ukrainian, Vietnamese, and Simplified/Traditional Chinese); en-US is unchanged.
    
    * retired goreportcard.com
  • fix(mtproto): stop persisting a vestigial inbound-level secret
    MTProto is multi-client: mtg's [secrets] config and every share link read only the per-client secrets. The old HealMtprotoSecret regenerated an inbound-level secret on every save, and seedMtprotoSecretsToClients only dropped it for legacy single-secret inbounds, so multi-client inbounds kept a dead secret. That value once leaked into stale links imported into Telegram, which mtg then rejected as "incorrect client random".
    
    Replace HealMtprotoSecret with StripMtprotoInboundSecret (removes the key), strip on save in normalizeMtprotoSecret, and add a one-time stripMtprotoInboundSecrets migration that runs after the seeder so a legacy secret is first preserved onto a client before the inbound-level copy is dropped.
  • feat(mtproto): adopt dolonet/mtg-multi and make MTProto inbounds multi-client
    Replace the upstream 9seconds/mtg sidecar with the dolonet/mtg-multi fork so a single MTProto inbound can serve many per-user secrets. Each panel client is now one named FakeTLS secret in the fork's [secrets] section: clients are first-class (attach/detach, limits, expiry, per-client tg:// links) exactly like every other protocol, mirroring the WireGuard multi-client model. Per-client traffic and online status come from the fork's /stats JSON API (its Prometheus output has no per-user label), fed into the existing email-keyed client_traffics accumulator; an optional throttle caps concurrent connections. A one-time seeder converts each legacy single-secret inbound into a one-client inbound.
    
    The fork ships only linux/darwin amd64/arm64 binaries but is pure Go, so provisioning builds it from source for every supported platform (release.yml, DockerInit.sh) while keeping the panel-expected mtg-<os>-<arch> filename and the 'run' verb, so process.go is untouched. Also fixes a pre-existing update.sh gap that never renamed the mtg binary for armv6/armv7 updates.
  • feat(db): add pgclient command to install or upgrade PostgreSQL client tools
    Restoring a panel backup made by a newer pg_dump fails when the host's
    pg_restore is older, and the existing pg_ensure_client only installs the
    distribution package when the tools are missing - it can never upgrade,
    and distribution repositories often cap below the required major.
    
    Add pg_upgrade_client to x-ui.sh, exposed as 'x-ui pgclient [major]' and
    as a PostgreSQL menu entry: it checks the installed pg_restore major,
    tries the distribution package for the exact requested major first, and
    falls back to the official PostgreSQL repository (apt on Debian/Ubuntu,
    yum/dnf on Enterprise Linux, with a /usr/pgsql PATH symlink fallback);
    Arch, Alpine and openSUSE install their current package. The panel's
    dump-version mismatch error now names the ready-to-copy command with
    the exact major parsed from the dump header.
  • fix(db): probe dump readability before PostgreSQL import
    pg_restore cannot read archives newer than itself, so importing a dump
    made by pg_dump from PostgreSQL 17+ into a panel with an older
    postgresql-client failed with a raw 'unsupported version (1.16) in file
    header' - and only after Xray had already been stopped for the restore.
    
    Probe the uploaded file with pg_restore --list first, which reads only
    the archive TOC without touching the database, so an unreadable dump is
    rejected before Xray is interrupted. When the failure is a dump-format
    version mismatch, translate it into a message naming the PostgreSQL
    version that produced the dump and the client version to install.
  • feat(outbound): add real-delay connection test mode
    The HTTP probe reports the warm per-request round-trip, which reads
    lower than the delay figure client apps show for the same server. Add a
    third "real" test mode that reuses the temp-instance HTTP probe but
    reports the cold request's full elapsed time - tunnel establishment
    included - and skips the warm request. UDP-transport outbounds forced
    out of the TCP lane still report "http"; in real mode they report
    "real". The mode joins the TCP/HTTP toggle on the outbounds tab, with
    the label translated in all 13 locales.
  • fix(client): stop duplicate client entries accumulating in inbound settings
    Adding a user to multi-node inbounds could leave 3-6 identical entries
    in one inbound's settings.clients array: addInboundClient appended
    incoming clients unconditionally, and the duplicate-email precheck
    exempts a matching subId (so one identity can span several inbounds),
    so a retried or raced add of the same client re-appended it to an
    inbound that already carried it - on the master and, since nodes run
    the same code, on every node, whose snapshot adoption then copied the
    duplicates back verbatim. The normalized clients/client_inbounds tables
    stayed clean (unique constraints), which is why the phantom rows only
    showed in settings-driven views like the Detach clients modal, where
    duplicate React keys also broke the selection counter.
    
    Three layers: addInboundClient now skips incoming clients whose email
    is already on the target inbound (idempotent re-adds instead of
    duplication), node snapshot adoption collapses duplicate emails before
    writing the central row, and an idempotent startup repair rewrites any
    inbound whose settings still carry duplicates from older builds.
    
    Closes #5770
  • fix(db): clamp traffic counters below int64 max and repair overflowed rows
    A counter pushed past int64 (multi-node setups hit this via historic
    delta-compounding bugs) makes SQLite silently promote the INTEGER cell
    to REAL. From then on the column no longer scans into the Go int64
    field and every reader of client_traffics fails at once: the inbounds
    page, xray restarts, and node traffic sync all return "converting
    driver.Value type float64 to int64".
    
    Two-part fix: every unbounded "up = up + ?" add (local traffic, node
    delta merge, inbound counters, plus the Go-side outbound accumulation)
    now saturates at TrafficMax, a cap safely below math.MaxInt64 so one
    more delta cannot overflow; and a startup repair casts REAL-promoted
    cells back to INTEGER and clamps all traffic counters into
    [0, TrafficMax] across client_traffics, inbounds, outbound_traffics
    and node_client_traffics, restoring access to already-corrupted panels
    without manual sqlite surgery.
    
    Closes #5762
  • fix(node): fully delete clients on nodes instead of only detaching them
    Deleting a client on the master propagated to nodes via the detach
    endpoint, which removes the client from that one inbound's settings but
    deliberately keeps the client record. The node ended up with an
    orphaned record that kept showing in its Clients view; the master and
    node could never converge on a delete.
    
    Full-delete and detach intent now travel separately: the Runtime
    interface gains DeleteClient, which on Remote hits the node's
    panel/api/clients/del endpoint (record, attachments, traffic; repeat
    calls for a client on several inbounds of the same node are swallowed
    as idempotent "not found"). Delete/DeleteByEmail/BulkDelete use it for
    node inbounds, while Detach/BulkDetach keep the inbound-scoped detach
    RPC so removing a client from one inbound never wipes it node-wide
    (the #5543 guarantee is preserved and covered by tests). Bulk deletes
    above the fold threshold still converge membership via reconcile; their
    leftover node records can be cleaned with the node's delete-orphans
    action.
    
    Closes #5797
  • fix(outbound): measure HTTP test delay on a warm connection
    Since the batched prober replaced the single tester, the reported delay
    came from one cold request with keep-alives disabled, so it stacked the
    SOCKS handshake, proxy dial, proxy TLS, target TCP and target TLS on top
    of the round-trip. Users upgrading from v2.9.4 - whose tester warmed the
    connection first and timed a second request - saw several times the real
    connection time.
    
    The cold request still proves reachability and supplies the HTTP status
    plus the connect/TLS/TTFB breakdown; the delay is now re-measured on a
    second request over the kept-alive connection, falling back to the cold
    total when the warm request fails. Bodies are drained (bounded) so the
    connection returns to the pool, and the batch test asserts both requests
    of a probe share one connection.
  • fix(tgbot): find clients by tgId regardless of settings JSON formatting
    The Telegram-bot usage lookup prefiltered inbounds with
    settings LIKE '%"tgId": N%', which requires the exact space the panel's
    MarshalIndent happens to emit. Inbounds whose settings were serialized
    compactly (node sync, imports, external edits) never matched, so the
    bot reported no configuration even though the client and traffic rows
    exist. Replace the string match with the driver-portable JSON helpers
    already used by GetAllEmails, which read the actual clients array on
    SQLite and Postgres alike.
    
    Closes #5805
  • fix(node): stop client edits from tearing down node inbounds and harden reconcile fingerprints
    A client save on the master always stamped a fresh updated_at, marked
    the node dirty, and let the 5s sync push a full inbounds/update to the
    node, where applying it removes and re-adds the Xray handler - killing
    live traffic on every edit, including no-op saves (open the editor,
    click Save). Nodes stayed online with Xray running while forwarding
    nothing until a manual Xray restart.
    
    - No-op client saves preserve the client's updated_at and return before
      any DB write, runtime RPC, or node dirty mark when the effective
      settings did not change.
    - Successful per-client add/update/delete pushes advance the node's
      reconcile-skip fingerprint only when the recorded fingerprint proves
      the node held the exact pre-edit payload and every push in the edit
      succeeded (Remote.AdvancePushedInbound). Anything unproven keeps the
      stale fingerprint so the dirty reconcile still sends the full inbound.
      Unconditional stamping would certify folded bulk changes (threshold,
      flow change, offline edit) or partially failed batches as delivered:
      a folded 41->6 bulk delete followed by one live edit left the node
      permanently serving all 41 clients in end-to-end testing, with the
      snapshot adoption then resurrecting the deleted clients on the master.
    - DeleteUser treats only an envelope-level not-found as already deleted;
      an HTTP 404 from an old node build without the detach endpoint
      surfaces as an error instead of certifying an undelivered delete.
      cacheDel drops the fingerprint alongside the id cache so DelInbound
      and tag renames leave no stale skip entry.
    - Adopting the node's own settings serialization into the master row now
      also stamps the fingerprint (RecordAdoptedInbound). Without it the
      serialization round-trip invalidated the fingerprint one sync tick
      after every push, so each edit degraded back to a full teardown push.
    - UpdateInboundClient applies the Shadowsocks method normalization
      before the no-op comparison (real method changes bump updated_at, SS
      no-op edits are detected) and syncs the generated subId into the
      pushed client so the node cannot mint a different one.
    
    Verified with a two-panel docker deployment: no-op saves produce zero
    node requests, real edits send one lightweight clients/update RPC with
    zero full inbound updates and zero handler teardowns, and folded bulk
    deletes still converge.
    
    Based on PR #5778 by @rqzbeh.
    
    Closes #5764
    Closes #5771
  • feat(ui): client-realtime-speed (#5687)
    * refactor(inbounds): extract TRAFFIC_POLL_INTERVAL_S to shared util
    
    * feat(clients): derive per-client live speed from traffic WebSocket deltas
    
    * feat(clients): render speed column and mobile card line
    
    * i18n(clients): add pages.clients.speed key to all 13 locales
  • fix(node): stop one rejected inbound from starving a node's traffic sync
    A legacy socks inbound (predating the socks-to-mixed protocol rename) fails the node's request validation when pushed. ReconcileNode aborted on the first failed inbound and syncOne then skipped the traffic snapshot entirely and never cleared ConfigDirty, so the whole node re-failed every tick and the master stopped deducting traffic for every client on that node, exactly as reported in #5685.
    
    Three-part fix: ReconcileNode now pushes every inbound and runs the delete sweep even past individual failures, returning the failures joined; syncOne logs a failed reconcile but continues with the traffic pull (dirty stays set, so reconcile retries and the merge stays in its conservative mode); and a migration renames legacy socks inbounds to mixed, which has an identical settings shape, removing the known trigger.
    
    Closes #5685
  • feat(tgbot): register usage, inbound, restart and clearall in the bot command menu
    The Telegram command menu listed only start/help/status/id although usage, inbound and restart were already handled, and resetting all traffic was reachable only through inline keyboards. Register all handled commands with localized descriptions and add an admin-gated /clearall command that reuses the existing reset-all confirmation keyboard, so nothing destructive runs without an explicit confirm.
    
    Closes #5307
  • feat(tgbot): show inbound remark alongside email in the online clients list
    Online-client buttons showed only the email, which is ambiguous when the same usernames exist across inbounds. Label each button email - remark via the canonical GetClientInboundByEmail lookup (first matching inbound for multi-inbound clients); the callback payload stays the bare email.
    
    Closes #5318
  • feat(clients): hide disabled inbounds in the client form selector
    The attach-inbounds select in the client add/edit modal listed every inbound, so panels with many disabled inbounds had to scroll past dead entries. InboundOption now carries the inbound's enable flag and the form drops disabled inbounds from the options, keeping ones the client is already attached to so edit mode still renders existing assignments.
    
    Closes #5645
  • feat(tgbot): include hostname in backup and ban-log messages
    Backup and ban-log pushes carried no server identity, so admins running the bot against several panels could not tell which server a backup came from. Prepend the same hostname line the periodic report and event notifications already use; the tgbot.messages.hostname key exists in all locales, so no new i18n keys are needed.
    
    Closes #5387
  • fix(panel): use the hosting node address for WireGuard client configs (#5679)
    * fix(panel): use the hosting node address for WireGuard client configs
    
    The clients page rendered a node-managed WireGuard inbound's config with the
    master panel's host in Endpoint instead of the hosting node's address, so the
    copied/QR config pointed at the wrong server. The subscription path already
    resolves this via resolveInboundAddress; the UI generator did not.
    
    Expose the share-host resolution inputs (node address, listen, share-address
    strategy/address) on InboundOption and route buildWireguardClientConfig through
    the same canonical resolver the inbounds-page share links use, extracted as
    resolveShareHost. This also brings local inbounds with a shareable listen or a
    listen/custom share strategy into parity with the subscription Endpoint; the
    common listen=0.0.0.0 case still falls back to the panel host.
    
    * fix(frontend): keep a raw fallback host and refresh node-fed inbound options
    
    Code review of the WireGuard node-endpoint change surfaced two gaps.
    resolveShareHost normalized its last-resort fallbackHostname, so a panel
    reached via a hostname the share-host grammar rejects (underscore label,
    trailing-dot FQDN) emitted a broken 'Endpoint = :51820'; the fallback now
    stays verbatim when normalization empties it. Node mutations only
    invalidated the nodes query, leaving the staleTime-Infinity inbound
    options cache serving an edited node address until the sync job
    broadcast (never, for disabled/offline nodes); they now invalidate the
    options key too.
    
    Also folds the ShareHostFields projections into direct structural passes,
    elides the default node shareAddrStrategy so omitempty drops it, and
    replaces the nullable node-address scan with COALESCE.
    
    ---------
    
    Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • docs(settings): clarify Sub Port/Sub Domain double as subscription-link fallback (#5721)
    * docs(settings): clarify Sub Port/Sub Domain double as subscription-link fallback
    
    subPort/subDomain are documented purely as the subscription service's own
    listen address, but when "Reverse Proxy URI" is empty, GetDefaultSettings
    silently reuses them (with the admin API request's own Host header as the
    domain fallback) to build the subscription link/QR shown in the panel.
    Behind a reverse proxy where the sub service listens on an internal port
    and is exposed externally on a different port/domain, this produces a
    broken link even though "Reverse Proxy URI" already solves it - nothing
    in the UI text pointed to it. Clarify all locales.
    
    * docs(settings): fix wording nits from review (punctuation, CJK parens, es-ES field name)
    
    - en-US/id-ID/pt-BR/tr-TR/uk-UA/ar-EG: add terminating punctuation before
      the appended sentence so it doesn't run on directly after the closing
      parenthesis.
    - zh-CN/zh-TW/ja-JP: restore full-width CJK parentheses around the
      pre-existing parenthetical, matching the rest of each file.
    - es-ES: subURIDesc referenced "Dominio/Puerto de escucha", but the
      actual field labels in this locale are "Dominio de Escucha" and
      "Puerto de Suscripción".
    
    ---------
    
    Co-authored-by: Volov <volovdata@google.com>
  • feat(frontend): add targetStrategy field to the outbound editor
    Xray-core added a top-level targetStrategy to OutboundObject that
    controls how the destination domain is resolved before dialing
    (AsIs/UseIP*/ForceIP*, any protocol). The panel neither offered a
    control for it nor preserved the key across the modal's JSON round
    trip, so hand-written values were silently dropped on save.
    
    The form now carries targetStrategy next to sendThrough as a select
    of the 11 canonical values; the adapter normalizes wire values to
    canonical case (the core matches case-insensitively) and omits the
    key when unset. Freedom settings additionally read the new
    settings-level targetStrategy with domainStrategy as fallback,
    mirroring the core, while still emitting the legacy domainStrategy
    key so configs keep working on older cores.
  • fix: make all self-managed file downloads/installs atomic, with real completion status (#5711)
    * fix(script): download the live x-ui.sh script atomically before replacing it
    
    update_menu(), update_shell(), and update.sh's update_x-ui() all overwrote
    /usr/bin/x-ui in place via `curl -o`, truncating and rewriting the same
    inode a currently-running x-ui process may still be reading from. A
    network hiccup or slow write during that overwrite leaves a
    half-old/half-new script on disk, which then fails with bogus syntax
    errors on the next run. Download to /usr/bin/x-ui-temp and `mv -f` into
    place instead, matching the atomic pattern install.sh already uses.
    
    Also fixes update_menu() checking chmod's exit code instead of curl's,
    which meant a failed download could still report "Update successful."
    
    * fix(script): close remaining gaps in the atomic script-update path
    
    Code review of the previous commit found the atomic mv fix was itself
    incomplete:
    
    - None of the mv -f calls checked their exit status, so a failed move
      fell through to chmod and "success" messaging while /usr/bin/x-ui
      stayed on the old file.
    - update_shell()'s `[[ -s x-ui-temp ]]` guard couldn't tell "curl -z
      got a 304, nothing to do" from "a stale temp file survived an
      earlier crashed run" -- the latter could get moved into place with
      no freshness check.
    - update_menu(), update_shell(), and update_x-ui() all hardcoded the
      same /usr/bin/x-ui-temp path, so two concurrent updates (e.g. a
      cron auto-update racing an interactive menu update) could collide.
    - update.sh's update_x-ui() was missing the non-empty-file guard
      update_shell() already had.
    
    x-ui.sh's update_menu() and update_shell() now share a
    replace_xui_script() helper that uses a PID-suffixed temp path
    (/usr/bin/x-ui-temp.$$), pre-cleans it before every attempt, and
    checks the exit status of curl, the non-empty test, and mv before
    treating the update as successful. update.sh's update_x-ui() gets the
    same sequence inlined (it's fetched as a standalone script and can't
    call x-ui.sh's function), closing the missing-guard gap and using its
    own unique temp path.
    
    * fix(script,panel): harden the remaining self-update download paths
    
    install.sh had the same unguarded /usr/bin/x-ui-temp overwrite the two
    already-fixed scripts had: no exit-status check on mv, and a fixed temp
    name shared with x-ui.sh/update.sh's (now-unique) temp files. Give it
    its own PID-suffixed temp path, an empty-file guard, and an mv
    exit-status check, matching the pattern used there.
    
    Audited the web dashboard's Go-native updater (panel.go) for the same
    bug class: it already uses os.CreateTemp for a genuinely unique temp
    file and cleans up via both a deferred Remove and a shell EXIT trap, so
    it was never exposed to the fixed-path race. It was missing a check
    for a zero-byte download (a 200 OK with an empty body would chmod +x
    and exec an empty script) -- added that alongside the existing size
    cap.
    
    Not addressed here: once startUpdate()'s child process starts, the Go
    service releases it and returns success immediately. If update.sh
    fails partway through, the still-running old panel keeps answering
    /status, so the frontend's poll can report success with no update
    having happened. Fixing that needs update.sh to signal completion
    status back and the frontend to check it -- a separate follow-up.
    
    * feat(panel): report real completion status for the web self-update
    
    Fixes the fire-and-forget gap flagged in the atomic-overwrite fix: once
    startUpdate() launches update.sh detached, the Go service had no way to
    learn whether it actually succeeded. If update.sh failed partway
    (network drop, disk full, permission denied), the still-running old
    panel kept answering /status, so the frontend's poll reported success
    with nothing having changed.
    
    update.sh now writes its outcome to a small JSON status file
    (/etc/x-ui/update-status.json by default) via `trap ... EXIT`, which
    covers every exit path in the script -- including the two bare `exit 1`
    call sites that don't go through the existing _fail() helper. The Go
    service generates a run ID before launching, passes it and the status
    path to update.sh via XUI_UPDATE_RUN_ID/XUI_UPDATE_STATUS_FILE, and a
    new GET /panel/api/server/getUpdateStatus endpoint reports it back. The
    frontend now polls that instead of blindly trusting HTTP reachability,
    and shows a distinct error or "couldn't confirm" message instead of
    silently reloading into a false success.
    
    Adversarial review of this surfaced three more issues, fixed here:
    - No lock stopped two concurrent /updatePanel calls from launching two
      update.sh runs that would race each other on the actual update work
      (tar extraction, service unit swap). Added an in-memory guard with a
      5-minute self-expiring window, so a run that never reaches a terminal
      state doesn't lock out retries indefinitely.
    - XUI_UPDATE_RUN_ID is read from the environment and was interpolated
      unquoted into the status JSON; a malformed value would produce
      invalid JSON. Now validated as digits-only before use.
    - The run ID is a UnixNano timestamp (19 digits), sent as a raw JSON
      number it would lose precision in JavaScript (past
      Number.MAX_SAFE_INTEGER), letting two different runs round to the
      same value on the wire and defeat the whole comparison. It's now a
      decimal string end to end (Go, the status file, and the generated
      frontend type).
    
    install.sh's equivalent temp-file/mv path and the Go-native
    downloadPanelUpdater() path were audited for the same bug classes
    during this work; findings from that audit were addressed separately.
    
    * fix(panel): release the update lock as soon as the run finishes
    
    An exhaustive multi-angle review of the whole branch (12 finder angles,
    3-vote adversarial verification, a fresh-eyes sweep) surfaced a real
    bug in the concurrency guard added in the previous commit, plus several
    smaller issues; this fixes what's actionable now.
    
    The bug: acquireUpdateSlot only ever released on the 5-minute stale
    timeout or if launching itself failed. If update.sh launched fine but
    failed fast (bad GitHub API response, "x-ui not installed", any of its
    early exit paths), the status file correctly reported "failed" within
    seconds, but a retry was still rejected with "a panel update is
    already in progress" for up to 5 more minutes -- the guard never
    looked at the very status file this branch built to know a run was
    done. It now tracks which run ID currently holds the slot and checks
    that run's own status before falling back to the timeout, so a fast
    failure clears the way for an immediate retry. Added a regression test
    for this, plus one confirming a stale, unrelated runID can't be
    mistaken for the current run finishing.
    
    Also:
    - Added a genuinely concurrent test for the guard: 200 goroutines
      racing acquireUpdateSlot, asserting exactly one wins. The previous
      tests only ever called it from one goroutine, so they gave no signal
      if the mutex's check-then-set were silently broken -- verified this
      by temporarily removing the lock and confirming the old tests still
      passed while the new one caught it immediately under -race.
    - Removed the redundant upfront "pending" status write: GetUpdateStatus
      already defaults a missing/stale file to pending, and the frontend
      matches by run ID regardless, so the write changed no observable
      behavior. Deleted writeUpdateStatus entirely since that was its only
      caller.
    - Renamed replace_xui_script()'s unclear "conditional" parameter to
      use_if_modified_since, matching what it actually controls.
    - Added HTTP-level tests for the new getUpdateStatus endpoint,
      including a regression test that the runId wire format is a JSON
      string (decoding into a Go string field fails outright if it were
      ever a bare number). updatePanel's actual launch path is not
      covered: on a Linux test runner it would make a real network call
      and could exec a real update.sh, so only its non-Linux guard path is
      safely testable without mocking.
    
    Not fixed here, tracked separately: the same unsafe-overwrite pattern
    this branch eliminated for /usr/bin/x-ui is still present for the
    systemd unit file install in update.sh and install.sh (lower severity
    since systemd only reads it on daemon-reload, not continuously); and
    startUpdate's systemd-run-vs-detached-fallback branching has no test
    coverage since testing it safely needs dependency injection this fix
    doesn't warrant bundling in.
    
    * fix(script): make systemd unit file installation atomic
    
    Same anti-pattern as the /usr/bin/x-ui overwrite fixed earlier: every
    site that lands the systemd unit at ${xui_service}/x-ui.service --
    copying it from the extracted release tarball, or falling back to a
    GitHub download per distro family -- wrote straight onto the live
    path via cp/curl, no temp file, no verification. A network drop
    mid-download or an interrupted cp leaves the unit file truncated;
    systemd then fails to parse it on the next daemon-reload/start,
    leaving the panel unable to come up until an operator manually
    re-copies a good unit file.
    
    Lower severity than the /usr/bin/x-ui case (systemd only reads this
    file on demand at daemon-reload time, not continuously the way bash
    interprets a running script line by line), but it's the identical
    gap, just left uncovered when that fix landed.
    
    Added a small shared helper in both update.sh and install.sh --
    _install_xui_service_unit() -- covering both source types (cp from
    the tarball, curl from GitHub): write to a PID-suffixed temp file,
    verify the copy/download succeeded and the result is non-empty, then
    mv -f into place and check that exit status too, matching the pattern
    already used for /usr/bin/x-ui. All 4 cp sites and the 3-way curl
    fallback in each file now go through it; verified no other site
    writes new content to the unit path (the remaining ${xui_service}
    references are a pre-install existence check, an rm during old-version
    cleanup, and the chown/chmod that already ran after the file is safely
    in place -- none of those need atomicity).
    
    Verified with bash -n on both files, plus a standalone scratch test
    exercising cp-success, cp-with-missing-source, cp-with-empty-source,
    and curl-failure paths: on every failure the previous, good unit file
    content is left untouched and no temp file is leaked behind.
    
    * fix(script): make Alpine's OpenRC init script install atomic; drop a stray comment
    
    A final maximum-rigor review of the whole PR (12 finder angles including
    a repo-wide sweep for any remaining instance of the bug class this PR
    fixes) found two more real issues:
    
    - Alpine's /etc/init.d/x-ui startup script is downloaded via a bare
      `curl -fLRo` straight onto the live path in both update.sh and
      install.sh -- the exact same unguarded-overwrite pattern already
      fixed for /usr/bin/x-ui and the systemd unit file, just left
      uncovered on the OpenRC side. A network drop mid-download truncates
      the live init script; OpenRC then fails to source/execute it on the
      next start, leaving the panel unable to come up. Fixed with the same
      temp-file + non-empty check + mv -f (with its own exit-status check)
      pattern used everywhere else in this PR. Verified with bash -n and a
      standalone scratch-script test covering success, empty-download, and
      destination-preserved-on-failure paths.
    
    - internal/web/service/panel/panel_test.go had one line-level `//`
      comment on a call site, which the root CLAUDE.md's hard rule ("No //
      line comments in committed Go/TS... rename instead of annotating")
      explicitly prohibits. The comment duplicated context already stated
      in the test's own doc comment two lines above, so it's simply
      removed rather than reworded.
    
    Also flagged, deliberately not bundled here since it's a different
    subsystem: x-ui.sh's update_geofiles() downloads Xray's live
    geoip.dat/geosite.dat with the same unguarded curl -o pattern. Tracked
    as its own follow-up.
    
    * fix(script): make geo-data file downloads atomic
    
    Same anti-pattern as /usr/bin/x-ui, the systemd unit file, and the
    Alpine init script fixed in prior PRs: update_geofiles() downloaded
    Xray's live geoip.dat/geosite.dat (and the IR/RU variants) with curl
    writing straight onto the exact path Xray reads at runtime
    (internal/xray/process.go's GetGeoipPath/GetGeositePath), no temp
    file, no verification. The existing check only inspected the reported
    HTTP status via -w '%{http_code}', not file integrity, so a network
    drop mid-download could leave a truncated .dat file on disk that
    passes the status check. Xray then fails to parse it on the next
    restart/reload, breaking any routing rules that reference geoip:/
    geosite:.
    
    The -z conditional-GET usage needed care here: the original code
    pointed both -z and -o at the same live path. Fixed by pointing -z at
    the live file (to keep the "already current" freshness check) while
    -o writes to a PID-suffixed temp file, matching the pattern already
    proven in x-ui.sh's replace_xui_script(). Verified with a local HTTP
    server that a 304 response leaves the temp file untouched/nonexistent
    (so the existing "already up to date" branch still works unchanged),
    and added a non-empty check plus a checked mv -f before treating a
    download as installed.
    
    Verified with bash -n and an end-to-end scratch test against a local
    server covering: fresh download, 304-not-modified, empty response
    body, and a 404 -- confirming a failure at any stage leaves the
    previous good .dat file completely untouched and no temp file behind.
    
    * fix(script): verify the release tarball extraction, not just the download
    
    The final maximum-rigor review found the most significant remaining gap
    in this whole effort: update.sh and install.sh check the tarball
    download's exit status, but never check tar's exit status, and never
    verify the extracted x-ui binary actually exists before continuing.
    Worse, by the time extraction runs, the previous installation has
    already been stopped and deleted -- there's no rollback. A truncated
    download that still passes curl's own check, or a tar failure (disk
    full, killed process), left the panel silently in a broken half-state:
    chmod/config/service-install all continued to run against a missing or
    empty binary, with no error surfaced anywhere. This is the same bug
    class as everything else in this PR (unverified write to a path
    something then depends on), just for the tarball itself rather than a
    single file -- and it also covers the geo-data files this PR already
    fixed once for the interactive/cron path, since they ship inside this
    same tarball on every panel update.
    
    Added: a non-empty check on the downloaded archive (both files, both
    install.sh call sites) and a check that tar succeeded and produced a
    non-empty x-ui binary before proceeding, failing loudly with a message
    that explicitly says the previous install is already gone, since
    silently continuing here is worse than anywhere else in this PR.
    
    This doesn't make the multi-file extraction fully atomic (that would
    mean extracting to a temp directory and atomically swapping the whole
    install tree into place, a materially larger restructuring than
    anything else in this PR) -- but it closes the "fails silently, user
    discovers it days later when Xray can't start" gap, which was the
    actual reported problem this whole effort traces back to.
    
    Also fixed, all much smaller:
    - replace_xui_script() in x-ui.sh implicitly returned chmod's exit
      status instead of success, so a successful atomic install could be
      reported as failed if chmod transiently failed after the mv already
      landed the new script. Added an explicit `return 0`.
    - update_geofiles() had no default case branch; an unrecognized
      argument would silently reuse whatever dat_files/dat_source values a
      previous call left in the un-scoped globals instead of failing.
      Currently unreachable (all three call sites pass fixed literals) but
      cheap, defensive, and worth having.
    - internal/web/controller/server.go's updatePanel has one branch (an
      unparseable "dev" form value) that's both untested and safe to test
      on any platform, since it's rejected before any real exec/network
      call. Added the missing test case.
    
    Verified: bash -n on all three scripts; an empirical scratch test
    covering an empty downloaded archive, a corrupt (non-gzip) archive,
    and a successfully-extracting-but-empty archive, confirming each is
    caught before the script proceeds; full go build/vet/test -race
    across the whole module; frontend generation confirmed still in sync.
    
    * fix(panel): base the update-slot staleness fallback on process liveness
    
    Addresses the automated review on the upstream PR (MHSanaei/3x-ui#5711).
    
    Blocking finding: acquireUpdateSlot's staleness fallback freed the
    update slot purely on elapsed wall-clock time (5 minutes), with no
    check on whether the update.sh process it launched was actually still
    running. update.sh runs install_base() (apt-get/dnf/pacman update and
    install) before update_x-ui even starts, plus several GitHub
    downloads (release tarball, x-ui.sh, and possibly a service unit or
    x-ui.rc) -- on a slow or throttled host, a small VPS being the typical
    deployment target for this project, that alone can plausibly exceed 5
    minutes with nothing wrong. A second /updatePanel call arriving in
    that window (an admin retrying after the frontend's 90s poll times
    out, or overlapping master-node bulk-update calls) would launch a
    second update.sh, racing the exact rm/tar/mv/systemctl sequence this
    whole PR exists to make safe.
    
    Fixed by recording the launched process's PID (detached-fallback path
    only; the systemd-run path's own process has already exited by the
    time startUpdate returns, so it never learns update.sh's real PID) and
    checking it via the standard POSIX kill(pid, 0) liveness probe before
    treating a run as stale, following the existing panel_unix.go /
    panel_other.go platform-split pattern already used for
    setDetachedProcess. A confirmed-alive process now keeps the slot held
    past updateStaleAfter (raised from 5 to 20 minutes as a safer baseline
    for the systemd-run path, which still has no way to check liveness
    directly). updateHardCeiling (2 hours) is an absolute backstop so a
    genuinely wedged run can never lock out retries permanently even on
    the PID-tracked path.
    
    Added two regression tests exercising the new logic (gated to Linux,
    since processAlive is a no-op stub elsewhere): a live PID keeps the
    slot held past the stale window, and the hard ceiling overrides
    liveness. Traced both by hand against the new acquireUpdateSlot logic;
    could not execute-verify processAlive itself on this Windows dev
    machine (no WSL distro installed, and installing one felt
    disproportionate to validate kill(pid, 0), an extremely well-established
    POSIX primitive), but cross-compiled clean for linux/amd64 and this
    repo's CI runs the real test suite on Linux.
    
    Also fixed, both suggestions from the same review:
    - install.sh: two failure paths right after tarball extraction were
      exiting without cleaning up the already-downloaded x-ui.sh temp file
      (xui_script_temp), leaving it behind. Every other new failure branch
      in this PR removes its temp file before exiting; these two now do
      too.
    - frontend/src/pages/api-docs/endpoints.ts: updatePanel's doc entry
      did not reflect that a successful response now carries an obj with
      runId. Added an inline response example matching the existing
      pattern used for other ad hoc (non-schema-backed) responses like
      getWebCertFiles.
    
    Verified: go build/vet clean on both windows (native) and a linux/amd64
    cross-compile; full go test ./... clean; go test -race on the panel
    and controller packages; bash -n on all three shell scripts; npm run
    gen confirms the openapi.json diff is exactly the new response example
    with no stray changes to src/generated; TestAPIRoutesDocumented still
    passes.
  • fix(balancers): keep mixed strategies on one observer (#5674)
    * fix(balancers): keep mixed strategies on one observer
    
    Xray resolves Observatory and Burst Observatory through the same global observer feature. When any burst-required strategy is present, keep all observer-backed balancer selectors on burstObservatory and remove the regular observatory so mixed leastPing configs cannot generate two competing observer blocks.
    
    * test(balancers): cover observer strategy combinations
    
    Exercise the observer sync matrix for random, round-robin, leastPing, and leastLoad balancers. Include mixed and stale-observer cases so the panel keeps only the observer type that Xray should consume.
    
    * fix(balancers): clarify observer empty state
    
    Update the Observatory tab empty hint to describe the actual auto-managed cases. Least Ping, Least Load, and fallback Random or Round-robin balancers now explain why an observer is added before the balancer can choose a target.
    
    * fix(balancers): remove mixed observer switch
    
    Show only the observer settings panel that matches the current balancer requirements. Legacy configs that still contain both observatory blocks now display a warning instead of a tab switch, since saving balancers normalizes the config back to one global observer.
    
    * test(balancers): cover observer cleanup on deletion
    
    Add direct balancer deletion and outbound cascade cases for leastLoad, fallback, and mixed leastPing scenarios. These tests pin that the final unneeded observer is removed, burst switches back to regular observatory when only leastPing remains, and burst remains when a burst-required balancer survives.
  • fix(sub): resolve subscription clients and stats from normalized tables
    A subscription fetch inside a large inbound cost seconds because every
    layer re-parsed the inbound's full settings JSON: getInboundsBySubId
    preloaded the whole client_traffics table of each matched inbound,
    matchingClients parsed all clients to filter by subId, and then every
    per-protocol generator (raw links, JSON outbounds, Clash proxies) parsed
    the blob again per link — once to find the client by email and once for
    inbound-level fields like encryption or method. At 500k clients in one
    inbound that was 13s per raw fetch and 8.5s per JSON fetch; at 100k,
    2.6s/1.7s. After this change both cost ~70ms at 100k.
    
    matchingClients now resolves through the indexed clients/client_inbounds
    tables (ListForInboundBySubId, ordered by clients.id like ListForInbound
    — the same source the running Xray users are built from), and the
    per-request SubService carries two caches: clientsByInbound, primed by
    matchingClients/inboundLinks so clientForLink resolves a client without
    parsing settings (with the old full-parse as fallback, which also fixes
    the export-all-links path that re-parsed the blob once per client), and
    settingsByInbound, a once-per-request shallow decode that skips
    materializing the clients array entirely. The ClientStats preload is
    replaced by loading only the subscriber's traffic rows (indexed
    clients.sub_id); statsForClient's per-email DB fallback (#5567) covers
    any miss, and the case-insensitive email dedupe keeps the #5134
    guarantee for case-differing duplicate rows.
  • fix(job): batch ip-limit per-email lookups and persistence
    processObserved paid four round-trips per observed email every 10s scan:
    an inbound-resolving join, a tracking-row read, an autocommit Save (one
    fsync each under synchronous=FULL), and — worst of all — a full JSON
    parse of the owning inbound's settings blob just to read that one
    client's limitIp. On a big single inbound that parse alone made a scan
    cost ~1.5s per online client.
    
    The scan now front-loads three chunked batch queries (clients.limit_ip,
    email->inbound through the client_inbounds relation keeping the lowest
    inbound id like the old First(), and the tracking rows) and writes every
    inbound_client_ips change inside one transaction, so M observed emails
    cost a handful of queries and a single fsync. The per-email LIKE fallback
    remains for emails missing from the relation, preserving the #4963
    stale-email cleanup. limitIp now comes from the clients table (same
    source B3 gates on) instead of the settings blob, and xray disconnects
    for banned clients run after the commit so their network round-trips
    never extend the write transaction node syncs contend with.
  • feat(web): broadcast delta client stats above a snapshot threshold
    Both 5s broadcasters (the local traffic poll and the node traffic sync)
    shipped the complete client_traffics table on every cycle while a browser
    was connected. At 500k clients that is a 1.7s full-table read plus an
    86MB marshal per job per poll — and the hub drops any payload over 10MB
    and sends an invalidate the frontend ignores for these message types, so
    past ~55k clients all of it was pure waste and the UI got nothing.
    
    Installs at or below 5000 clients (clientStatsSnapshotMaxClients) keep
    the exact full-snapshot behavior — it exists because a pure delta feed
    left UI rows stale when nothing moved in a cycle (see GetAllClientTraffics)
    — and the payload now carries snapshot=true. Above the threshold the jobs
    send only this cycle's active rows (the xray poll's active emails, or the
    emails online on the synced nodes) with snapshot=false, and scope the
    last-online map to those rows; the initial full map still arrives over
    REST and the clients page refetches every 5s.
    
    GetActiveClientTraffics gains the overlayGlobalTraffic pass so delta rows
    carry the same cross-panel usage as snapshot rows. The node job also
    stops reading the full last-online map before the has-clients gate, which
    was a wasted full-table read on every tick with no dashboard open.
    
    Frontend: useClients keeps its live summary strictly snapshot-driven
    (snapshot=false payloads skip the allClientStats replace and the summary
    falls back to the server-computed one); the per-row page merge and the
    inbounds-page merges already handle deltas.
  • fix(job): gate ip-limit scan on clients.limit_ip instead of parsing all settings
    hasLimitIp ran settings LIKE '%limitIp%' and JSON-parsed every matching
    inbound's settings blob — and since clients marshal limitIp without
    omitempty, every inbound matched, so each 10s scan loaded and parsed
    every settings blob in the database (~75MB of JSON at 500k clients) just
    to decide whether any limit exists.
    
    It now probes the normalized clients table (limit_ip > 0, Limit(1) count
    like depletedCond does), which SyncInbound and the legacy seeder keep in
    sync with the settings JSON. Semantics note: a limitIp that exists only
    in settings JSON with no clients row no longer enables enforcement — the
    enforcement path itself already resolves clients through the same
    normalized tables.