Commit Graph
140 Commits
  • fix(install): preserve custom bin/ files (e.g. hand-added geoip) across updates (#6152)
    * fix(install): preserve custom bin/ files (e.g. hand-added geoip) across updates
    
    Every reinstall/update wipes /usr/local/x-ui/ wholesale and re-extracts
    the release tarball, which only ships known assets (xray/mtg binaries,
    the bundled geoip*/geosite*.dat sets). A user-reported real incident:
    a hand-placed custom geoip file referenced from a routing rule via
    "ext:<file>:<code>" got silently deleted on update, and Xray refused
    to start at all afterward ("failed to open <file>: no such file or
    directory"), taking down every inbound until the file was manually
    restored from the user's own backup.
    
    install_x-ui now backs up the old bin/ before the wipe and restores,
    after extraction, only the files the fresh release doesn't provide --
    bundled assets still get the newer per-release copy, nothing custom
    silently disappears. Verified in isolation: standard files (geoip.dat,
    the xray binary) end up as the fresh release's copy; a custom file
    absent from the release survives untouched.
    
    Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
    
    * fix: harden the bin/ snapshot-and-restore against the review round on #6152
    
    - Replace the mktemp+cp snapshot with a same-filesystem mv of bin/ aside:
      an unchecked mktemp failure previously made the very next line copy
      bin/'s contents into "/" (empty custom_bin_backup + trailing slash),
      and a silently-ignored cp failure (stderr redirected, exit code never
      checked) could leave a truncated custom geo file that gets "restored"
      as if it were intact. A rename is atomic and needs no extra disk space,
      removing both failure modes at once; if it fails, back off cleanly and
      say so instead of proceeding as if a backup exists.
    - Add a trap so an interrupted update (Ctrl-C, signal) between the
      backup and the restore doesn't leave the snapshot (which contains
      bin/config.json and every mtproto client's FakeTLS secret) sitting
      around indefinitely; the two exit-path cleanups this replaces are gone
      since the trap now covers those exits too.
    - Move the restore below the arm arch-rename/chmod block instead of
      before it, so xray-linux-arm32/mtg-linux-arm already exist under their
      final names and don't get needlessly restored-then-overwritten and
      misreported as "custom".
    - Exclude bin/config.json and bin/mtproto/*.toml from the restore: those
      are the panel's own generated runtime state (internal/xray/process.go,
      internal/mtproto/manager.go), not admin-placed files, and restoring a
      stale one only resurrects dead state or recreates bin/mtproto/ with the
      wrong (more permissive) directory mode.
    - Match symlinks in the restore's find, not just plain files -- cp -a
      already preserves them in the snapshot, but the restore loop was
      silently dropping them, which is exactly the failure mode (a geo file
      symlinked in from elsewhere) this PR set out to fix.
    - Quote the two new xui_folder expansions.
    - Extend the non-interactive smoke test to reinstall over an existing
      install with a sentinel file in bin/, asserting it survives and that
      the bundled geoip.dat is still the release's own copy -- the update
      path this PR touches had no CI coverage at all before this.
    
    Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
  • fix (install.sh): use realpath instead of script name (#6075)
    * fix (install.sh): use realpath instead of script name
    
    ###Description:
    During arch() sctipt tries to delete itself in case no compatible arch found. This may lead to unexpected file deletion if executed outside root dir; also cur_dir is declared but doesn't seem to be used anywhere
    
    ###Way to reproduce:
    ```bash
    cd "/some/other_dir_with_install_sh"
    /3x-ui/project/dir/install.sh
    ```
    
    * fix(install): quote the script path before the self-delete
    
    realpath was handed an unquoted $0, so a script living under a path that
    contains spaces was split into several arguments: realpath printed a
    partial path plus an error, and rm -f then targeted a name matching
    nothing at all. The unsupported-arch branch silently kept the script it
    means to remove — the very case the surrounding fix exists for.
  • fix(script): remove release download time limit (#5952)
    * fix(script): remove release download time limit
    
    * fix(script): stop stalled release downloads
    
    ---------
    
    Co-authored-by: sanmaxdev <sanmaxdev@users.noreply.github.com>
  • fix(script): confirm auto-detected public IPv4 before issuing IP certificate
    On networks with asymmetric routing (or proxies/multi-WAN), external
    IP-echo services can return a transit or gateway address instead of the
    server's real incoming IP, and every IP-certificate flow silently
    issued for that wrong address. The x-ui.sh menu flow (option 20 -> 6)
    and the install.sh/update.sh SSL menus now show the detected IPv4 for
    confirmation (Enter keeps the old behavior), and declining falls into
    the same validated manual-entry loop already used when every provider
    fails. Non-interactive installs are untouched - XUI_SERVER_IP already
    pins the address there.
    
    Closes #5867
  • fix(script): stop logging an error when Enter accepts the default ACME port
    Pressing Enter at the 'Please choose which port to use (default is 80)' prompt left WebPort empty, and bash arithmetic treats an empty string as 0, so the out-of-range branch fired and printed 'Your input is invalid' even though the default was correctly applied. Handle empty input as accepting the default silently, and validate real input with a digits-only regex so non-numeric entries like '8x' get the invalid-input message instead of a bash arithmetic error. Applied to the identical prompt in x-ui.sh, install.sh, and update.sh.
    
    Fixes #5829
  • 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: 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(scripts): pass --force to acme.sh --installcert so it survives sudo
    acme.sh guards every non-install command behind _checkSudo: when a
    non-root user runs the panel scripts via sudo, it prints the sudo wiki
    warning and exits before doing anything, unless FORCE is set. All our
    --issue calls already pass --force and were unaffected, but none of the
    --installcert calls did, so issuance succeeded and installation then
    aborted silently, ending in "Certificate files not found after
    installation". FORCE has no other effect on the installcert path, so
    mirror the --issue calls and pass --force everywhere we install certs.
    
    Closes #5741
  • feat(install): add dev-latest install option and sync README translations
    install.sh now accepts `dev-latest` (or `dev`) to install the rolling per-commit dev pre-release, bypassing the numeric version-floor check.
    
    README.md documents the version-pinned and dev-latest install commands. All six language READMEs are brought back in sync with the English source: the new install instructions plus the previously-missing "Unattended install & cloud images" section, the XUI_TUNNEL_HEALTH_* env vars, and the custom subscription templates link.
  • feat(iplimit): auto-install fail2ban on install and update
    IP limit enforcement is gated on fail2ban being present (ce8b1bed), but the bare-metal install.sh/update.sh never installed it, so the feature stayed disabled until the user ran the IP Limit menu by hand. Docker already auto-configures it; bare-metal hosts did not.
    
    Extract the fail2ban install + jail setup out of install_iplimit into a non-interactive setup_fail2ban_iplimit() (no exit/before_show_menu, returns a status) exposed via 'x-ui setup-fail2ban', and call it from install.sh and update.sh after the panel is up. update.sh is the primary update path (x-ui update and the panel self-updater both run it). Honors XUI_ENABLE_FAIL2BAN (proceed only when unset or true, matching the Go gate) and is non-fatal so a fail2ban failure never aborts the install/update.
  • fix(install): support IPv6-only hosts (#5487)
    * fix(install): support IPv6-only hosts
    
    * fixup: complete IPv6-only install and update support
    
    * fixup: remove no-op download retries
  • ci(smoke): retry transient GitHub download failures
    The first-boot smoke test and install.sh fetched the released binary with
    a single curl attempt, so a transient GitHub/CDN 504 failed the whole job.
    
    - smoke-firstboot.sh: add --retry/--retry-all-errors with connect/max
      timeouts to the version API and tarball downloads, split the download
      into a guarded step, and assert the tarball is non-empty.
    - install.sh: add --retry plus connect/max timeouts to the release-binary
      downloads and version lookups. Omit --retry-all-errors here for curl
      < 7.71 (Ubuntu 20.04 / Debian 10 / CentOS 7) compatibility; plain
      --retry already covers 504 and other transient errors.
  • feat: release-driven golden-image & unattended-install deployment pipeline (#5323)
    * feat(install): add non-interactive install path for cloud/golden-image use
    
    Trigger non-interactive mode when XUI_NONINTERACTIVE=1 or stdin is not a
    TTY (curl | bash, cloud-init). Every prompt is then replaced by an env var
    or a sane default; interactive prompts stay byte-for-byte identical.
    
    Honored env vars: XUI_USERNAME, XUI_PASSWORD, XUI_PANEL_PORT,
    XUI_WEB_BASE_PATH (unset => random, as before), XUI_SSL_MODE=none|ip|domain
    (default none), XUI_DOMAIN, XUI_ACME_EMAIL, XUI_DB_TYPE/XUI_DB_DSN, plus
    additive XUI_ACME_HTTP_PORT, XUI_SSL_IPV6, XUI_SERVER_IP.
    
    On success, write /etc/x-ui/install-result.env (mode 600) with the panel
    creds + access URL + api token, in both interactive and non-interactive
    modes, so cloud-init/MOTD can surface them. Postgres in non-interactive
    mode requires XUI_DB_DSN or installs locally; never silently downgrades.
    
    * feat(deploy): add first-boot per-instance credential generation
    
    Golden images ship with no x-ui.db. x-ui-firstboot.sh runs once (guarded by
    /etc/x-ui/.firstboot-done), before x-ui.service, and replaces the seeded
    admin/admin with fresh random username/password on a random high port,
    regenerates the session secret/panel GUID via 'x-ui setting -reset', mints an
    API token, and writes the creds to /etc/x-ui/credentials.txt (600) + /etc/motd.
    
    Idempotent: skips regeneration if a non-default admin already exists. The
    oneshot unit is ordered After=network-online/cloud-init and Before=x-ui.service
    so the panel never serves default credentials.
    
    * chore(deploy): force LF for cloud-image deploy assets (.service/.hcl/.yaml)
    
    * feat(deploy): add Packer config + provisioning scripts for golden image
    
    One build, two sources: amazon-ebs (AWS AMI, Canonical Ubuntu 24.04 base via
    source_ami_filter) and qemu (qcow2 + raw, NoCloud-seeded for build-time SSH).
    Provisioner order is fixed: provision.sh -> harden.sh -> cleanup.sh.
    
    - provision.sh: downloads the released x-ui tarball (no Go build), installs the
      panel + firstboot unit, enables but does NOT start services, creates NO DB.
    - harden.sh: key-only SSH, no root password login, locks default account
      passwords, enables unattended-upgrades (scanner-compliant).
    - cleanup.sh: wipes any DB/creds, SSH host keys, authorized_keys, machine-id,
      cloud-init state, logs and history; fails the build if any secret survives.
    
    packer fmt -check clean; packer validate passes for both sources.
    
    * feat(deploy): add generic cloud-init user-data for unattended install
    
    cloud-init.yaml installs the latest 3x-ui non-interactively (XUI_NONINTERACTIVE=1)
    on any cloud-init platform, generating unique per-instance credentials and
    surfacing them via /etc/x-ui/install-result.env, serial console and MOTD.
    README documents per-provider usage (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
    and all XUI_* knobs.
    
    * ci: add image.yml to build cloud images on release
    
    On release: published (or workflow_dispatch with a tag), waits for the
    x-ui-linux-amd64.tar.gz asset (handles the release-matrix upload race), then:
    - qemu-image (always): builds the qcow2 with Packer and attaches a compressed
      .qcow2.xz + sha256 to the GitHub release. Uses KVM when /dev/kvm exists,
      else TCG.
    - ami-image (gated): builds the AWS AMI only when AWS creds exist (OIDC role
      preferred, else access keys), so forks skip cleanly. Prints the AMI ID to the
      job summary. No secrets or AMI IDs are committed.
    
    * test(deploy): add container smoke tests for install + firstboot
    
    smoke-noninteractive.sh: runs install.sh piped (no TTY) with
    XUI_NONINTERACTIVE=1 in an Ubuntu container; asserts install-result.env (600)
    holds random non-default creds, hasDefaultCredential is false, and the panel
    serves HTTP.
    
    smoke-firstboot.sh: installs the released binary with no DB, runs
    x-ui-firstboot.sh; asserts per-instance creds + credentials.txt (600) + MOTD,
    no admin/admin, and that a second run is a no-op (sentinel honored).
    
    smoke.yml runs both as gated jobs on PRs/pushes touching install.sh or deploy/**.
    Both pass locally against the v3.3.1 release binary.
    
    * docs(deploy): add Packer/marketplace docs and link from README
    
    - deploy/README.md: index of the cloud-deploy tooling and the two models
    - deploy/packer/README.md: how to build locally, variables, first-boot behavior
    - deploy/marketplace/aws/README.md: seller registration -> AMI scan ->
      limited-visibility preview -> go-public checklist
    - deploy/marketplace/hetzner/README.md: cloud-init-first guidance + snapshot
      caveat (delete x-ui.db first) + hetznercloud/apps reference
    - README.md: link the unattended-install / cloud-image docs from Quick Start
    
    * feat(deploy): build golden images for arm64 as well as amd64
    
    The install path was already multi-arch (install.sh auto-detects arch); this
    extends the golden image + CI to arm64:
    
    - packer: xui_arch (amd64|arm64, validated) now derives the base AMI filter and
      the Ubuntu cloud image; the qemu source switches to qemu-system-aarch64 + virt
      machine + AAVMF UEFI firmware for arm64. amd64 path unchanged.
    - image.yml: arch matrix. AMIs for amd64 (t3.small) + arm64 (t4g.small/Graviton)
      from one runner; qcow2 for amd64 on a standard runner and arm64 on a native
      ubuntu-24.04-arm runner. Waits for both release tarballs.
    - smoke.yml: run install + firstboot smoke tests on amd64 and arm64 runners;
      smoke-firstboot.sh now resolves the arch tarball via dpkg.
    - docs updated for both arches.
    
    packer fmt/validate pass for amd64 and arm64; actionlint + shellcheck clean.
    Verified locally: non-interactive install AND firstboot run on the real arm64
    release binary under emulation (ELF aarch64, no admin/admin).
    
    * chore(deploy): default AWS region to eu-central-1 (Frankfurt)
    
    Replace the us-east-1 fallback in image.yml (4 sites) and the Packer 'region'
    default + doc examples. Still overridable via the AWS_REGION repo variable / the
    -var 'region=...' flag.
    
    * feat(deploy): add Amazon Lightsail support (launch script + snapshot builder)
    
    Lightsail can't launch from an EC2 AMI and its blueprint list isn't
    self-publishable, so add the two self-service paths instead:
    
    - launch-script.sh: paste into Lightsail 'Add launch script' (or --user-data) to
      install 3x-ui non-interactively with unique per-instance credentials.
    - snapshot-userdata.sh + build-snapshot.sh: AWS CLI pipeline that provisions a
      build instance (panel installed, NO DB, firstboot enabled), runs the shared
      cleanup.sh, then snapshots it. Instances launched from the snapshot mint their
      own credentials on first boot. Optional --panel-port pins a known port for the
      Lightsail firewall.
    - README documents both paths, the firewall caveat, and the blueprint reality.
    
    EC2 AMI / Marketplace path kept untouched alongside. All scripts shellcheck-clean.
    
    * fix(deploy): address Copilot PR review findings
    
    - install.sh + firstboot: write install-result.env / credentials.txt values with
      printf %q so the files stay safe to source even if creds are pinned with shell
      metacharacters (no-op for the alphanumeric random defaults).
    - firstboot: fail closed if 'x-ui setting -show' can't be parsed to true/false —
      exit without writing the sentinel so the next boot retries, instead of silently
      skipping regeneration and risking admin/admin.
    - firstboot + cloud-init + lightsail launch-script: keep secrets out of the
      world-readable /etc/motd (show URL + username only; full creds via the mode-600
      file / serial console).
    - lightsail build-snapshot: handle download-default-key-pair returning either a
      PEM or base64, and assert a valid PEM before using it for SSH.
    - image.yml: pin hashicorp/setup-packer@v3 (was @main).
    - deploy/README: document XUI_ACME_HTTP_PORT / XUI_SSL_IPV6 / XUI_SERVER_IP.
    
    Both container smoke tests still pass; shellcheck + actionlint clean.
  • fix(script): SSL management fixes (#4994, #5010, #5070)
    - Issue acme.sh HTTP-01 over IPv4 unless the host has no global IPv4
      address: the hardcoded --listen-v6 started a v6-only standalone
      listener, so validation of a domain whose A record points at this
      host always failed (#4994).
    - Add a custom cert/key path option to the "Set Cert paths" menu so
      certificates living outside /root/cert (e.g. certbot under
      /etc/letsencrypt) can be wired to the panel from the CLI (#5010).
    - Derive the displayed Access URL from the certificate's actual SAN
      list instead of the cert folder name, list the other covered names,
      and show the panel's custom-path certificate in "Show Existing
      Domains" (#5070). Also silence find when /root/cert doesn't exist.
  • fix(mtproto): reap orphaned mtg, fix SysLog viewer, mtg log visibility, export remark (#5105) (#5107)
    * fix(logs): render journalctl output in the SysLog viewer
    
    The log viewer's parseLogLine only understood the app-log format
    (2006/01/02 15:04:05 LEVEL - body). With SysLog ticked the backend
    returns journalctl lines (Mon DD HH:MM:SS host ident[pid]: LEVEL - body),
    so the parser mistook the journal time for the level and dropped the
    body, leaving only timestamps. Detect and strip the journald prefix,
    keep the journal timestamp as the stamp, then parse the real level and
    body from the remainder.
    
    * feat(mtproto): surface mtg output and add status reporting
    
    mtg's stdout/stderr was captured by a writer that kept only the last
    line and showed it nowhere, so the reason a proxy could not reach
    Telegram was invisible. Stream mtg output line-by-line into the x-ui
    log, tagged per inbound, so it appears in the panel log viewer and
    journald.
    
    Also fix mangled log lines: logger.Info uses fmt.Sprint, which drops
    the space between adjacent string operands, producing output like
    'inbound3on0.0.0.0:8443'. Switch the affected mtproto calls to the
    formatted (*f) variants.
    
    Add show_mtproto_status to x-ui.sh so 'x-ui status' reports each
    mtproto inbound's mtg process state and bind address.
    
    * fix(logs): parse all journalctl message shapes in SysLog viewer
    
    Real journalctl output mixes four message shapes after the
    'Mon DD HH:MM:SS host ident[pid]:' prefix: go-logging 'LEVEL - msg'
    (x-ui/xray), Go std-log with an embedded date (net/http, runtime),
    telego's '[timestamp] LEVEL msg', and systemd lines. The viewer only
    understood the first, so std-log and telego lines — which never contain
    ' - ' — collapsed to a bare timestamp (e.g. the 8s telego 409 spam).
    
    Extract the parser into a pure, testable module and teach it the other
    shapes: strip the redundant Go std-log date, lift the level out of
    telego brackets, and always keep the message body. Add a unit test
    covering each shape with real captured lines.
    
    * fix(mtproto): reap orphaned mtg sidecars so a stale one can't break new clients
    
    On Linux x-ui does not kill its mtg children when it dies (no kill-on-exit,
    unlike the Windows job object). After a crash, OOM, kill -9, or update, a
    stale mtg keeps holding the inbound port with an OLD secret, so new clients
    fail the FakeTLS handshake and get silently domain-fronted to the fakeTLS
    domain instead of proxied to Telegram (a few MB of traffic, never connects).
    
    Sweep orphans at startup: on the first reconcile, before x-ui starts any of
    its own mtg, scan /proc and SIGKILL any process whose executable is our
    mtg-<goos>-<goarch> binary. x-ui is the sole owner of mtg, so anything alive
    then is an orphan. Runs once per process (swept guard), survives the
    binary-deleted-during-update case via /proc/<pid>/cmdline, and is a no-op on
    Windows (job object) and other platforms.
    
    Also clear stray mtg in update.sh/install.sh after stopping x-ui, anchored to
    the 'mtg-linux-<arch> run ' invocation so the pattern can't match unrelated
    command lines (e.g. x-ui.sh's own 'grep mtg-linux').
    
    * fix(logs): drop dead body initializer flagged by eslint no-useless-assignment
    
    * fix(mtproto): drop remark fragment from tg://proxy export link
    
    The mtproto export link appended the inbound remark as a URL fragment
    (tg://proxy?server=...&port=...&secret=...#remark). Telegram Desktop
    rejects a proxy deep link with a trailing fragment as 'This proxy link
    is invalid', breaking one-click import, and a remark is meaningless for
    proxy links across clients. Stop adding it in both the panel link
    (genMtprotoLink) and the subscription service. Fixes #5105.
    
    * fix(x-ui.sh): remove unused check_mtproto_status helper
    
    show_mtproto_status does its own process check, so check_mtproto_status
    was dead code. Drop it (per Copilot review on #5107).
  • feat(mtproto): add MTProto (FakeTLS) protocol via managed mtg sidecar (#5076)
    * feat(mtproto): add MTProto (FakeTLS) protocol via managed mtg sidecar
    
    Xray-core has no mtproto proxy, so mtproto inbounds run as standalone
    mtg (9seconds/mtg) sidecar processes managed by the panel — one per
    inbound — and are excluded from the generated Xray config entirely.
    
    - model: MTProto protocol constant, validator, and FakeTLS secret
      helpers (GenerateFakeTLSSecret/HealMtprotoSecret)
    - mtproto package: per-inbound mtg process manager with reconcile,
      graceful stop, and best-effort Prometheus traffic scraping
    - runtime: delegate mtproto inbounds to the mtg manager instead of the
      Xray gRPC API; skip mtproto when building the Xray config
    - web: boot reconcile + StopAll wiring, periodic reconcile/traffic job,
      port-conflict transport, secret healing on inbound add/update
    - sub: tg:// proxy share-link generation
    - frontend: protocol option, Zod schema, Protocol tab (FakeTLS domain +
      regenerable secret), info-modal link, and i18n
    - provisioning: fetch mtg v2.2.8 in install.sh, DockerInit.sh, and the
      Linux + Windows release workflows
    
    * fix
    
    * fix
    
    * fix: address Copilot review comments on mtproto PR
    
    - web/web.go: create NewMtprotoJob once and reuse for cron + initial run
    - mtproto/manager.go: StopAll cleans up per-inbound config files on shutdown
    - mtproto/manager.go: CollectTraffic releases mutex before HTTP scrapes to
      avoid blocking Ensure/Reconcile/Remove during network I/O
    - database/model/model.go: panic on crypto/rand failure in mtprotoRandomMiddle
      instead of silently producing a weak all-zero secret
    - install.sh: fix chmod to handle renamed bin/mtg-linux-arm on armv5/v6/v7
  • fix(ssl): clean ECC state, guard cert reuse, register renew hook (#4875)
    - Cleanup on issuance/install failure now also removes the acme.sh
      ${domain}_ecc (and ${ip}_ecc) directory, not just ${domain}, so a
      failed run no longer leaves partial state behind.
    - The 'existing certificate' check only reuses a cert when its
      fullchain.cer and key files are actually present and non-empty;
      otherwise the broken state is removed and issuance proceeds. This
      fixes the 0-byte fullchain.pem produced by reusing failed state.
    - Menu option 5 (set cert paths) now registers the acme.sh --installcert
      hook with --reloadcmd 'x-ui restart' when acme.sh knows the domain, so
      auto-renewal copies the renewed cert and reloads the panel.
  • feat(postgres): in-panel backup/restore and consistent CLI backend
    Two PostgreSQL gaps on the panel:
    
    1. x-ui setting and other CLI subcommands read XUI_DB_TYPE/XUI_DB_DSN from
       the process environment, which systemd injects via EnvironmentFile but a
       plain shell invocation does not. On a PostgreSQL install the CLI silently
       fell back to SQLite, so changes made from the management menu never
       reached the panel's database. Load the systemd EnvironmentFile
       (/etc/default/x-ui and distro equivalents) at startup; godotenv.Load does
       not override existing vars, so it stays a no-op for the managed service.
    
    2. DB backup/restore (panel endpoints and the Telegram bot) only handled the
       SQLite file, so on PostgreSQL Back Up returned a stale/absent x-ui.db and
       Restore silently did nothing. Add pg_dump/pg_restore based backup/restore:
       - GetDb/ImportDB run pg_dump (custom format) / pg_restore, passing
         credentials via the PG* environment instead of argv.
       - getDb downloads x-ui.dump on Postgres, x-ui.db on SQLite.
       - Telegram backup sends the matching file via GetDb.
       - BackupModal shows a Postgres note and accepts .dump; the dist page
         injects window.X_UI_DB_TYPE; new strings translated for all locales.
       - install.sh installs postgresql-client for the external-DSN path and
         points the user to in-panel Backup & Restore.
    
    Closes #4658
  • Random PostgreSQL role + post-install credentials display (#4608)
    * feat(install): random PostgreSQL role + post-install credentials display
    
    The local-Postgres installer used to bake in a static role name (`xui`)
    and only printed `PostgreSQL (xui@127.0.0.1:5432/xui)` at the end of
    install, leaving operators without the random password or any hint of
    how to connect from the shell.
    
    Two changes:
    
    - install_postgres_local now generates an 8-char random role name
      alongside the random password, and double-quotes identifiers in the
      CREATE/ALTER statements (a random alphanumeric may start with a digit,
      which Postgres rejects for unquoted identifiers).
    
    - After a successful local install, a dedicated "PostgreSQL Credentials"
      block is rendered in the summary — DB / user / pass / host / port /
      DSN / env-file path, plus ready-to-paste psql commands for both the
      postgres superuser and the new role. Credentials cross the subshell
      boundary via a 0600 tmpfile (PG_CRED_FILE) that the parent shell
      sources and unlinks; the PG_* vars are unset after display.
    
    Only fires for the local-install flow; the external-DSN path is
    unchanged.
    
    * fix(install): address Copilot review on Postgres install flow
    
    - Use mktemp (unguessable, 0600) instead of /tmp/x-ui-pg-creds.$$ and
      cleanup in both success and failure paths to close the symlink/race
      attack on the predictable filename.
    - In install_postgres_local, capture the prior umask and restore it
      after writing PG_CRED_FILE; return 1 if the write fails so the
      caller does not source nothing and label the install with empty
      PG_* vars.
    - On reinstall, reuse the existing xui DB owner instead of generating
      a fresh role each run, so existing tables stay accessible after a
      re-run; only the password is rotated. Falls back to a fresh random
      role when the DB does not exist or is owned by postgres.
  • feat(bash): prompt for PostgreSQL (#4472)
    * feat(install): prompt for SQLite vs PostgreSQL during install
    
    * fix(install): write env file to per-distro path and handle pg-install failure
    
    The env file was hardcoded to /etc/default/x-ui, but RHEL/Fedora units read
    /etc/sysconfig/x-ui, Arch reads /etc/conf.d/x-ui, and Alpine OpenRC auto-
    sources /etc/conf.d/x-ui. PostgreSQL selection was silently dropped on every
    distro except Debian. Also initdb on openSUSE (service wouldn't start) and
    prompt the operator on local-install failure instead of silently demoting
    to SQLite.
    
    * fix(scripts): make x-ui.sh and update.sh PostgreSQL-aware
    
    update.sh ran setting -show and migrate without sourcing the env file, so
    PostgreSQL users had migrations applied to the SQLite default and settings
    introspection read the wrong DB. Sourcing the per-distro env file at the
    start of update_x-ui exports XUI_DB_TYPE/XUI_DB_DSN to all binary calls.
    
    x-ui.sh now shows the active backend in View Current Settings (password
    masked) and removes the env file on uninstall so a later reinstall doesn't
    inherit a stale DSN.
  • Feat/multi inbound clients (#4469)
    * feat(clients): add shadow tables for first-class client promotion
    
    Introduces three new GORM-backed tables (clients, client_inbounds,
    inbound_fallback_children) and a populate-only seeder that backfills
    them from each inbound's existing settings.clients JSON. Duplicate
    emails across inbounds auto-merge under one client row, with each
    field conflict logged. Existing services are unchanged and continue
    reading from settings.clients — this commit is groundwork only.
    
    * feat(clients): make clients+client_inbounds the runtime source of truth
    
    Adds ClientService.SyncInbound that reconciles the new tables from
    each inbound's clients list whenever existing service paths mutate
    settings.clients. Wires it into AddInbound, UpdateInbound,
    AddInboundClient, UpdateInboundClient, DelInboundClient,
    DelInboundClientByEmail, DelDepletedClients, autoRenewClients, and
    the timestamp-backfill path in adjustTraffics, plus DetachInbound
    on DelInbound.
    
    GetXrayConfig now builds settings.clients from the new tables before
    writing config.json, and getInboundsBySubId joins through them
    instead of JSON_EACH on settings JSON. Live Xray config and
    subscription endpoints are now driven by the relational view;
    settings.clients JSON stays in step as a side effect of every write.
    
    * feat(clients): add top-level Clients tab and CRUD API
    
    Adds /panel/api/clients endpoints (list, get, add, update, del,
    attach, detach) backed by ClientService methods that orchestrate
    the per-inbound Add/Update/Del flows so a single client row is
    created once and attached to many inbounds in one operation.
    
    The frontend gains a dedicated Clients page (frontend/clients.html
    + src/pages/clients/) with an AntD table, multi-inbound attach
    modal, and full CRUD. Axios interceptor learns to honour
    Content-Type: application/json so the JSON endpoints work
    alongside the legacy form-encoded ones.
    
    The legacy per-inbound client modal stays untouched in this PR —
    both flows now write to the same source of truth.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(inbounds): add Port-with-Fallback inbound type
    
    Adds a new "portfallback" protocol that emits as a VLESS-TLS inbound
    under the hood but is paired with a sidecar table of child inbounds.
    Panel auto-builds settings.fallbacks at Xray-config-gen time from the
    sidecar — each child's listen+port becomes the fallback dest, with
    SNI/ALPN/path/xver match criteria pulled from the row. No more typing
    loopback ports by hand or keeping settings.fallbacks in sync.
    
    Backend: new FallbackService (Get/SetChildren, BuildFallbacksJSON);
    two new routes (GET/POST /panel/api/inbounds/:id/fallbackChildren);
    xray.GetXrayConfig injects fallbacks for PortFallback inbounds; the
    inbound model emits protocol="vless" so Xray accepts the config.
    
    Frontend: PORTFALLBACK joins the protocol dropdown; selecting it
    shows the standard VLESS controls plus a Fallback Children table
    (inbound picker + per-row SNI/ALPN/path/xver). Children are loaded
    on edit and replaced atomically on save.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): add Reset Traffic, QR Code, Info actions + Online/Remaining columns
    
    The Clients page table gains:
    - Online column — green/grey tag driven by /panel/api/inbounds/onlines,
      polled every 10s.
    - Remaining column — bytes-remaining tag, coloured green/orange/red
      against quota, purple infinity when unlimited.
    - Action icons per row: QR, Info, Reset traffic, Edit, Delete.
    
    ClientInfoModal shows the full client detail (uuid/password/auth,
    traffic ↑/↓ + remaining + all-time, expiry absolute + relative,
    attached inbounds chip list, online + last-online).
    
    ClientQrModal fetches links for the client's subId via
    /panel/api/inbounds/getSubLinks/:subId and renders each one through
    the existing QrPanel component.
    
    Reset Traffic confirms then calls the existing per-inbound endpoint
    on the client's first attached inbound (the traffic row is keyed on
    email globally, so any attached inbound resets the shared counter).
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): expose Attached inbounds in edit mode
    
    The multi-select was gated on add-only, so editing a client had no way
    to change which inbounds it belonged to. The picker now shows in both
    modes, and on submit the modal diffs the picked set against the
    original attachedIds — additions go through the /attach endpoint,
    removals through /detach, both after the field update lands so the
    new attachments get the latest values.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): unbreak template parsing + stale i18n keys
    
    - InboundFormModal: split the multi-line help string in the
      PortFallback section onto one line — Vue's template parser was
      bailing on Unterminated string constant because a single-quoted
      literal spanned two lines inside a {{ }} interpolation.
    - ClientInfoModal: t('disable') was missing at the root level, so
      vue-i18n returned the key path literally. Use t('disabled') which
      exists.
    - Linter cleanup elsewhere: pages.client.* references renamed to
      pages.clients.* to match the merged i18n block; whitespace
      normalisation in a few unrelated Vue templates.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * 1
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(traffic): drop all-time traffic tracking
    
    Removes the AllTime field from Inbound and ClientTraffic and migrates
    existing DBs by dropping the all_time columns on startup. The counter
    duplicated up+down without adding signal, and the per-event accumulator
    ran on every traffic write.
    
    Frontend: drop the All-time column from the inbound list and the
    client-row table, the All-time row from the client info modal, and the
    All-Time Total Usage tile from the inbounds summary card. The
    allTimeTraffic/allTimeTrafficUsage i18n keys are removed across every
    locale.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): mobile cards, multi-select, bulk add
    
    Adds the same row-card layout the inbounds page uses on mobile: the
    table is suppressed under the mobile breakpoint and each client renders
    as a compact card with a status dot, email, Info button, Enable switch,
    and overflow menu. All the per-client detail (traffic, remaining,
    expiry, attached inbounds, flow, created/updated, URL, subscription)
    opens through the existing info modal.
    
    Multi-select with bulk delete wires AntD row-selection on desktop and
    a per-card checkbox on mobile; a Delete (N) button appears in the
    toolbar when anything is selected.
    
    Bulk add reuses the five email-generation modes from the inbound bulk
    modal but takes a multi-inbound picker so one bulk run can attach to
    several inbounds at once. Submits client-by-client through the
    existing /panel/api/clients/add endpoint.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(inbounds): remove legacy per-inbound client UI
    
    Now that clients live as first-class rows attached to one or many
    inbounds, the per-inbound client UI on the inbounds page is dead
    weight — every client action either has a global equivalent on the
    Clients page or makes no sense in a many-to-many world.
    
    Deletes ClientFormModal, ClientBulkModal, CopyClientsModal, and
    ClientRowTable from inbounds/. Strips the matching emits, refs,
    handlers, and dropdown menu items from InboundList and InboundsPage,
    and removes the dead mobile expand-chevron state and the desktop
    expanded-row plumbing that drove the inline client table.
    
    The InboundFormModal Clients tab still works in add-mode (one inline
    client at inbound creation) — that flow goes through ClientService.
    SyncInbound on save and remains useful.
    
    Fixes a stray "</a-dropdown>" left over by an earlier toolbar edit
    in ClientsPage that broke the template parser.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): add Delete depleted action
    
    Mirrors the legacy delDepletedClients action that lived under the
    inbounds page, but as a first-class /panel/api/clients/delDepleted
    endpoint backed by ClientService. The new path goes through
    ClientService.Delete for each depleted email, so the new clients +
    client_inbounds + xray_client_traffic tables stay consistent.
    
    Adds a danger-styled toolbar button on the Clients page (next to
    Reset all client traffic) with a confirm dialog and a toast
    reporting the deleted count.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(api): move every client-shaped endpoint off /inbounds onto /clients
    
    After the multi-inbound client migration, client state belongs to the
    client API surface, not the inbound one. Twelve routes that were
    crammed under /panel/api/inbounds/* now live where they belong, under
    /panel/api/clients/*.
    
    Moved (route, handler, doc):
      POST  /clientIps/:email
      POST  /clearClientIps/:email
      POST  /onlines
      POST  /lastOnline
      POST  /updateClientTraffic/:email
      POST  /resetAllClientTraffics/:id
      POST  /delDepletedClients/:id
      POST  /:id/resetClientTraffic/:email
      GET   /getClientTraffics/:email
      GET   /getClientTrafficsById/:id
      GET   /getSubLinks/:subId
      GET   /getClientLinks/:id/:email
    
    Their /clients/* counterparts are:
      POST  /clients/clientIps/:email
      POST  /clients/clearClientIps/:email
      POST  /clients/onlines
      POST  /clients/lastOnline
      POST  /clients/updateTraffic/:email
      POST  /clients/resetTraffic/:email          (email-only, fans out)
      GET   /clients/traffic/:email
      GET   /clients/traffic/byId/:id
      GET   /clients/subLinks/:subId
      GET   /clients/links/:id/:email
    
    per-inbound resetAllClientTraffics and delDepletedClients are dropped
    entirely — the Clients page already exposes global Reset All Traffic
    and Delete depleted actions, and per-inbound resets are meaningless
    once a client can be attached to many inbounds.
    
    ClientService.ResetTrafficByEmail is the new email-only reset path:
    it looks up every inbound the client is attached to and pushes the
    counter reset + Xray re-add through inboundService.ResetClientTraffic
    for each one, so depleted users come back online instantly.
    
    Frontend callers (ClientsPage, useClients, ClientQrModal,
    ClientInfoModal, InboundInfoModal, InboundsPage, useInbounds) all
    switched to the new paths. The Inbounds page drops its per-inbound
    "Reset client traffic" and "Delete depleted clients" dropdown items —
    users do those at the client level now. api-docs is rebuilt to match.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(service): switch tgbot + ldap callers to ClientService
    
    Adds two thin helpers to ClientService (CreateOne, DetachByEmail) and
    rewrites tgbot.SubmitAddClient and ldap_sync_job to call ClientService
    directly. Removes the JSON-blob payloads (BuildJSONForProtocol output for
    add, clientsToJSON/clientToJSON helpers) that callers previously fed to
    InboundService.AddInboundClient/DelInboundClient.
    
    ldap_sync_job.batchSetEnable now loops InboundService.SetClientEnableByEmail
    per email instead of trying to coerce AddInboundClient into doing the
    update — the old path would have failed duplicate-email validation for
    existing clients anyway.
    
    The legacy InboundService.AddInboundClient/UpdateInboundClient/
    DelInboundClient methods stay in place; they are now only used internally
    by ClientService Create/Update/Delete/Attach. Inlining + deleting them
    follows in a separate commit.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(service): move all client mutation methods to ClientService
    
    Moves the client mutation surface out of InboundService and into
    ClientService. These methods all operate on a single client (identity
    fields, traffic limits, expiry, ip limit, enable state, telegram tg id)
    and didn't belong on the inbound aggregate.
    
    Moved (12 methods): AddInboundClient, UpdateInboundClient, DelInboundClient,
    DelInboundClientByEmail, checkEmailsExistForClients, SetClientTelegramUserID,
    checkIsEnabledByEmail, ToggleClientEnableByEmail, SetClientEnableByEmail,
    ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail,
    ResetClientTrafficLimitByEmail.
    
    Each method now takes an explicit *InboundService for the helpers that
    legitimately stay on InboundService (GetInbound, GetClients, runtimeFor,
    AddClientStat / UpdateClientStat / DelClientStat, DelClientIPs /
    UpdateClientIPs, emailUsedByOtherInbounds, getAllEmailSubIDs,
    GetClientInboundByEmail / GetClientInboundByTrafficID,
    GetClientTrafficByEmail).
    
    Stays on InboundService: ResetClientTrafficByEmail and
    ResetClientTraffic(id, email) — these mutate xray_client_traffic rows,
    not client identity, so they're inbound-side bookkeeping.
    
    Callers updated: tgbot (6 calls), ldap_sync_job (1 call),
    InboundService internal (writeBackClientSubID, CopyInboundClients,
    AddInbound's email-uniqueness check), ClientService Create/Update/
    Delete/Attach/Detach.
    
    Also removes a dead resetAllClientTraffics controller handler whose
    route was already gone after the previous /clients API migration.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(clients): finish migrating to ClientService + tidy IP routes
    
    Two related cleanups in the new /clients surface:
    
    1. Move ResetAllClientTraffics (bulk-reset of xray_client_traffic +
       last_traffic_reset_time, with node-runtime propagation) from
       InboundService to ClientService. PeriodicTrafficResetJob now holds
       a clientService and calls
       j.clientService.ResetAllClientTraffics(&j.inboundService, id).
       The last client-mutation method on InboundService is gone.
    
    2. Shorten redundantly-named routes/handlers under /panel/api/clients:
       - /clientIps/:email      -> /ips/:email      (handler getIps)
       - /clearClientIps/:email -> /clearIps/:email (handler clearIps)
       The "client" prefix was redundant inside the clients namespace.
    
    Frontend (InboundInfoModal) and api-docs updated to match.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(inbounds,clients): clean up inbound modal + enrich client modal
    
    Inbound modal rework (InboundFormModal.vue + inbound.js):
    - Drop the embedded Client subform in the Protocol tab. Multi-inbound
      clients are managed exclusively from the Clients page now; a fresh
      inbound is created with zero clients (settings constructors default
      to []) and the user attaches clients afterwards.
    - Hide the Protocol tab entirely when it has nothing to render
      (VMESS, Trojan without fallbacks, Hysteria). Auto-switches active
      tab to Basic when the tab disappears while focused.
    - Move the Security section (Security selector + TLS block with certs
      and ECH + Reality block) out of the Stream tab into its own
      Security tab, sharing the canEnableStream gate.
    
    Client modal additions (ClientFormModal.vue + ClientBulkAddModal.vue):
    - Flow select (xtls-rprx-vision / -udp443) appears only when the
      panel actually has a Vision-capable inbound (VLESS or PortFallback
      on TCP with TLS or Reality). Hidden otherwise, and cleared when
      it disappears.
    - IP Limit input is disabled when the panel-level ipLimitEnable
      setting is off, fetched into useClients alongside subSettings and
      threaded through ClientsPage to both modals.
    - Edit modal now shows an "IP Log" section listing IPs that have
      connected with the client's credentials, with refresh and clear
      buttons (calls the renamed /panel/api/clients/ips and /clearIps
      endpoints).
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(inbounds): drop manual Fallbacks UI from inbound modal
    
    The PortFallback protocol type now covers the common
    VLESS-master-plus-children case with auto-wired dests, so the manual
    Fallbacks editor (showFallbacks block in the Protocol tab) is mostly
    redundant. Removed:
    
    - the v-if="showFallbacks" template block (SNI/ALPN/Path/dest/PROXY rows)
    - the showFallbacks computed
    - the addFallback / delFallback helpers
    - the .fallbacks-header / .fallbacks-title styles
    - the showFallbacks gate from hasProtocolTabContent (so Trojan-over-TCP
      no longer shows an empty Protocol tab)
    
    Power users who need a non-inbound fallback dest (nginx, static site)
    can still author settings.fallbacks via the Advanced JSON tab.
    
    * feat(clients,inbounds): move search/filter to Clients page + small fixes
    
    Search/filter relocation:
    - Remove the search/filter toolbar (search switch + filter radio +
      protocol/node selects + the visibleInbounds projection +
      inboundsFilterState localStorage + filter CSS + the SearchOutlined/
      FilterOutlined/ObjectUtil/Inbound imports it required) from
      InboundList. The filters were all client-oriented buckets bolted
      onto the inbound row.
    - Add a search/filter toolbar to ClientsPage with the same shape:
      switch between deep-text search and bucket filter (active /
      deactive / depleted / expiring / online) + protocol filter that
      matches clients attached to at least one inbound with the chosen
      protocol. State persists in clientsFilterState localStorage.
      filteredClients drives both the desktop table and the mobile card
      list, and select-all / allSelected / someSelected only span the
      visible subset.
    - useClients now also fetches expireDiff and trafficDiff from
      /panel/setting/defaultSettings (used to detect the expiring
      bucket); ClientsPage threads them into the client-bucket helper.
    
    Loose fixes folded in:
    - Add Client: email field is auto-filled with a random handle on
      open, matching uuid/subId/password/auth.
    - Inbound clone: parse and reuse the source settings JSON (with
      clients reset to []) instead of building a fresh defaulted
      Settings, so VLESS Encryption/Decryption and other non-client
      fields survive the clone.
    - en-US.json: add the ipLog string used by the edit-client modal.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): add Reverse tag field for VLESS-attached clients
    
    Mirrors the Flow field's pattern: a Reverse tag input appears in the
    Add/Edit Client modal whenever at least one selected inbound is VLESS
    or PortFallback. The value rides over the wire as
    client.reverse = { tag: '...' } so it lands directly in model.Client's
    *ClientReverse field; an empty value omits the reverse key entirely.
    
    On edit the field is hydrated from props.client.reverse?.tag, and the
    showReverseTag watcher clears the field if the user drops the last
    VLESS-like inbound from the selection.
    
    * fix(xray): emit only protocol-relevant fields per client entry
    
    The Xray config synthesizer was writing every identifier field (id,
    password, flow, auth, security/method, reverse) on every client entry
    regardless of the inbound's protocol. Xray ignores unknown fields, so
    the config worked, but it diverged from the spec and leaked secrets
    across protocols when one client was attached to multiple inbounds —
    a VLESS inbound's generated config carried the same client's Trojan
    password and Hysteria auth alongside its uuid.
    
    Switch on inbound.Protocol when building each entry:
    - VLESS / PortFallback: id, flow, reverse
    - VMess: id, security
    - Trojan: password, flow
    - Shadowsocks: password, method
    - Hysteria / Hysteria2: auth
    email is emitted for every protocol.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): restore auto-disable kick under new schema
    
    disableInvalidClients still resolved (inbound_tag, email) pairs via
    JSON_EACH(inbounds.settings.clients), which is empty after migrating
    to the clients + client_inbounds tables. Result: xrayApi.RemoveUser
    never ran for depleted clients, clients.enable stayed true so the UI
    showed them as active, and only xray_client_traffic.enable got flipped
    - making "Restart Xray After Auto Disable" only half-work.
    
    Resolve the targets via a JOIN through the new schema, flip clients.enable
    so the Clients page reflects the state, and drop the legacy JSON
    write-back plus the subId cascade workaround (email is unique now).
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): live WebSocket updates + Ended status surfacing
    
    ClientsPage now subscribes to traffic / client_stats / invalidate
    WebSocket events instead of polling /onlines every 10s. Per-row
    traffic counters refresh in place, online state stays current, and
    list-level mutations elsewhere trigger a refresh.
    
    The client roll-up summary moves from InboundsPage to ClientsPage
    where it belongs, restructured into six labeled stat tiles
    (Total / Online / Ended / Expiring / Disabled / Active) with email
    popovers on the ones with issues.
    
    Auto-disabled clients (traffic exhausted or expiry passed) now
    classify as 'depleted' even though clients.enable=false, so they
    show up under the Ended filter and render a red Ended tag instead
    of looking indistinguishable from an operator-disabled row.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(nodes): per-node client roll-up and panel version
    
    Added transient inboundCount / clientCount / onlineCount /
    depletedCount fields to model.Node, populated by NodeService.GetAll
    via aggregated queries (one join across inbounds + client_inbounds,
    one over client_traffics intersected with the in-memory online
    emails). The Nodes list renders these as colored chips on a new
    "Clients" column so an operator can see at a glance how many users
    each node carries and how many are currently online or depleted.
    
    Also exposes the remote panel's version. The central panel adds
    panelVersion to its /api/server/status payload (sourced from
    config.GetVersion). Probe reads that field and persists it on the
    node row, mirroring how xrayVersion already flows. NodesPage gets
    a new column next to Xray Version, in both desktop and mobile
    views, with English and Persian strings.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): stop node sync from resurrecting deleted clients
    
    Several related issues around node-managed clients:
    
    - Remote runtime: drop the per-inbound resetAllClientTraffics path
      and point traffic/onlines/lastOnline fetches at the new
      /panel/api/clients/* routes.
    - Delete from master: always push the updated inbound to the node
      even when the client was already disabled or depleted, so the
      node actually loses the user instead of silently keeping it.
    - setRemoteTraffic: mirror remote clients into the central tables
      only on first discovery of a node inbound. Matched inbounds let
      the master own the join table, so a stale snap can no longer
      re-create a ClientRecord (and join row) for a client that was
      just deleted on the master.
    - ClientService.Delete: route through submitTrafficWrite so deletes
      serialize with node traffic merges, and switch the final
      ClientRecord delete to an explicit Where("id = ?") clause.
    - setRemoteTraffic UNIQUE-constraint fix: use clause.OnConflict on
      inserts and email-keyed UPDATEs for client_traffics, so mirroring
      a snap doesn't trip the unique email index.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(clients): switch client API endpoints from id to email
    
    All client-scoped routes now use the unique email as the path key
    (get, update, del, attach, detach, links). Email is the stable,
    protocol-independent identifier — UUIDs don't exist for trojan or
    shadowsocks, and internal numeric ids leaked panel implementation
    detail into the public API.
    
    Removed the redundant /traffic/byId/:id endpoint (covered by
    /traffic/:email) and collapsed /links/:id/:email into /links/:email,
    which now returns links across every attached inbound for the client.
    
    Frontend selection, bulk delete, and toggle state are now keyed by
    email as well, dropping the id→email lookup workaround.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(server): move cached state and helpers into ServerService
    
    ServerController had grown to hold its own status cache, version-list
    TTL cache, history-bucket whitelist, and the loop that drove all three
    — concerns that belong in the service layer. Pull them out:
    
    - lastStatus + the @2s refresh become ServerService.RefreshStatus and
      ServerService.LastStatus; the controller's cron now just orchestrates
      the cross-service side effects (xrayMetrics sample, websocket broadcast).
    - The 15-minute Xray-versions cache (with stale-on-error fallback) moves
      into ServerService.GetXrayVersionsCached, collapsing the controller
      handler to a single call.
    - The freedom/blackhole outbound-tag walk used by /xraylogs becomes
      ServerService.GetDefaultLogOutboundTags.
    - The allowed-history-bucket whitelist moves to package-level
      service.IsAllowedHistoryBucket, so both NodeController and
      ServerController validate against the same list.
    
    Net result: web/controller/server.go drops from 458 to 365 lines and
    contains only HTTP wiring + presentation-y side effects.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * refactor(api): emit JSON-text columns as nested objects
    
    Inbound, ClientRecord, and InboundClientIps store settings /
    streamSettings / sniffing / reverse / ips as JSON-text in the DB. The
    API was passing that text through verbatim, so every consumer had to
    JSON.parse a string inside a string. Add MarshalJSON / UnmarshalJSON so
    the wire format is a real nested object, while still accepting the
    legacy escaped-string shape on write. Frontend dbinbound.js gets a
    matching coerceInboundJsonField helper for the same dual-shape read
    path, and inbound.js toJson stops emitting empty/placeholder fields
    (externalProxy [], sniffing destOverride when disabled, etc.) so the
    new normalised JSON stays terse. api-docs and the inbound-clone path
    are updated to the new shape. Controller route lists are regrouped so
    all GETs sit above POSTs.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): include inboundIds and traffic in /clients/list
    
    ClientRecord got its own MarshalJSON in the previous commit, and
    ClientWithAttachments embeds it to add inboundIds and traffic. Go
    promotes the embedded MarshalJSON to the outer struct, so the encoder
    was calling ClientRecord.MarshalJSON for the whole value and silently
    dropping the extras. The frontend reads row.inboundIds / row.traffic
    from /clients/list, so attached inbounds didn't render and newly added
    clients looked like they hadn't saved. Add an explicit MarshalJSON on
    ClientWithAttachments that splices the extras in.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): gate IP Log on ipLimitEnable + clean access-log dropdown
    
    Legacy panel hid the IP Log section when access logging was off; the
    Vue 3 migration left it gated on isEdit only, so the section showed
    even when xray's access log was 'none' and nothing was being recorded.
    Restore the ipLimitEnable gate on the edit modal's IP Log form-item.
    
    While here, clean up the Xray Settings access-log dropdown: previously
    two 'none' entries appeared (an empty value labelled with t('none') and
    the literal 'none' from the options array). Drop the empty option for
    access log (the literal 'none' covers it) and relabel the empty option
    for error log / mask address to t('empty') so they're distinguishable.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(nodes): route per-client ops through node clients API + orphan sweep
    
    Adds Runtime methods AddClient, UpdateUser, and DeleteUser so master
    mutates clients on a node via /panel/api/clients/{add,update,del} rather
    than pushing the whole inbound. The previous rt.UpdateInbound path made
    the node DelInbound+AddInbound on every single-client change, briefly
    cycling every other user on the same inbound.
    
    DelInbound no longer filters by enable=true, so a disabled node inbound
    actually gets removed from the node instead of being resurrected by the
    next snap.
    
    setRemoteTrafficLocked now sweeps any ClientRecord with zero
    ClientInbound rows after SyncInbound rebuilds the attachments, which is
    how a node-side delete propagates back to master instead of leaving a
    detached ghost. ClientService.Delete tombstones the email first so a
    snap arriving mid-delete can't re-create the record.
    
    WebSocket broadcasts an "invalidate(clients)" message on every client
    mutation so the Clients page refreshes without manual reload.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(balancers): allow fallback on all strategies + feed burstObservatory from random/roundRobin
    
    Drops the random/roundRobin gate on the Fallback field in
    BalancerFormModal so every strategy can pick a fallback outbound.
    
    syncObservatories now feeds burstObservatory from leastLoad +
    random + roundRobin balancers (was leastLoad only), matching how
    leastPing feeds observatory.
    
    Fix the JsonEditor "Unexpected end of JSON input" that appeared
    when switching a balancer between leastPing and another strategy:
    the obsView watcher was gated on showObsEditor (a boolean OR of
    the two flags) and missed the case where one observatory
    swapped for the other in the same tick. Watch the individual
    flags instead so obsView flips to the surviving editor and the
    getter stops pointing at a deleted key.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(inbounds): use sortedInbounds for mobile empty-state check
    
    InboundList referenced an undefined visibleInbounds in the mobile
    card list's empty-state guard, throwing "Cannot read properties of
    undefined (reading 'length')" and breaking the entire mobile render.
    
    * feat(clients): sortable table columns
    
    Adds the same sortState / sortableCol / sortFns pattern InboundList
    uses, wrapping filteredClients in sortedClients so sort composes with
    the existing search/filter pipeline. Sortable: enable, email,
    inboundIds (attachment count), traffic, remaining, expiryTime;
    actions and online stay unsorted.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(shadowsocks): generate valid ss2022 keys and per-client method for legacy ciphers
    
    The Add Client flow on shadowsocks inbounds was producing xray configs
    that failed to start:
    
    - 2022-blake3-* ciphers need a base64-encoded key of an exact byte
      length per cipher. fillProtocolDefaults was assigning a uuid-style
      string, which xray rejects as "bad key". Now the password is
      generated (or replaced if invalid) via random.Base64Bytes(n) sized
      to the chosen cipher.
    - Legacy ciphers (aes-256-gcm, chacha20-*, xchacha20-*) require a
      per-client method field in multi-user mode; model.Client has no
      Method, so settings.clients was stored without one and xray failed
      with "unsupported cipher method:". applyShadowsocksClientMethod
      now injects the top-level method into each client on add/update,
      and healShadowsocksClientMethods backfills it at xray-config-build
      time so existing inbounds heal on the next start.
    - xray/api.go ssCipherType switch was missing aes-256-gcm, which
      fell through to ss2022 path.
    - SSMethods dropdown now offers aes-256-gcm.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): preserve ClientRecord on inbound delete + filter Attached inbounds to multi-client protocols
    
    Replace the global orphan sweep in setRemoteTrafficLocked with a
    per-inbound diff cleanup: only delete a ClientRecord whose email
    disappeared from a snap-tracked inbound (i.e. a node-side delete).
    Inbounds that vanished entirely from the snap (e.g. admin deleted
    the inbound on master) aren't iterated, so a client whose last
    attachment came from that inbound is now left alone instead of
    being deleted alongside the inbound.
    
    ClientFormModal and ClientBulkAddModal now filter the Attached
    inbounds dropdown to protocols that actually support multiple
    clients: shadowsocks, vless, vmess, trojan, hysteria, hysteria2,
    and portfallback (which routes through VLESS settings).
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): make empty-state text readable on dark/ultra themes
    
    The "No clients yet" empty state had a hardcoded black color
    (rgba(0,0,0,0.45)) that vanished against the dark backgrounds.
    Drop the inline color, let it inherit from the AntD theme, and
    fade with opacity like the mobile card empty state already does.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(clients): client-first tgbot add flow, tgId field, lightweight inbound options
    
    - tgbot: drop legacy per-protocol Add Client UI in favour of a client-first
      multi-inbound flow. New BuildClientDraftMessage / getInboundsAttachPicker
      let an admin pick one or more inbounds and submit a single client; per-
      protocol secrets are now generated server-side via fillProtocolDefaults.
      Drops awaiting_id/awaiting_password_tr/awaiting_password_sh state cases
      and add_client_ch_default_id/pass_tr/pass_sh/flow callbacks. Adds a
      setTGUser button + awaiting_tg_id state so the bot can set Client.TgID
      during Add.
    - clients UI: add Telegram user ID input to ClientFormModal (0 = none).
      Hide IP Limit field entirely when ipLimitEnable is off — disabled fields
      still take layout space, this collapses Auth(Hysteria) to full width.
    - inbounds API: new GET /panel/api/inbounds/options that returns just
      {id, remark, protocol, port, tlsFlowCapable}. Used by the clients page
      pickers so the dropdown payload stays small on panels with thousands of
      clients (drops settings JSON, clientStats, streamSettings). Server-side
      TlsFlowCapable mirrors Inbound.canEnableTlsFlow so the modal no longer
      needs to parse streamSettings client-side.
    - clientInfoMsg now shows attached inbound remarks, and getInboundUsages
      reports the attached client count per inbound.
    - api-docs: document the new /options endpoint and add tgId / flow to the
      clients add/update bodies.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(inbounds): keep Node column visible for node-attached inbounds
    
    The Node column was bound to hasActiveNode, so disabling every node hid
    the column even when inbounds were still attached to those nodes — the
    admin lost the visual cue that those inbounds belonged to a node and
    would come back when it was re-enabled. Combine hasActiveNode with a
    new hasNodeAttachedInbound check (any dbInbound with nodeId != null) so
    the column survives node-disable.
    
    * fix(api-docs): accept functional-component icons in EndpointSection
    
    AntD-Vue icons (SafetyCertificateOutlined, etc.) are functional
    components, so the icon prop's type: Object validator was rejecting
    them with a "Expected Object, got Function" warning at runtime.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * test: cover crypto, random, netsafe, sub helpers, xray equals, websocket hub, node service
    
    Adds ~110 unit tests across previously untested packages. Focus on
    pure-logic and concurrency surfaces where regressions would silently
    affect users:
    
    - util/crypto, util/random: password hashing round-trip, ss2022 key
      generation, alphabet/length invariants.
    - util/netsafe: IsBlockedIP edge cases, NormalizeHost validation,
      SSRF guard with AllowPrivate context bypass.
    - util/common, util/json_util: traffic formatter, Combine nil-skip,
      RawMessage empty-as-null and copy-on-unmarshal.
    - sub: splitLinkLines, searchKey/searchHost, kcp share fields,
      finalmask normalization, buildVmessLink round-trip.
    - xray: Config.Equals and InboundConfig.Equals field-by-field,
      getRequiredUserString/getOptionalUserString type checks.
    - web/websocket: hub registration, throttling, slow-client eviction,
      nil-receiver safety, concurrent register/unregister.
    - web/service: NodeService.normalize validation, normalizeBasePath,
      HeartbeatPatch.ToUI mapping.
    - web/job: atomicBool concurrent set/takeAndReset semantics.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * i18n(clients): replace English fallbacks with proper translation keys
    
    Pulls every hard-coded English label/title in the Clients page and its
    four modals through the i18n layer so localized panels stop leaking
    English. New keys live under pages.clients (auth, hysteriaAuth, uuid,
    flow, flowNone, reverseTag, reverseTagPlaceholder, telegramId,
    telegramIdPlaceholder, created, updated, ipLimit) plus refresh at the
    root and toasts.bulkDeletedMixed / bulkCreatedMixed for partial-failure
    toasts. Also switches the add-client modal's primary button from "Add"
    to "Create" for consistency with other create flows.
    
    The bulk-add Random/Random+Prefix/... email-method options stay
    hard-coded by request - they're identifier-shaped strings.
    
    * i18n: backfill 99 missing keys across all 12 non-English locales
    
    Brings every translation file up to parity with en-US.json so the
    Clients page, the fallback-children inbound section, the new refresh
    verb, the Nodes panel-version label and a handful of older holes stop
    falling through to the English fallback. New strings span:
    
    - pages.clients.* (labels, confirmations, toasts, emailMethods)
    - pages.inbounds.portFallback.* (Reality fallback inbound section)
    - pages.nodes.panelVersion, menu.clients, refresh
    
    Technical identifiers (Auth, UUID, Flow, Reverse tag) are intentionally
    left untranslated since they correspond to xray-core field names.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * i18n: drop stale pages.client block duplicated in every non-English locale
    
    Every non-English locale carried a pages.client (singular) section with
    30 entries that duplicated pages.clients (plural). The plural namespace
    is what the Vue code actually consumes; the singular one was dead
    weight from an older rename that never got cleaned up in the
    non-English files. Removing it brings every locale to exactly 984
    keys, matching en-US.json.
    
    * chore: apply modernize analyzer fixes across codebase
    
    Mechanical replacements suggested by golang.org/x/tools/.../modernize:
    strings.Cut/CutPrefix/SplitSeq, slices.Contains, maps.Copy, min(),
    range-over-int, new(expr), strings.Builder for hot += loops,
    reflect.TypeFor[T](), sync.WaitGroup.Go(), drop legacy //+build lines.
    
    * feat(database): add PostgreSQL as an optional backend alongside SQLite
    
    Lets operators with large client counts or multi-node setups pick PostgreSQL
    at install time without breaking the existing SQLite default. Backend is
    selected at runtime via XUI_DB_TYPE/XUI_DB_DSN, a small dialect layer keeps
    the five JSON_EXTRACT/JSON_EACH queries portable, and a new `x-ui migrate-db`
    subcommand copies SQLite data into PostgreSQL in FK-aware order.
    
    * fix(inbounds): gate node selector to multi-node-capable protocols
    
    Hide the Deploy-To selector and clear nodeId when switching to a
    protocol that can't run on a remote node. Also:
    
    - subs: return 404 (not 400) when subId matches no inbounds, so VPN
      clients distinguish "deleted/unknown" from a server error
    - hysteria link gen: use the inbound's resolved address so node-managed
      inbounds advertise the node host instead of the central panel
    - shadowsocks: default network to 'tcp' (udp was causing issues for some
      clients on first-create)
    - vite dev proxy: rewrite migrated-route bypass against the live base
      path instead of a hardcoded single-segment regex
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(clients): bulk add/delete correctness + perf, working pagination, delayed-start in form
    
    Bulk add/delete were serial on the frontend (one toast per call, N round-trips)
    and the backend race exposed by parallelizing them lost client attachments and
    hit UNIQUE constraint failed on client_inbounds. The single add/edit modal also
    had no Start-After-First-Use option, and the table never showed the delayed
    duration.
    
    Backend (web/service/client.go):
    - Per-inbound mutex on Add/Update/Del InboundClient so concurrent writers on
      the same inbound don't lose the read-modify-write of settings JSON.
    - SyncInbound skips create+join when the email is tombstoned so a concurrent
      maintenance pass (adjustTraffics, autoRenewClients, markClientsDisabledIn-
      Settings) that did a stale RMW can't resurrect a just-deleted client with a
      fresh id.
    - compactOrphans sweeps settings.clients entries whose ClientRecord no longer
      exists, applied in Add/DelInboundClient + DelInboundClientByEmail so each
      user-initiated mutation self-heals the inbound's settings.
    - DelInboundClient uses Pluck instead of First for the stats lookup so a
      missing row doesn't abort the delete with a noisy ErrRecordNotFound log.
    
    Frontend:
    - HttpUtil.{get,post} accept a silent option that suppresses the auto-toast.
    - ClientBulkAddModal fires creates in parallel + silent + one summary toast.
    - useClients.removeMany runs deletes in parallel + silent and refreshes once;
      ClientsPage bulk delete uses it and shows one aggregate toast.
    - useClients.applyInvalidate debounces 200 ms so the burst of N WebSocket
      invalidate events from the backend collapses into a single refresh.
    - ClientsPage pagination is reactive (paginationState ref + tablePagination
      computed); onTableChange persists page-size and page changes.
    - ClientFormModal gains a Start-After-First-Use switch + Duration days input
      alongside the existing Expiry Date picker; on edit-mode open a negative
      expiryTime is decoded back to delayed mode + days; on submit the payload
      sends -86400000 * days or the absolute timestamp.
    - ClientsPage table shows the delayed-start duration (blue tag Nd, tooltip
      Start After First Use: Nd) instead of infinity.
    - Telegram ID field in the form is hidden when /panel/setting/defaultSettings
      reports tgBotEnable=false; Comment then fills the row.
    - Form row 3 collapses UUID (span 12) + Total GB (span 8) + Limit IP (span 4)
      when ipLimitEnable is on, else UUID + Total GB at 12/12.
    - useInbounds.rollupClients counts only clients with a matching clientStats
      row, so orphans in settings.clients no longer inflate the inbound's count.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(windows): clean shutdown, working panel restart, harden kernel32 load
    
    Three Windows-specific issues addressed:
    
    1. Orphaned xray-windows-amd64 after VS Code debugger stop. Delve's
       "Stop" sends TerminateProcess to the Go binary, which is uncatchable
       — our signal handlers never run, so xrayService.StopXray() is skipped
       and xray is left dangling. Spawn xray as a child of a Job Object with
       JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so the OS kills xray when our
       handle to the job is closed (which happens even on TerminateProcess).
       Also trap os.Interrupt in main so Ctrl+C in the terminal runs the
       graceful path.
    
    2. /panel/setting/restartPanel logged "failed to send SIGHUP signal: not
       supported by windows" because Windows can't deliver arbitrary signals.
       Add a restart hook in web/global; main registers it to push SIGHUP
       into its own signal channel, and RestartPanel calls the hook before
       falling back to the (Unix-only) signal path. Same restart-loop code
       runs in both cases.
    
    3. util/sys/sys_windows.go now uses windows.NewLazySystemDLL so the
       kernel32.dll resolve is pinned to %SystemRoot%\System32 (prevents
       DLL hijacking by a planted DLL next to the binary). Local filetime
       type replaced with windows.Filetime, and the unreliable
       syscall.GetLastError() fallback replaced with a type assertion on the
       errno captured at call time.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(sys): correct CPU/connection accounting on linux + darwin
    
    util/sys/sys_linux.go:
    - GetTCPCount/GetUDPCount were counting the column header row in
      /proc/net/{tcp,udp}[6] as a connection, inflating the reported total
      by 1 per non-empty file (so the panel status line always showed 2
      more connections than actually existed). Replace getLinesNum +
      safeGetLinesNum with a single bufio.Scanner-based countConnections
      that skips the header.
    - CPUPercentRaw now opens HostProc("stat") instead of a hardcoded
      /proc/stat so HOST_PROC overrides apply, matching the connection
      counters in the same file.
    - Simplify CPU field unpacking: pad nums to 8 once instead of guarding
      every assignment with a len check.
    
    util/sys/sys_darwin.go:
    - Fix swapped idle/intr indices on kern.cp_time. BSD CPUSTATES order
      is user, nice, sys, intr, idle (CP_INTR=3, CP_IDLE=4) — gopsutil's
      cpu_darwin_nocgo.go reads the same layout. The previous code used
      out[3] as idle and out[4] as intr, so busy = total - dIdle was
      actually subtracting interrupt time, making the panel report CPU
      usage close to 100% on macOS regardless of actual load.
    - Collapse the per-field delta math into a single loop.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * fix(xray): rotate crash reports into log folder, prevent overwrites
    
    writeCrashReport had two flaws: it wrote to the bin folder (alongside the
    xray binary) which conflates artifacts, and the second-precision timestamp
    meant a tight restart-loop crash burst overwrote prior reports. Write to
    the log folder with nanosecond precision and keep the last 10 reports.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * revert(inbounds): drop unreleased portfallback protocol
    
    The Port-with-Fallback inbound (commit 62fd9f9d) was confusing as a
    standalone protocol — fallbacks belong on a regular VLESS/Trojan TCP-TLS
    inbound, the way Xray models them natively. Rip out the entire feature
    cleanly (no migration needed since it was never released): protocol
    constant, fallback children DB table, FallbackService, 2 API endpoints,
    all UI rows, related translations and api-docs. A native fallback flow
    attached to VLESS/Trojan TCP-TLS/Reality will land in a follow-up commit.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
    
    * feat(inbounds): native fallbacks on VLESS/Trojan TCP-TLS, with working child links
    
    A VLESS or Trojan inbound on TCP with TLS or Reality can now act as a
    fallback master: pick existing inbounds as children and the panel auto-
    fills the SNI / ALPN / path / xver routing fields from each child's
    transport, auto-builds settings.fallbacks at config-gen time, and
    rewrites the child's client-share link so it advertises the master's
    reachable endpoint and TLS state instead of the child's loopback listen.
    
    Layout matches the Xray All-in-One Nginx example: master at :443 with
    clients + TLS, each child on 127.0.0.1 with its own transport+clients.
    Order matters (Xray walks fallbacks top-to-bottom) — reorder via the
    per-row up/down arrows. Path / SNI / ALPN are exposed under a per-row
    Edit toggle for the rare cases where the auto-derivation needs
    overriding; otherwise just pick a child and you're done.
    
    Backend: new InboundFallback table + FallbackService (GetByMaster /
    SetByMaster / GetParentForChild / BuildFallbacksJSON); two routes
    (GET / POST /panel/api/inbounds/:id/fallbacks); xray.GetXrayConfig
    injects settings.fallbacks for any VLESS/Trojan TCP-TLS/Reality
    inbound; GetInbounds annotates each child with FallbackParent so the
    frontend can rewrite links without an extra round-trip.
    
    Link projection covers every emission path — clients-page QR/links,
    per-inbound Get URL, raw subscription, sub-JSON, sub-Clash, and the
    inbounds-page link/info/QR — via a shared projectThroughFallbackMaster
    on the backend and a shared projectChildThroughMaster on the frontend
    that both handle the panel-tracked relationship and the legacy
    unix-socket (@vless-ws) convention.
    
    Strings translated into all 12 non-English locales.
    
    * docs: rewrite CONTRIBUTING with full local-dev setup
    
    The prior three-line CONTRIBUTING left newcomers guessing at every
    non-trivial step: which Go / Node versions, where xray comes from, why
    the panel goes blank when XUI_DEBUG=true is flipped on, how the Vue
    multi-page setup is wired, what to do on Windows when go build trips
    on the CGo SQLite driver.
    
    Now covers prerequisites, MinGW-w64 install on Windows (niXman builds
    or MSYS2), one-shot first-time setup, two frontend dev workflows with
    the XUI_DEBUG asset-cache gotcha called out, the architecture and
    conventions of the Vue side, a project-layout map, useful env vars,
    and the PR checklist.
    
    ---------
  • feat: add API token to install output (#4322)
    * feat: add API token to install output
    
    Add -getApiToken flag to the setting subcommand so shell scripts
    can retrieve the panel API token. Include the token in the
    install.sh completion banner for automation/deployment use.
    
    * fix(install): adapt -getApiToken CLI to multi-token service
    
    settingService.GetApiToken was removed when API tokens moved to a
    multi-row ApiTokenService. Switch the install-time CLI to list tokens
    and create one named "install" if none exist, preserving the
    `apiToken: <value>` output the install.sh grep depends on.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(install): add skip-SSL option for reverse-proxy / SSH-tunnel setups
    Adds a 4th choice to the install-time SSL prompt for users who terminate
    TLS elsewhere (nginx, Caddy, Traefik) or only reach the panel through an
    SSH tunnel — closes #3802.
    
    - Option 4 prints a clear warning, then optionally binds the panel to
      127.0.0.1 via `x-ui setting -listenIP` so it's unreachable from the
      public internet
    - When the user binds to 127.0.0.1, print the same SSH port-forwarding
      command set that x-ui.sh's SSH_port_forwarding() already shows, so
      remote access is one ssh -L away
    - Track SSL_SCHEME so the final "Access URL:" line shows http:// when
      SSL is skipped, instead of misleadingly advertising https://
    - Soften the section header from "(MANDATORY)" to "(RECOMMENDED)" and
      print "SSL Certificate: Skipped" when option 4 is chosen
    - Rework the SSL menu copy to a parallel "verb — what (constraint)"
      shape with a single Tip line focused on option 4's risks
  • fix(scripts): harden server-IP detection with multi-provider + manual fallback
    Try six IPv4 providers in turn, accept only HTTP 200 + IPv4-shaped body,
    and prompt the user to enter their IP if every provider fails.
    
    Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
  • fix: enhance WebSocket stability, resolve XHTTP configurations and fix UI loading shifts (#3997)
    * feat: implement real-time traffic monitoring and UI updates using a high-performance WebSocket hub and background job system
    
    * feat: add bulk client management support and improve inbound data handling
    
    * Fix bug
    
    * **Fixes & Changes:**
    1. **Fixed XPadding Placement Dropdown**:
       - Added the missing `cookie` and `query` options to `xPaddingPlacement` (`stream_xhttp.html`).
       - *Why:* Previously, users wanting `cookie` obfuscation were forced to use the `header` placement string. This caused Xray-core to blindly intercept the entire monolithic HTTP Cookie header, failing internal padding-length validations and causing the inbound to silently drop the connection.
    2. **Fixed Uplink Data Placement Validation**:
       - Replaced the unsupported `query` option with `cookie` in `uplinkDataPlacement`.
       - *Why:* Xray-core's `transport_internet.go` explicitly forbids `query` as an uplink placement option. Selecting it from the UI previously sent a payload that would cause Xray-core to instantly throw an `unsupported uplink data placement: query` panic. Adding `cookie` perfectly aligns the UI with Xray-core restrictions.
    ### Related Issues
    - Resolves #3992
    
    * This commit fixes structural payload issues preventing XHTTP from functioning correctly and eliminates WebSocket log spam.
    - **[Fix X-Padding UI]** Added missing `cookie` and `query` options to X-Padding Placement. Fixes the issue where using Cookie fallback triggers whole HTTP Cookie header interception and silent drop in Xray-core. (Resolves [#3992](https://github.com/MHSanaei/3x-ui/issues/3992))
    - **[Fix Uplink Data Options]** Replaced the invalid `query` option with `cookie` in Uplink Data Placement dropdown to prevent Xray-core backend panic `unsupported uplink data placement: query`.
    - **[Fix WebSockets Spam]** Boosted `maxMessageSize` boundary to 100MB and gracefully handled fallback fetch signals via `broadcastInvalidate` to avoid buffer dropping spam. (Resolves [#3984](https://github.com/MHSanaei/3x-ui/issues/3984))
    
    * Fix
    
    * gofmt
    
    * fix(websocket): resolve channel race condition and graceful shutdown deadlock
    
    * Fix: inbounds switch
    
    * Change max quantity from 10000 to 500
    
    * fix
  • Fix SSL domain setup on reinstall: reuse existing certs and avoid false success/failure logs (#4004)
    * perf: replace /dev/urandom | tr with openssl rand to fix CPU spike
    
    * fix: add cron to default package installation and improve SSL certificate handling
    
    * Reworked `--installcert` success criteria, cleanup behavior adjusted.
  • Require HTTP 200 from curl before using IP
    Replace simple curl+trim checks with a response+http_code parse to ensure the remote URL returns HTTP 200 and a non-empty body before assigning server_ip. Changes applied to install.sh, update.sh and x-ui.sh: use curl -w to append the status code, extract http_code and ip_result, and only set server_ip when http_code == 200 and ip_result is non-empty. This makes the IP discovery more robust against error pages or partial responses while keeping the existing timeout behavior.
  • Add x-ui.service.arch file (#3650)
    * Add a service file for Arch-based OSs
    
    * Update release.yml with arch service file
    
    * Update x-ui.service.arch
  • Add port selection and checks for ACME HTTP-01 listener
    Introduces user prompts to select the port for ACME HTTP-01 certificate validation (default 80), checks if the chosen port is available, and provides guidance for port forwarding. Adds is_port_in_use helper to all scripts and improves messaging for certificate issuance and error handling.
  • fix
  • Remove wget dependency from everywhere (#3598)
    * Remove wget dependency
    
    * Merge branch 'curl_only' of https://github.com/nebulosa2007/3x-ui into nebulosa2007-curl_only
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • Set variables for packaging purposes (#3600)
    * Set Variables for settings
  • Added EnvironmentFile to systemd unit (#3606)
    * Added EnvironmentFile to systemd unit
    
    * Added support for older releases
    
    * Remove ARGS
    
    * Fixed copy unit
    
    * Fixed unit filename
    
    * Update update.sh
  • Set log folder variable to /var/log/3x-ui (#3599)
    * Set log folder variable to /var/log/3x-ui
    
    * Set log folder as x-ui and create the log folder
    
    * Create the log folder in install and update scripts
  • fix