Commit Graph
3060 Commits
  • fix(ui): make the Happy Eyeballs toggle produce a config xray actually enables
    Toggling Happy Eyeballs on filled the object with schema defaults, and
    tryDelayMs defaulted to 0. That broke the feature twice over: xray-core
    treats tryDelayMs=0 as happy-eyeballs-off, and the wire normalizer
    strips every field that equals its default, leaving an empty object it
    then deletes - so the switch silently flipped back off on reopen (the
    "disabled when Prefer IPv6 is off" symptom; prioritizeIPv6=true was the
    one non-default that let the object survive). Default tryDelayMs to the
    recommended 250ms so an enabled config survives serialization and is
    functional in the core.
    
    Closes #5780
  • fix(ui): align the subUpdates limit with the backend and show the range
    The hand-written settings schema capped subUpdates at 168 while the
    backend (and the generated schema mirrored from it) accepts 0-525600.
    Anyone upgrading from 2.x with a stored value above 168 could no longer
    save any settings tab: the whole settings object is validated on every
    save, so the stale field blocked everything with an unexplained
    "Invalid input". Match the backend bounds and put them on the input so
    the limit is discoverable.
    
    Closes #5821
  • fix(script): rename the Xray binary to xray-linux-arm32 on 32-bit ARM
    The panel maps GOARCH=arm to "arm32" and launches bin/xray-linux-arm32,
    but install.sh/update.sh renamed the release tarball's binary
    (xray-linux-armv5/v6/v7) to xray-linux-arm. On armv7 boxes every update
    downloaded a fresh Xray core into a name the panel never executes, so an
    old correctly-named binary kept running forever, and a brand-new install
    had no launchable Xray binary at all. Rename to arm32 to match the panel
    (mtg stays plain "arm", matching internal/mtproto), and drop the stale
    misnamed xray-linux-arm during updates like the existing amd64 cleanup.
    
    Closes #5788
  • fix(script): make local PostgreSQL and fail2ban setup work on RHEL-family distros
    Fresh installs on Rocky/Alma/RHEL/Oracle failed twice (#5806):
    
    - postgresql-setup --initdb ships a pg_hba.conf whose TCP rules use ident
      auth, which matches the OS username against the Postgres role and always
      rejects the randomly generated panel role, so the panel could never
      connect ("Ident authentication failed"). Prepend password-auth rules
      scoped to the panel database (first match wins; md5 also accepts
      scram-stored verifiers) and reload, in both install.sh and the x-ui.sh
      mirror.
    
    - fail2ban only exists in EPEL on the RHEL family, but only the CentOS 7
      branch enabled EPEL, so IP Limit setup failed with "No match for
      argument: fail2ban". Enable epel-release (with the dl.fedoraproject.org
      package as fallback for RHEL proper) before installing; Fedora ships
      fail2ban in its own repos and is skipped.
    
    Closes #5806
  • fix(script): stop running full system upgrades via pacman -Syu on Arch
    Installing or updating the panel on Arch/Manjaro/Parch performed a full
    system upgrade (pacman -Syu) instead of only refreshing the package
    database and installing the needed packages, unlike every other distro
    branch (apt-get update, dnf makecache, zypper refresh, apk update).
    Unrequested full upgrades can pull in kernel and system updates the
    user never asked for. Align all pacman calls on the -Sy --noconfirm
    form already used elsewhere in these scripts.
    
    Closes #5810
  • 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(script): correct hardcoded menu option numbers in x-ui.sh (#5787)
    * fix(script): correct hardcoded menu option numbers in x-ui.sh
    
    The error messages referenced option 19 for SSL Certificate Management
    and option 16 for Logs Management, but the actual positions in show_menu
    are 20 and 17 respectively.
    
    * Update x-ui.sh
  • fix(ci): pin the tag smoke test to the release under test
    The v3.4.2 tag push triggered the smoke workflow immediately, but
    install.sh with no arguments resolves releases/latest, which still pointed
    at v3.4.1 while release.yml was uploading the new assets. The green smoke
    run therefore validated the previous release (#5756). A paths filter alone
    cannot exclude tag pushes because a brand-new tag ref has no diff base.
    
    Restrict the push trigger to branches so tag pushes no longer start the
    unpinned job, and add a workflow_run job that fires after the release
    workflow completes for a v* tag: it checks out the tagged commit, passes
    the tag through smoke-noninteractive.sh into install.sh's explicit-version
    path, and asserts the installed binary reports exactly that version.
    
    Closes #5756
  • 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(frontend): add text search to the inbound list
    The v2.x panel could filter inbounds but the list page only had the node dropdown. Add a search box next to it matching on remark, port, and protocol, composed with the node filter; the dataset is already client-side, so no API change.
    
    Closes #5267
  • feat(sub): show the announcement on the subscription info page
    The subAnnounce setting was only emitted as a base64 Announce response header, which most client apps ignore and browsers never see. Pass it into the sub page view-model and render it as an info alert at the top of the card; custom themes get the announce key for free.
    
    Closes #5276
  • 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
  • fix(docker): start crond and persist acme.sh state so cert renewal works
    The image shipped busybox crond but the entrypoint never started it, and the acme.sh crontab entry vanished on every container recreation, so certificates issued via the panel's SSL menu silently expired after 90 days. The entrypoint now re-registers the acme.sh cron job and starts crond when acme.sh is installed, and docker-compose gains an acme volume so renewal state survives recreation.
    
    Closes #5116
  • feat(sub): serve the HTML info page for browser requests on JSON and Clash URLs
    Opening the /json or /clash subscription URL in a browser dumped raw JSON/YAML while the base64 URL rendered the info page. Extract the browser-detection and page-rendering branch from subs into maybeServeSubPage and run it first in all three handlers, so every subscription URL shows the same info page in a browser while client apps keep receiving the raw body.
    
    Closes #5348
  • 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
  • feat(frontend): add text search to node select components
    Typing in the Deploy To select of the inbound form and the node filter select on the inbound list now filters nodes by label, matching the showSearch convention used elsewhere (NodeFormModal, HostFormModal). With 20+ nodes, scrolling was the only way to find one.
    
    Closes #5743
  • 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>
  • Env vars example file update (#5678)
    * Update .env.example
    
    * Update .env.example
    
    * Update .env.example
    
    * Update .env.example
  • 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): show client group in the client info modal
    The group label was already on ClientRecord but the info modal never
    displayed it. Add a conditional row next to the comment, rendered as a
    geekblue tag to match the group column in the clients table.
  • 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(frontend): stop group modals clearing selection on background refetch
    The reset effect in GroupAddClientsModal and GroupRemoveClientsModal
    depended on the memoized rows, which are rebuilt whenever GroupsPage
    re-renders because candidates/members are inline-filtered arrays. The
    5s client-list poll re-renders the page, so any selection made in the
    modal was wiped a few seconds later. Reset only when the modal opens.
  • refactor(sub): drop unused subReq parameter from genHy
    genHy reads inbound settings directly via json.Unmarshal and never
    touched subReq; the parameter was only added for signature uniformity
    with genVless/genServer in 7c12700c.
  • chore(deps): bump github.com/klauspost/compress from 1.18.6 to 1.19.0 (#5731)
    Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.18.6 to 1.19.0.
    - [Release notes](https://github.com/klauspost/compress/releases)
    - [Commits](https://github.com/klauspost/compress/compare/v1.18.6...v1.19.0)
    
    ---
    updated-dependencies:
    - dependency-name: github.com/klauspost/compress
      dependency-version: 1.19.0
      dependency-type: direct:production
      update-type: version-update:semver-minor
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • chore(deps): bump github.com/shirou/gopsutil/v4 from 4.26.5 to 4.26.6 (#5730)
    Bumps [github.com/shirou/gopsutil/v4](https://github.com/shirou/gopsutil) from 4.26.5 to 4.26.6.
    - [Release notes](https://github.com/shirou/gopsutil/releases)
    - [Commits](https://github.com/shirou/gopsutil/compare/v4.26.5...v4.26.6)
    
    ---
    updated-dependencies:
    - dependency-name: github.com/shirou/gopsutil/v4
      dependency-version: 4.26.6
      dependency-type: direct:production
      update-type: version-update:semver-patch
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • chore(deps): bump google.golang.org/grpc from 1.81.1 to 1.82.0 (#5729)
    Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.81.1 to 1.82.0.
    - [Release notes](https://github.com/grpc/grpc-go/releases)
    - [Commits](https://github.com/grpc/grpc-go/compare/v1.81.1...v1.82.0)
    
    ---
    updated-dependencies:
    - dependency-name: google.golang.org/grpc
      dependency-version: 1.82.0
      dependency-type: direct:production
      update-type: version-update:semver-minor
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • chore(frontend): bump minor npm deps
    Update frontend dependencies to newer patch/minor versions in package.json and refresh package-lock accordingly. This includes runtime libraries (i18next, react-router-dom, recharts) and tooling updates (typescript-eslint, vite) to keep the frontend stack current and aligned.
  • 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(web): sync the VLESS generate-key dropdown with the encryption field
    The auth-kind dropdown in the VLESS "Generate Key" block was hardcoded to
    x25519 on mount, while the "Already selected" text next to it was derived
    independently from settings.encryption. Editing an inbound whose encryption
    uses another kind (e.g. ML-KEM-768) showed a mismatched dropdown, and
    clicking Generate without noticing would produce a keypair of the wrong
    kind for the inbound.
    
    Extract the encryption-string parsing into a shared pure helper
    (lib/xray/vless-encryption), use it both for the selected-auth label and to
    initialize/sync the dropdown, so the two can no longer diverge. When the
    encryption is none or unparseable the dropdown keeps its x25519 default.
    
    Closes #5744
  • fix(settings): include savePayload in the category body memo deps
    react-hooks/exhaustive-deps flagged the omission; a stale closure could
    hand SecurityTab an outdated save callback after a mutation state change.
  • 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.
  • fix(traffic): disable depleted clients by id instead of a second full scan
    disableInvalidClients evaluated the depleted predicate twice per poll:
    once to SELECT the rows (for xray removal and settings sync) and again in
    the UPDATE that flips enable off — each a full client_traffics scan, the
    second also re-running the cross-panel EXISTS subquery when global rows
    exist.
    
    The UPDATE now flips the already-collected rows by primary key in
    sqlInChunk batches, sorted for stable lock order. Same rows, same
    RowsAffected, half the scan cost; id-based matching also stays correct
    for rows with empty emails.
  • fix(traffic): persist delayed-start expiry only for converted clients
    addClientTraffic's second pass wrote expiry_time for every polled row via
    UPDATE ... WHERE expiry_time < 0 — a no-op statement per active client on
    every 5s poll, since almost all rows carry a positive expiry. At 10k
    active clients that was 10k pointless indexed UPDATEs per poll.
    
    adjustTraffics now returns the emails it actually converted this tick and
    the persistence pass writes exactly those, in sorted order to keep
    concurrent writers lock-compatible on Postgres. Behavior is unchanged:
    unconverted rows never matched the WHERE clause anyway.
  • test(scale): cover traffic poll, ws payloads, ip-limit job, sub and xray config at 500k
    The paths that run continuously in production had no scale coverage: the
    5s traffic poll (AddTraffic with its auto-renew and depleted scans), the
    websocket snapshot the job broadcasts while a browser is connected, the
    10s ip-limit job (hasLimitIp LIKE scan + per-email settings parse), a
    subscription fetch inside a huge inbound, and the full Xray config build.
    
    New benchmarks reuse the XUI_SCALE_TEST / XUI_DB_TYPE gating and stay
    log-only. Sizes default to 10k/100k; XUI_SCALE_SIZES=500000 raises the
    ladder without editing code. seedScaleDataset writes inbounds, clients,
    client_inbounds and client_traffics directly in one transaction instead
    of SyncInbound, so a 500k seed takes seconds. XUI_SCALE_DB_PATH persists
    the seeded SQLite file for manual smoke runs against a live panel.
  • docs: move architecture map into docs/ and refresh it against the live tree
    The architecture/code map previously lived in .claude/CLAUDE.md, which was
    gitignored (local-only) and auto-loaded into every agent session alongside
    the root CLAUDE.md. Track it in docs/architecture.md instead and reference
    it from CLAUDE.md so it is read on demand.
    
    While moving it, fact-check the whole map against the current tree:
    - add the missing internal/eventbus and internal/tunnelmonitor packages,
      the service/email subpackage, and util/wirecodec
    - document node mTLS (tls_client.go, node_mtls.go, setting_mtls.go) and the
      fourth TLS verify mode
    - add the Host, ClientExternalLink, NodeClientIp and ClientGlobalTraffic
      models plus their symptom-index rows
    - correct the cron table (check_cpu_usage is 1m not 10s; add
      check_memory_usage and free_os_memory), the middleware chain
      (MaxBodyBytes, ConfigEnvelope, CSRF) and the controller route prefixes
    - refresh the sub/ and service/ file listings, frontend pages (hosts/,
      index/), CI workflow list, and replace stale exact line counts with
      rounded sizes
  • feat(settings): let users clear stored secrets from the UI
    Redacted secrets (SMTP password, Telegram bot token, LDAP password) are
    always served blank to the browser, so the update path treats a blank
    submission as "unchanged" and silently restores the stored value. That
    made a once-set secret impossible to remove without editing the database
    — e.g. switching to a passwordless localhost SMTP relay kept sending the
    old credentials forever.
    
    Blank stays "unchanged"; clearing is now its own signal. The update
    request carries explicit clear flags (request-scoped fields on the
    controller form, so they are never persisted as settings rows), and
    preserveRedactedSecrets skips the restore for a flagged secret. Each
    secret field gets a Clear/Undo button that arms the flag; typing a new
    value disarms it. The 2FA token keeps its existing behavior: it is
    already clearable by disabling 2FA.
    
    Closes #5724
  • fix(sub): default https:// for scheme-less support and profile URLs
    A support URL saved without a scheme (e.g. "t.me/handle") is served
    verbatim in the subscription Support-Url header and page data, and client
    apps resolve it relative to the subscription domain — clicking it lands
    on "https://panel.example/t.me/handle". Same hazard for the profile URL.
    
    Default the scheme to https:// when none is present, both when saving the
    settings and when reading already-stored values, so existing databases are
    covered without a migration. Deliberate non-http schemes (tg://, mailto:,
    tel:) pass through untouched, which is why these two fields don't go
    through SanitizeHTTPURL's http(s)-only validation.
    
    Closes #5738
  • fix(settings): repair legacy path settings that block every settings save
    A subJsonPath (or subPath/subClashPath/webBasePath) stored without its
    leading/trailing slash — written before the slash rules existed, or
    restored from an old backup — fails the frontend's whole-form validation,
    so every save on the Settings page is rejected client-side. The backend's
    CheckValid would normalize the value, but a save request never reaches it,
    leaving the panel wedged until someone edits the database by hand.
    
    Normalize the stored path rows at startup, mirroring CheckValid's slash
    rules. The pass is idempotent and not seeder-gated, since a restored
    backup can reintroduce bad values at any time.
    
    Also add the missing pages.settings.validation.pathLeadingSlash key to
    all 13 locales — the validation error used to render as its raw key.
    
    Closes #5726
  • fix(node): stop Postgres deadlocks and deleted-client resurrection in node sync
    Two defects in the node traffic sync, both hit hard on busy
    master+multi-node Postgres deployments:
    
    Client-IP merges deadlocked. Each node syncs on its own goroutine and
    shared clients appear in several nodes' reports, but MergeInboundClientIps
    and upsertNodeClientIps locked rows in whatever order each node's report
    arrived. Two concurrent merges taking the same rows in opposite order is
    exactly what Postgres aborts with SQLSTATE 40P01 ("merge client ips from
    <node> failed: deadlock detected"). Both merges now process emails in
    sorted order so every transaction acquires row locks in one global order.
    
    Deleted clients resurrected with zeroed traffic. A snapshot fetched just
    before a deletion still names the deleted email; applying it after the
    delete committed re-added the client. The delete tombstone existed for
    precisely this race but only zeroed the seed counters: the sync still
    recreated the client_traffics row, and worse, adopted the node's stale
    settings JSON wholesale, putting the client back in the central inbound
    as if it were brand new with 0 traffic. Snapshot application now skips
    row creation for tombstoned emails on known inbounds and strips
    tombstoned clients from adopted settings; fresh node-adoption semantics
    (rows seeded at zero) are unchanged.
    
    The mass-disconnect part of the report is the forced node restart on
    auto-disable, removed separately in 4d6f2ddd.
    
    Closes #5739
  • fix(node): stop force-restarting a node's Xray when its clients auto-disable
    When a depleted or expired client lived on a node, the master pushed the
    updated inbound (client flipped off) to the node and then also told the
    node to fully restart Xray. The push alone already applies the disable:
    the node updates that one inbound on its running core. The extra restart
    dropped every live connection on the node each time any of its clients
    crossed a quota or expiry, and a restart that failed to come back left
    the node forwarding nothing until someone restarted Xray by hand.
    
    This mirrors e5b56c94, which removed the same forced restart from the
    local auto-disable path; remote nodes now get the same graceful
    reconcile-by-push treatment.
    
    Closes #5740