Commit Graph
597 Commits
  • fix: allow IPv4 and IPv6 inbounds to share a port (#6603)
    * fix: distinguish IPv4 and IPv6 listen conflicts
    
    * fix(ports): let an IPv4 address share a port only with a v6only wildcard
    
    xray listens on tcp/udp, and Go opens every wildcard listen, 0.0.0.0
    included, as one dual-stack socket unless sockopt.v6only is set. Treating
    :: and 0.0.0.0 as separate families let the panel save pairs the core
    then fails to bind, and it broke main's own TestListenOverlaps.
    
    listenOverlaps now takes the inbound's sockopt.v6only: a wildcard claims
    both families, or only IPv6 with v6only, so :: with v6only may share its
    port with an IPv4 address while a plain :: or 0.0.0.0 still may not.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(tgbot): unstick the add-client wizard's inbound picker (#6621)
    * fix(tgbot): unstick the add-client wizard's inbound picker
    
    Tapping "➕ Новый клиент" always sent the "choose inbound" message,
    even when the button list ended up empty after protocol filtering.
    getInboundsAddClient checked len(inbounds)==0 before filtering but
    never re-checked after, so an admin whose every inbound was excluded
    got a message with nothing to tap and no further feedback.
    
    WireGuard and AmneziaWG were excluded outright too, a holdover from
    the wizard's original 2025 implementation, before
    defaultWireguardClients
    and defaultAmneziaWGClients existed. Both now auto-generate a keypair +
    AllowedIPs for a client with none set, and the subscription server
    already emits wireguard:// and vpn:// share links for them, so both
    inbound types flow through the same generic Create path as VLESS/Trojan
    already used by the bot. Mixed/HTTP/Tunnel stay excluded: they have no
    per-client model in this codebase.
    
    - getInboundsAddClient now returns getInboundsFailed when the button
      list is empty after filtering, instead of sending an unusable keyboard
    - WireGuard/AmneziaWG removed from the exclusion list in both
      getInboundsAddClient and getInboundsAttachPicker
    - the previously duplicated excludedProtocols map is now a single
      package-level addClientExcludedProtocols shared by both functions
    
    * test(tgbot): pin which inbounds the add-client picker offers
    
    The picker change had no test. One drives a database holding WireGuard,
    AmneziaWG, VLESS and Mixed inbounds and wants the first three offered;
    the other holds only Mixed, HTTP and Tunnel and wants getInboundsFailed
    instead of an empty keyboard. Both fail on the previous picker.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(amneziawg): stop AAAA fallback on v4-only tunnels and expose I2–I5 (#6611)
    * fix(amneziawg): stop AAAA fallback on v4-only tunnels and expose I2–I5
    
    Gate tunnel DNS queries to address families the device can actually dial,
    reject undialable literal IPs early, and surface I2–I5 on the outbound form.
    
    Fixes #6570
    
    * ci: retrigger frontend after npm registry maintenance
    
    The frontend job failed solely on `npm audit` while registry.npmjs.org
    returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
    build, and storybook all passed. Local `npm audit --omit=dev
    --audit-level=high` now reports 0 vulnerabilities.
    
    * style(amneziawg): keep the tunnel DNS family comments to two lines
    
    CLAUDE.md caps a comment block at two lines.
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres (#6612)
    * fix(ip-limit): CAS-retry inbound_client_ips merges under Postgres
    
    Two writers RMW the same ips JSON blob; on PostgreSQL a lost update drops
    remote IPs that partitionLiveIps only sees through that blob (#6587).
    Compare-and-set on the previous blob with re-merge on miss, matching the
    repo's conditional Where+RowsAffected pattern.
    
    Fixes #6587
    
    * ci: retrigger frontend after npm registry maintenance
    
    The frontend job failed solely on `npm audit` while registry.npmjs.org
    returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
    build, and storybook all passed. Local `npm audit --omit=dev
    --audit-level=high` now reports 0 vulnerabilities.
    
    * test(ip-limit): cover the scan's CAS against a mid-scan node sync
    
    The job-side compare-and-set had no test of its own. A write injected
    between the scan's read and its update now has to keep the node's remote
    IP; main's blind Save drops it. Also keeps the new comments to two lines,
    as CLAUDE.md requires.
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): keep serverDescription literal in external link fragments (#6580)
    * fix(panel): accept 2FA codes from adjacent TOTP windows
    
    CheckUser compared only gotp.Now(), so a code submitted at the end of
    its 30s window (or with slight client/server clock drift) failed with
    'invalid 2fa code', while the immediate retry in the next window
    succeeded. Accept current +/-1 window, the standard TOTP skew
    tolerance.
    
    Fixes MHSanaei/3x-ui#6535
    
    * fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode
    
    Move the +/-1 window helper to internal/util/totp so both 2FA
    acceptance points use it: login (CheckUser) and disable/rebind plus
    username/password changes (VerifyTwoFactorCode). Also shrink comments
    to the 2-line house rule and anchor the unit test mid-window to avoid
    a step-boundary flake.
    
    Addresses review on #6546 (MEDIUM + 2 LOWs).
    
    * fix(sub): keep serverDescription literal in external link fragments
    
    Client external links escaped the whole remark, turning
    ?serverDescription=<base64> into %3F...%2F... so Happ lost its
    subtitle. Split on ?serverDescription= like appendQueryAndFragment
    (#6488): escape only the display name, keep a clean base64 tail
    literal, fall back to full escaping otherwise.
    
    Fixes MHSanaei/3x-ui#6575
    
    * refactor(sub): share one serverDescription fragment split across link paths
    
    #6488 fixed the split in appendQueryAndFragment and #6575 was the same
    bug on the external-link path, which had its own copy. Both now call
    escapeLinkFragment with their own escaper, so a later change to the tail
    check cannot reach one path and miss the other.
    
    ---------
    
    Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): send panel guid as X-HWID on outbound subscription fetch (#6579)
    * fix(panel): accept 2FA codes from adjacent TOTP windows
    
    CheckUser compared only gotp.Now(), so a code submitted at the end of
    its 30s window (or with slight client/server clock drift) failed with
    'invalid 2fa code', while the immediate retry in the next window
    succeeded. Accept current +/-1 window, the standard TOTP skew
    tolerance.
    
    Fixes MHSanaei/3x-ui#6535
    
    * fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode
    
    Move the +/-1 window helper to internal/util/totp so both 2FA
    acceptance points use it: login (CheckUser) and disable/rebind plus
    username/password changes (VerifyTwoFactorCode). Also shrink comments
    to the 2-line house rule and anchor the unit test mid-window to avoid
    a step-boundary flake.
    
    Addresses review on #6546 (MEDIUM + 2 LOWs).
    
    * fix(sub): send panel guid as X-HWID on outbound subscription fetch
    
    Outbound subscriptions hit the same HWID-limited donor 404 as client
    external links (#6559/#6567). Identify this panel with GetPanelGuid
    plus X-Device-OS, honoring the externalSubSendHwid opt-out.
    
    Fixes MHSanaei/3x-ui#6574
    
    * fix(sub): send the external-subscription X-HWID from outbound fetches too
    
    The outbound fetch used panelGuid while client external links send the
    externalSubHwid id from #6567, so an HWID-limited provider counted one
    panel as two devices. It also re-added the externalSubSendHwid opt-out
    that #6567 dropped.
    
    Move the id into service.ExternalSubscriptionHwid, keeping the
    externalSubHwid row so existing installs keep their slot, and send it
    from both paths. The outbound test now fails on the panelGuid version.
    
    ---------
    
    Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): never use X-Real-IP as the subscription host (#6608)
    ResolveRequest and the panel's resolveHost fell back to X-Real-IP for the host when a trusted proxy sent no X-Forwarded-Host. X-Real-IP names the visitor, so behind nginx with only that header set, subscription and exported links advertised the subscriber's own public IP as the server.
    
    The host now comes from a trusted X-Forwarded-Host, else the dialed request Host. X-Real-IP stays a client-IP source only.
    
    Fixes #6589.
  • test(database): give each package its own schema when tests run on PostgreSQL (#6594)
    With XUI_DB_TYPE=postgres every test package shared one database and worked in public. Go runs package test binaries concurrently, so migrations raced and rows a previous run left behind leaked into the next.
    
    testpg.IsolatePackage creates a schema for the calling package, puts it first on search_path and drops it when the package finishes. It returns at once unless XUI_DB_TYPE is postgres. internal/web/service's TestMain adopts it.
  • fix(sub): drop legacy freedom.domainStrategy from JSON sub template (#6609)
    The JSON-subscription template still set settings.domainStrategy on its freedom outbound, the placement #6515 moved off everywhere else, so xray-core migrated it to sockopt with a deprecation warning on every load. AsIs is the core default when the key is absent, so dropping it changes nothing else.
    
    Fixes #6482.
  • fix(sub): preserve external VLESS encryption in Clash subscriptions (#6576)
    * fix(sub): preserve external VLESS encryption in Clash subscriptions
    
    Copy non-empty, non-none encryption from parsed external VLESS settings,
    matching local proxy export. This prevents merged Clash/Mihomo subscriptions
    from losing the encryption parameters of externally added nodes.
    
    Cover encryption normalization and omission, plus merged YAML from pasted
    links and HTTPS subscriptions containing plain or Base64 share-link lists.
    
    Validation: regression cases fail before the fix and pass after it; the full
    subscription package and go build ./... pass. Four unrelated packages still
    fail on Windows, with the same failures reproduced using the original code.
    
    Refs: MHSanaei/3x-ui#6572
    
    * test(nodes): wait for chart effects in history panel assertions
    
    The DOM can commit its accessible labels before Sparkline updates the refs used by uPlot range callbacks. Wait for the existing assertions together so the test does not read the empty-data range.
    
    Reproduced the original CI failure locally on attempt 5. The fixed test passed 12 consecutive runs; lint, format and TypeScript checks pass. The full frontend suite passed 1607 of 1608 tests, including Storybook. The unrelated input-number guard fails on Windows because execFileSync cannot launch the extensionless oxlint shim (ENOENT); invoking oxlint.cmd reports all three expected diagnostics.
  • fix(sub): preserve per-inbound tunnel identity in subscriptions (#6653)
    matchingClients primed the per-request link cache with the shared clients rows, whose wg_* columns hold whichever WireGuard/AmneziaWG inbound synced last. A client on several such inbounds (one per node) therefore got the same tunnel address and keys in every subscription profile.
    
    Membership, subId, enable, quota and expiry still come from the normalized tables. For WireGuard and AmneziaWG the tunnel identity (keys, AllowedIPs, keepalive) is now overlaid from this inbound's own settings, the source clientsForLinkExport already uses for direct links. A member with no settings entry, or malformed settings, yields no link for that inbound rather than another inbound's credentials.
    
    Fixes #6641.
  • fix(sub): emit Hysteria certificate pin for Mihomo (#6651)
    buildHysteriaProxy dropped pinnedPeerCertSha256 from Clash/Mihomo YAML although the raw share link already carries it as pinSHA256, so Mihomo rejected a self-signed Hysteria2 certificate whenever allowInsecure was off.
    
    Emit the first valid SHA-256 pin as Mihomo's fingerprint field in its colon-separated form, honouring an external endpoint's override. client-fingerprint stays the uTLS setting. Mihomo accepts a single fingerprint, so of several pins the first valid one wins.
    
    Refs #4683.
  • fix(tgbot): scope the add-client wizard to the admin, not the chat (#6604)
    Two admins in one group chat shared one draft and one wizard step: clientDrafts and userStateStore were keyed by chat id alone, so the second admin's wizard opened on the first one's email and limits, and whichever of them tapped a control last decided what the other created.
    
    Key both stores by (chat, user) instead. A private chat is unaffected: its two ids are equal, so the key matches what the chat alone used to be. A message with no sender (a channel post) keys to user 0, which no admin holds.
    
    Fixes #6593.
  • fix(database): keep the legacy tag cleanup from colliding with an existing tag (#6592)
    * fix(database): avoid legacy inbound tag cleanup collisions
    
    * test(database): assert the legacy tag cleanup keeps the migration green
    
    The collision guard's test asserted only that the colliding tag was left
    alone, which an unguarded cleanup also produces: the UPDATE fails on the
    unique index and the row is unchanged either way. The cleanup shares a
    transaction with every other requirement, so that failure rolls all of
    them back on every boot and only reaches the log. Assert the call itself
    succeeds, which is what actually distinguishes the two.
    
    ---------
    
    Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
  • fix(hwid): serialize the device-limit write with its trim (#6591)
    setClientLimitHwidByEmail wrote clients.limit_hwid and then trimmed client_hwids as two independent statements. A traffic-cycle Save that read the record before the limit changed could write the stale value back after it, and a failed trim committed the new limit anyway.
    
    Both halves now run inside runSerializedTx, the transaction the traffic writer already owns. setClientLimitHwidByEmailTx and clearClientHwidsBySubIDTx refuse a handle that is not that transaction (errClientHwidWriteNotSerialized) instead of falling back to the shared handle. Client delete moves onto the same writer, and BulkCreate withdraws a re-created client's tombstone before applying its optional HWID limit.
    
    TestSetClientLimitHwidIsSerializedWithSyncInbound holds a stale traffic-cycle Save open across the limit change and fails without the serialization (limit_hwid = 5, want 1).
  • fix(ip-limit): append fail2ban lines only after the scan commits (#6590)
    updateInboundClientIps wrote the [LIMIT_IP] lines that drive the jail
    while the scan's transaction was still open, and marked the addresses in
    bannedSeen at the same time. A commit failure after that point rolls the
    database back but takes nothing back from the log: fail2ban proceeds to
    ban addresses the panel never recorded, and the in-memory bannedSeen
    entry makes the next scan skip them, so the rollback is never repaired.
    
    Selection stays inside the transaction. processObserved now collects one
    pendingBan per enforced client and publishes after the commit succeeds,
    disconnecting only the clients whose lines actually reached the log. The
    Xray disconnects already ran after the commit for the same reason.
    
    Recording moved with the write rather than with the decision:
    selectAdvancedSinceLastBan no longer mutates anything, and
    recordBannedSeen runs once a line is on disk. It also runs for clients
    with nothing to ban, because that is the pass that forgets addresses a
    client no longer exceeds its limit with - pruning used to be a side
    effect of the filter, and skipping it left a stale entry that suppressed
    the next legitimate ban.
    
    The log file is opened once per scan instead of once per client, the
    write error is checked instead of discarded, and Close is reported.
    
    updateInboundClientIps no longer reports shouldCleanLog, because the
    only thing that set it was the ban branch that moved out; processObserved
    sets it when a publication actually happens. disAllowedIps went with the
    write it served.
    
    Tests: a transaction failed at COMMIT through a deferred foreign key
    leaves no line and no bannedSeen entry; a publication that cannot open
    the log leaves the address retryable; a client returning under its limit
    has its entry forgotten, so going over again is banned a second time; a
    committed over-limit scan publishes and reports; and writeBanLines
    surfaces a write error rather than swallowing it.
  • fix(panel): validate sponsor logo name before any file or network use
    The public /sponsors/logo/:name route only accepted names matching an
    active sponsor's logo, which was already regex-filtered, but that guard
    was indirect. Checking sponsorLogoRe on the name itself makes the
    path/URL safety local and clears CodeQL alerts #113 (go/request-forgery)
    and #114 (go/path-injection).
  • feat(panel): add sponsor slots fed from sponsors.sanaei.dev
    Monthly sponsor placements need to change without cutting a panel
    release. Panels now read 3X/sponsors.json from the MHSanaei/sponsors
    repo (GitHub Pages on sponsors.sanaei.dev) and show active sponsors in
    four slots: an overview banner, a rotating sidebar card (max three), the
    login page and a new Sponsors page that also lists open placements.
    
    An entry shows only while enable is not false and until is in the
    future; links must be https and logos are png/webp/jpg by name only.
    The list is cached for an hour and the last good copy survives upstream
    failures; logos are proxied through /sponsors/logo/:name with failures
    cached, so CSP stays 'self' and admin browsers never reach a third
    party. Admins can hide a slot for 24h. Under XUI_DEBUG the panel reads
    a sibling ../sponsors/3X checkout so edits can be previewed before push.
  • fix(nodes): stop a restarting panel from reporting itself as down
    Adding a node fails right after that node's panel restarts. nodes/add
    probes the node's /panel/api/server/status first, and that endpoint
    returns whatever the @2s ticker last sampled - nil until the first tick
    lands, so the master reads a healthy panel as unreachable and rejects it
    with "Add node (remote returned success=false: )", an error whose
    message is empty because the node answered success with a null obj.
    
    The window is far wider than one tick: GetStatus resolved the public
    IPv4/IPv6 addresses inline and held s.mu across every lookup, so a box
    with no IPv6 route spent 3s per service - about 15s of nil status after
    each restart, and the same stall on a fresh panel's first sample.
    
    - status now answers from CurrentStatus, which samples on demand when
      the ticker has not run yet instead of returning a null obj
    - the public-IP lookups run in the background and outside s.mu, so a
      status sample never waits on them
    - probe tells "no status yet" apart from a genuine success=false, so the
      master's error says something when it meets an older node
  • fix(nodes): say which half of node mTLS failed, and say it as an error (#6565)
    * fix(nodes): say which half of node mTLS failed, and say it as an error
    
    A configured client CA bundle that will not parse produced the same
    warning as a settings read that failed, and both read as though mTLS
    were merely unavailable. It is not: the node API silently stops
    accepting client certificates, callers fall back to a bearer token or
    lose their only credential, and the one line saying so is a warning at
    boot.
    
    Report it at error level, and distinguish the two causes rather than
    attributing a storage fault to the operator's certificate bundle.
    NodeMtlsClientCAPool now tags the parse failure with
    ErrNodeMtlsTrustBundleInvalid; its message text is unchanged, so
    anything matching on the existing string still matches.
    
    Startup is deliberately left alone. Refusing to boot was considered and
    rejected: the bundle is one of two equal credentials here, a panel that
    will not start takes the proxies and the subscription server with it,
    and bundles written before the stricter validation landed in #6188 are
    already stored, editable only through the panel that would no longer
    come up.
    
    The tests pin the tag on an unusable bundle and its absence on an unset
    one; without the tag the first goes red.
    
    * test(nodes): drop a duplicate node mTLS trust-bundle test
    
    TestNodeMtlsClientCAPoolLeavesUnsetBundleUntagged asserted only that an
    unset nodeMtlsClientCAPem yields (nil, nil). That path returns before the
    line the sentinel change touched, so the test was green with and without
    ErrNodeMtlsTrustBundleInvalid, and TestNodeMtlsClientCAPool already pins
    the same two assertions on the same fixture. A test that passes either way
    certifies nothing and then gets cited as coverage for the sentinel.
    
    TestNodeMtlsClientCAPoolTagsAnInvalidBundle, which does go red without the
    sentinel, stays as the regression guard.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(tgbot): localize QR caption via I18nBot (#6564)
    * fix(panel): accept 2FA codes from adjacent TOTP windows
    
    CheckUser compared only gotp.Now(), so a code submitted at the end of
    its 30s window (or with slight client/server clock drift) failed with
    'invalid 2fa code', while the immediate retry in the next window
    succeeded. Accept current +/-1 window, the standard TOTP skew
    tolerance.
    
    Fixes MHSanaei/3x-ui#6535
    
    * fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode
    
    Move the +/-1 window helper to internal/util/totp so both 2FA
    acceptance points use it: login (CheckUser) and disable/rebind plus
    username/password changes (VerifyTwoFactorCode). Also shrink comments
    to the 2-line house rule and anchor the unit test mid-window to avoid
    a step-boundary flake.
    
    Addresses review on #6546 (MEDIUM + 2 LOWs).
    
    * fix(tgbot): localize QR caption via I18nBot
    
    sendClientQRLinks hardcoded English 'QRCode for client <email>:',
    bypassing I18nBot, so non-English bot languages (e.g. ru-RU) still
    got English. Add tgbot.answers.qrCodeForClient key with Email param
    in all 13 locales and route the caption through I18nBot.
    
    Fixes MHSanaei/3x-ui#6562
    
    * fix(tgbot): repair locale JSON syntax, harden QR i18n test
    
    - Add missing separators so all 13 locale files parse again.
    - Rewrite the regression test to read the real shipped files
      (fails on malformed JSON or missing key).
    - Add TestTgbotLocalesQrKeyValid covering every locale file.
    
    * chore(tgbot): drop QR caption tests that cannot catch the bug
    
    TestQRCodeForClientLocalizes never calls sendClientQRLinks: it registers
    two messages in a synthetic bundle and asserts on I18nBot, a passthrough
    to go-i18n. With the tgbot_client.go line reverted to the hardcoded
    English caption, both it and TestTgbotLocalesQrKeyValid still pass, so
    neither certifies the fix.
    
    The malformed-locale class they were added for is already pinned twice:
    the discord package's TestMain loads every translation file through
    locale.InitLocalizer and panics on invalid JSON, and
    frontend/src/test/i18n-dead-keys.test.ts parses all 13 locales and
    checks each carries the en-US key set. Both go red on the #6564 syntax
    error this PR first shipped.
    
    ---------
    
    Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): send stable X-HWID on external subscription fetch (#6567)
    * fix(panel): accept 2FA codes from adjacent TOTP windows
    
    CheckUser compared only gotp.Now(), so a code submitted at the end of
    its 30s window (or with slight client/server clock drift) failed with
    'invalid 2fa code', while the immediate retry in the next window
    succeeded. Accept current +/-1 window, the standard TOTP skew
    tolerance.
    
    Fixes MHSanaei/3x-ui#6535
    
    * fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode
    
    Move the +/-1 window helper to internal/util/totp so both 2FA
    acceptance points use it: login (CheckUser) and disable/rebind plus
    username/password changes (VerifyTwoFactorCode). Also shrink comments
    to the 2-line house rule and anchor the unit test mid-window to avoid
    a step-boundary flake.
    
    Addresses review on #6546 (MEDIUM + 2 LOWs).
    
    * fix(sub): send stable X-HWID on external subscription fetch
    
    A Master panel fetching a donor subscription sent no X-HWID, so an
    HWID-limited donor rejected it with 404. Identify this panel with a
    stable per-installation id (persisted in settings), occupying exactly
    one donor device slot.
    
    Fixes MHSanaei/3x-ui#6559
    
    * fix(sub): address review on external X-HWID
    
    - Serialize first-time id creation with a mutex so concurrent
      first fetches cannot mint two UUIDs.
    - Fix goimports grouping for the new third-party import.
    - Add externalSubSendHwid opt-out (default send); document it.
    - Cover header send/omit with httptest in TestFetchSendsStableHwid.
    
    * fix(sub): drop the SQL-only X-HWID opt-out
    
    The externalSubSendHwid opt-out added in 227ed818 had no settings
    field, CLI flag or docs, so an operator could only reach it by editing
    the settings table by hand, while every cache-miss fetch paid a query
    for it. CLAUDE.md rules out config knobs on a one-header fix.
    
    Also drop the test assertions that only restated the 3x-ui-server-
    prefix constant; TestFetchSendsStableHwid still goes red without the
    header.
    
    ---------
    
    Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(hosts): add a cipher suites override and accept custom suites
    The inbound TLS form offered cipherSuites as a closed single-choice list,
    but xray reads the value as a colon-separated list and accepts any name Go
    knows, so several suites or one missing from the list could not be set.
    Both the inbound and the new host field now use a tag picker that keeps
    the stored value as the colon-joined string xray expects; old single
    values open unchanged.
    
    A host's cipher suites replace the inbound's in the JSON subscription
    stream, and a blank field inherits them. Share links and Clash carry no
    cipher suite parameter, so their output is unchanged.
  • fix(clients): list HWID devices when the HWID limit is 0
    EnforceHwidForSubID returned before recording anything when a sub had no
    limit, so the panel's HWID Devices list stayed empty for every unlimited
    client. Devices are now upserted on the (sub_id, hwid_hash) index without
    enforcement or X-Hwid-* headers; the write is best-effort and only logs on
    failure, so tracking can never deny a subscription nothing restricts.
  • fix(logger): fix data race in InitLogger
    Replace the package logger variable with an atomic.Pointer so InitLogger swapping the handle no longer races with concurrent Debug/Info/Warning/Error calls from other goroutines. Also guard fileRotate with a mutex, and add a regression test that reproduces the race under concurrent logging.
  • feat(sub): redesign the subscription page around usage, tabs and app imports
    The info page was a long key/value table followed by every link and two
    app dropdowns, and it rendered left-to-right even for Persian and Arabic.
    It now leads with a usage ring, the remaining quota and a stats grid, and
    splits the rest into Subscription / Apps / Configs tabs.
    
    - Status tells expired, data-used-up and disabled apart instead of one
      "Inactive", replacing the hard-coded English expiry chip.
    - The Apps tab keeps every Android and iOS app with its existing deep
      link, preselects the visitor's platform and adds Windows: Hiddify and
      Clash Verge Rev import directly, v2rayN copies the link.
    - fa-IR and ar-EG render right-to-left; URLs, IDs and sizes stay LTR.
    - The footer shows the support link and the client refresh interval, so
      subPageContext now carries subUpdates (also in ?format=info).
    - Status, days-left and app deep-link logic lives in subPageModel.ts,
      with unit tests pinning the deep links the page already shipped.
  • fix(outbounds): keep subscription tags on their server when reality params rotate
    A subscription outbound's tag must stay bound to the upstream server it
    was assigned to for as long as that server stays in the subscription;
    balancers and routing rules select by that tag.
    
    The identity used to recognise a server across refreshes included every
    query parameter. A 3x-ui upstream picks a random shortId and SNI of a
    reality inbound on every request (older releases a random spiderX too),
    so no reality link was ever recognised, the stable-tag reservation never
    engaged, and every tag was handed out by list position. Removing or
    inserting a server then re-pointed existing tags at other servers:
    sub-germany carried France, sub-sweden Germany, and Sweden became
    sub-sweden-1. The identity now ignores sid, sni and spx when
    security=reality, since none of them selects the server. TLS sni still
    counts: it can pick the backend behind a shared front.
    
    Two more paths broke the same rule:
    - A link repeated in one body (same identity, different remark) shared a
      single link_identities key, so both tags gained a -N suffix on every
      refresh. Repeats are now numbered.
    - Links the core rejects were dropped after tagging, so the stored list
      that drives positional reuse was shorter than the parsed one and a
      rotated server behind a dropped link took its neighbour's tag. The
      filter now runs first; a dropped link's warning names its remark
      instead of a tag it never used.
    
    A mapping an older build already swapped stays swapped: its stored
    identities no longer match, so positional reuse reproduces it. Deleting
    and re-adding the subscription reallocates the tags from the remarks.
    
    Closes #6556
  • feat(clients): filter the client list by clicking a summary stat card
    Each card on the Clients page now toggles its status bucket as the sole
    filter, and the Clients card clears it. The bucket filters used to be
    wider than the card counts: "active" still included clients near
    depletion and "deactive" included disabled clients that had run out, so
    a filtered list could disagree with the number on the card. Both filters
    now reuse the summary expressions, and a test pins each card's count to
    the size of its filtered list.
  • fix(sub): prevent default profile page URL disclosure (#6538)
    * fix(sub): prevent default profile page URL disclosure
    
    Add explicit none, builtin, and custom profile page modes.
    Preserve existing custom URLs and warn before exposing the built-in page.
    Cover mode selection, legacy settings, and subscription response headers.
    
    * fix(subscription): add profile page link options and upgrade notes
  • fix(ldap): apply LDAP enable, disable and cleanup through the bulk paths
    The LDAP sync enabled, disabled and detached clients one at a time. Each
    per-client call locked the inbound and pushed to its node under that lock
    with a 4s timeout, so users sharing an inbound on a node that answers its
    status probe but hangs on client writes queued one push timeout apiece:
    five users took 20s in the test, and hundreds of directory users behind a
    hung node stretched one run over hours. Each changed email was also queued
    once per configured tag, repeating a no-op lookup for every extra tag.
    
    Enable and disable now go through BulkSetEnable, and the cleanup through
    one BulkDetach per inbound: each inbound is locked, written and pushed
    once, and its push stops at the first failure for the reconcile to finish.
    The same five users now cost a single push timeout.
  • chore(node): cover the sync tick's online prune from the job package
    The traffic sync's call that drops online sets of nodes it no longer
    fetches had no test: a job-package test cannot install an xray process,
    so online state was invisible there and removing the call passed.
    
    SetXrayProcessForTest installs a test process for tests in other packages,
    the same kind of seam as Manager.SetRuntimeOverride. The new job test runs
    a real tick with a disabled node and a deleted one and fails without the
    call.
  • fix(node): release a deleted node's metric series and HTTP client
    Deleting a node must free what the master keeps per node in memory.
    
    Delete dropped the node's cpu and mem series but not netUp and netDown,
    which the heartbeat records too, so each deleted node leaked two tiered
    histories. It now drops every NodeMetricKeys entry.
    
    InvalidateNode, called on node edit, disable and delete, cleared only the
    cached Remote. The pooled HTTP client and its transport stayed cached until
    a later call for the same node pruned them, which a deleted node never
    makes. InvalidateNode now drops those too, outside the manager lock; an
    edited node pays one fresh handshake on its next call.
  • perf(node): sync up to 32 nodes at once, like the heartbeat
    The traffic sync is scheduled every 5s but synced only 8 nodes at a time,
    each needing four to seven sequential requests. Past about 125 nodes 80ms
    away a tick outlasted its interval, so dashboard traffic, online clients
    and quota enforcement moved at a fraction of the intended cadence.
    
    Measured with 150-300 fake nodes over real HTTP, 80ms latency, a dashboard
    connected and client-IP sync on:
    
      SQLite, 300 nodes        8: 25-30s   16: 14-16s   32: 6-9.5s
      SQLite, 150 (20% slow)   8: 24-27s   16: 13-14s   32: 6-7.5s
      Postgres, 150 nodes      8: 13-18s   16: 7.5-10s  32: 6.5-8.3s
    
    No database-locked, pool or writer-queue errors at any setting, and the
    merged inbound and client traffic counts matched. Postgres's one-off
    adoption tick is slower at 32 than at 16 (16.5s vs 9.7s) as goroutines
    wait on its 25-connection pool; steady ticks are fastest at 32.
  • fix(traffic): reset due inbounds and clients concurrently
    The periodic reset job reset every due inbound, then every due client, one
    at a time, and each waited on its node: up to 10s per node inbound, and 4s
    per attached node inbound for a client. A few hanging nodes stretched a
    single run over hours.
    
    Both loops now run eight at a time. With the per-client fan-out of four
    that stays within the 32 concurrent node calls the other node fan-outs use.
  • fix(node): send one alert for a burst of node transitions
    A master-side network blip flips every node in one heartbeat tick, and
    each node published its own node.down, then node.up. A notifier queue holds
    64 events and the rate limiter keys on the node name, so with 150 nodes most
    alerts were dropped and the rest ran into Telegram and Discord limits.
    
    Past five same-direction transitions in one tick the heartbeat publishes a
    single event per direction naming the nodes (the first ten, sorted, then
    +N). Smaller ticks keep per-node events with their health data, and the
    notifiers already read the node name from Source, so no formatter changed.
  • fix(node): fan out operations that call every node
    An operation that calls every node has to finish inside the panel's 30s
    write timeout. Reset all traffic, UpdatePanels and bulk inbound delete
    walked the nodes one at a time, up to 10s per hanging node, so 15 hanging
    nodes out of 150 kept each request running for 2m41s while the browser
    had already been told it failed.
    
    All three now fan out through fanoutInboundResults, bounded by
    nodeFanoutConcurrency (32, the heartbeat's bound), and UpdatePanels keeps
    its results in request order. Bulk delete still removes the rows one at a
    time, since each rewrites shared routing references, and only fans out the
    node pushes that delInbound now hands back.
  • fix(node): drop online clients and sub-nodes of nodes no longer synced
    What the master derives from a node's reports (online clients, active
    inbounds, learned sub-nodes) must live only while that node is still
    synced; ClearNodeOnlineClients states it: a downed node must not keep its
    clients listed as online.
    
    Only a failed snapshot fetch cleared the online set, and only a failed
    probe cleared sub-nodes. A disabled node (both jobs skip it), a node marked
    offline before the sync tick reached it, a deleted node, and a node whose
    snapshot fetched but failed to merge all kept their clients online in
    onlineClients, onlineByGuid and activeInbounds, which the dashboard and a
    parent master's /clients/onlines read. Disabled and deleted nodes also kept
    their sub-nodes on the Nodes page until the panel restarted.
    
    The traffic sync now keeps online sets only for enabled, online nodes in
    its list, the heartbeat keeps sub-nodes only for enabled listed nodes, both
    before the empty-list return, and a failed merge clears like a failed
    fetch. The sync job's one-line call has no job-level test: that package
    cannot install the xray process, so RetainSyncedNodeOnlineClients carries
    the tested rule.
  • fix(traffic): push depletion changes to nodes off the serial writer
    Node I/O on the traffic-accounting path must never stall accounting; the
    serial writer states it ("Keep network I/O (node pushes) OUT of fn").
    
    AddTraffic still applied the depletion UpdateInbound for every node
    inbound inside the writer closure, one at a time with context.Background.
    One hanging node held the single writer for each push, freezing traffic
    polls, node snapshot merges and every client edit for the whole wave; a
    client shared by 150 nodes expiring could hold it for tens of minutes.
    The opt-in restart on client disable then ran node by node on the same
    traffic job.
    
    Remote plans now leave the writer and go through nodePushPlan and the 4s
    nodePushContext, fanned out like client pushes: an offline or slow node
    defers to the reconcile its dirty flag already schedules. The node restart
    runs in its own goroutine, since nothing replays or waits on it.
    
    TestTrafficDisableImmediatelyUpdatesNodeRuntime called addTrafficLocked
    directly, which pinned the push inside the writer; it now calls AddTraffic
    and still requires the push to have landed on return.
  • fix(clients): keep a vless reverse client's handler across a re-add (#6558)
    * fix(clients): keep a vless reverse client's handler across a re-add
    
    RemoveUser also drops the client's reverse outbound handler, and the account
    every live remove/re-add path rebuilt carried no reverse at all: buildUserAccount
    read id/flow/testseed/testpre and nothing else. Editing, bulk re-enabling, quota
    renewal and adding a client to an existing inbound therefore left a reverse
    client able to connect but not to open its tunnel until Xray restarted, with
    nothing logged. A traffic reset is the route operators hit most, since a
    depleted client is removed and re-added on every renewal.
    
    buildUserAccount now carries the tag (it accepts either the settings JSON object
    or a typed client value), and the five account maps those paths build include
    the client's reverse. Core chain, read from the pinned xray-core:
    AddUserOperation -> User.ToMemoryUser -> vless.Account.AsAccount copies Reverse
    (proxy/vless/account.go:24), and GetReverse rebuilds the handler from the stored
    account's tag (proxy/vless/inbound/inbound.go:193-205).
    
    Each path has a test that fails without its fix; the account-level test fails on
    both input shapes.
    
    * refactor(clients): drop an account map helper nothing calls
    
    Local.AddClient and Local.UpdateUser are only reachable through runtime.Runtime,
    and all four call sites of those two methods sit in a node branch, where the
    runtime is a *Remote -- Remote.AddUser ignores the map and pushes the inbound
    snapshot instead. So the extraction and its test covered a path no deployment
    takes, the reverse key it added could never reach a core, and the previous
    commit's claim that the node-push paths go through it was wrong.
    
    The four account maps that do reach buildUserAccount are untouched. Reported by
    the PR review.
  • fix(node): push a node only the client IPs it hosts
    A master's per-node sync must scope what it sends to the clients that node
    serves, so its cost tracks the node and not the fleet. The global-usage
    push already did (node_client_traffics by node_id); the 10s client-IP push
    sent GetAllInboundClientIps, the whole table, to every node.
    
    Each node's MergeInboundClientIps then created a row for every foreign
    email, and its next GET clientIps echoed the whole fleet back. Its IP-limit
    job only ever reads rows for its own clients, so none of it was used. With
    150 nodes x 150 clients, one IP tick pushed 299 MB and pulled 264 MB, every
    node held 22,500 rows instead of 150, and sync ticks grew 3.8s -> 10.2s
    even at 1ms latency; the cost grows with the square of the fleet.
    
    Both pushes now share nodeHostedEmails. After the change the same fleet
    moves 2.0 MB / 1.8 MB per tick and ticks stay near 3.2s. Nodes upgraded
    with foreign rows shed them within 30 minutes via pruneStaleIpRows.
  • fix(xray): stop a lone dns qType 0 from matching every query
    The core reads a dns rule's qType as a PortList, which drops a bare numeric
    0 (infra/conf/common.go: `if number != 0`), and a rule with no qTypes
    matches every query. A stored `"qType": 0` therefore does not target query
    type 0: it drops, refuses or hijacks all DNS through that outbound.
    
    A qType the panel writes has to be read by the core as exactly the query
    types it names. Four writers broke that:
    
    - DNSOutboundLegacyKeysFix rewrote a lone blockTypes [0] into "qType": 0,
      so "block type 0" became "block everything" on upgrade.
    - That seeder shipped in v3.8.0 and is recorded as done, so fixing it does
      not reach installs that already ran it. DNSOutboundQTypeZeroFix spells
      any stored numeric qType 0 as "0" once, protocol id matched like the core.
    - The outbound form adapter turned a typed "0" into the number 0.
    - The Xray template editor saves raw JSON past that adapter; the save now
      applies the same rewrite.
    
    Each writer is pinned by a test that fails without its part. The rewrite
    and the repair compare policies as the pinned core builds them, and the
    repair runs through runSeeders over a database whose legacy-keys seeder
    already ran, on SQLite and PostgreSQL 16.
  • fix(ports): refuse an inbound on a port an AmneziaWG peer forwards (#6554)
    * fix(ports): refuse an inbound on a port an AmneziaWG peer forwards
    
    checkForwardedPortsConflict only ever ran from the AmneziaWG save path, and only
    in one direction: an AmneziaWG client's forwardedPorts were checked against the
    ports other inbounds already hold, while the reverse -- an ordinary inbound
    saved onto a port some peer forwards -- had no guard at all. The forward
    listener binds that port on every interface in both directions
    (amneziawgnet/portfwd.go's attachTCP/attachUDP), so the two listeners want the
    same socket: the loser either leaves the peer's forward silently dead or fails
    the inbound's listen.
    
    checkPortConflictTx now resolves that owner the same way the relay-slot checks
    do -- same host, peers derived from the stored settings with the shared
    InstanceFromInbound -- and names the peer in the refusal. Sitting inside
    checkPortConflictTx covers both the save and the enable path added in #6549.
    
    TestAddInboundRefusesAPortAnAmneziaWGPeerForwards fails without this -- watched
    red, the create is allowed -- and its node-row companion pins the scoping that
    keeps a node row legal on a locally forwarded port.
    
    * fix(ports): name only a peer that binds as the owner of a forwarded port
    
    The owner lookup read instance.Peers and ForwardedPortsInclude directly, so a
    peer the forward supervisor skips (no email, or no address the tunnel routes
    to) was reported as holding a port nothing binds -- refusing a create that is
    legal with a message naming a row whose own port is its WireGuard one. It also
    repeated the candidate's listen address as the forward's location, though the
    forward binds :port on every interface.
    
    Share the supervisor's own gate through amneziawgnet.ForwardedPortOwner, report
    the wildcard bind, and propagate a failed owner query instead of reading it as
    "no conflict", matching the sibling checks in the same file.
    
    * style(ports): keep the forwarded-key doc block within the 2-line cap
    
    The reworded desiredPortForwardKeys doc ran to three lines, against the rule
    this repo sets for committed Go comments.
  • fix(limit-ip): leave a reverse client out of the temporary disconnect (#6553)
    * fix(limit-ip): leave a reverse client out of the temporary disconnect
    
    The LIMIT_IP cycle removes the client and adds it back 100 ms later. For a vless
    client carrying a reverse config that is not reversible: RemoveUser calls
    RemoveReverse and deletes the client's outbound handler, while the account added
    back is built without the reverse field, so the tunnel stays down until Xray
    restarts and the core's forward-proxy guard for that client no longer fires
    (proxy/vless/inbound/inbound.go:245 and :542-544 at the pinned core). The cycle
    now skips such a client and says so, instead of trading a limit violation for a
    tunnel that needs a restart to come back.
    
    TestDisconnectClientTemporarilySkipsReverseClient fails without this -- watched
    red, the client is removed and re-added -- and asserts the skip is logged rather
    than silent.
    
    * style(limit-ip): keep the reverse-client comment within the 2-line cap
    
    The block explaining why a reverse client is skipped was three lines, against
    the rule this repo sets for committed Go comments; the same why fits in two.
  • fix(panel): accept 2FA codes from adjacent TOTP windows (#6546)
    * fix(panel): accept 2FA codes from adjacent TOTP windows
    
    CheckUser compared only gotp.Now(), so a code submitted at the end of
    its 30s window (or with slight client/server clock drift) failed with
    'invalid 2fa code', while the immediate retry in the next window
    succeeded. Accept current +/-1 window, the standard TOTP skew
    tolerance.
    
    Fixes MHSanaei/3x-ui#6535
    
    * fix(panel): share TOTP skew tolerance with VerifyTwoFactorCode
    
    Move the +/-1 window helper to internal/util/totp so both 2FA
    acceptance points use it: login (CheckUser) and disable/rebind plus
    username/password changes (VerifyTwoFactorCode). Also shrink comments
    to the 2-line house rule and anchor the unit test mid-window to avoid
    a step-boundary flake.
    
    Addresses review on #6546 (MEDIUM + 2 LOWs).
    
    ---------
    
    Co-authored-by: sdhfsl <sdhfsl@users.noreply.github.com>
  • fix(xray): restart when a diff strands a client's live session (#6550)
    * fix(xray): restart when a diff strands a client's live session
    
    Disabling or deleting a client took it out of the generated config and the
    hot path applied that with AlterInbound/RemoveUser, which only drops the
    credential (vless, vmess, trojan and shadowsocks all keep the established
    session running) -- so the panel showed a disabled client whose connection
    kept passing traffic, and the core offers no API to close one session.
    
    A diff that removes a user without re-adding the same email under the same
    tag is that case: honour the operator's restart-on-client-disable setting and
    let the caller replace the process, which is already how an auto-disabled
    client loses its session. An edit re-adds the email and keeps the hot path.
    
    * chore(i18n): cover manual disable and delete in the restart-setting description
    
    The setting now also decides what happens when a client is disabled or deleted
    by hand, so the description cannot keep naming only the automatic path. All 13
    locales updated in the same commit to keep the wording consistent.
    
    * fix(xray): reach the guard from the manual switch and from every protocol
    
    Round-1 findings on this PR. The guard sat in tryHotApply, but a manual disable
    or delete applies through runtime.Runtime and finishes with needRestart false,
    so none of the three RestartXray schedulers fired and the predicate was never
    reached: the session in #6533 kept flowing. The apply layer now asks for the
    restart the setting promises when the client actually leaves the config, on the
    single-client update and delete paths and on bulk disable, and only for local
    inbounds so a node row cannot make the master restart its own core.
    
    The predicate itself could not fire for shadowsocks or hysteria either, because
    RemovedUsers is only produced for the protocols diffInboundUsers will diff. The
    diff now also compares settings.clients of an inbound present in both configs,
    which is the one shape every account list shares, so those protocols reach the
    guard through the inbound instead of through nothing.
    
    TestManualClientDisableHonoursRestartSetting fails without the apply-layer fix
    ("needRestart = false, want true" with the setting on) and
    TestHotDiffDropsUsersOnProtocolsItCannotDiff fails without the diff fix -- both
    watched red. The two three-line comments this PR added are back inside the cap.
    
    * docs(i18n): stop scoping restartXrayOnClientDisable to auto-disable
    
    The setting now covers a client disabled or deleted by hand as well, so its
    title no longer says "Auto" in all 13 locales, and the docs callouts in en, ru,
    zh and fa describe the same behaviour instead of the auto-only one.
  • docs(limit-ip): correct what the temporary disconnect can actually do (#6551)
    * docs(limit-ip): correct what the temporary disconnect can actually do
    
    The comment claimed removing and re-adding a user "disconnect[s] all
    connections". RemoveUser only clears the core's credential validator in vless,
    vmess, trojan, shadowsocks and hysteria alike, so a session already up keeps
    running and the fail2ban ban on the logged IP is what ends the traffic. Comment
    only: the protocol gate and its test are untouched.
    
    * docs(limit-ip): say what the disconnect cycle really does per protocol
  • perf(nodes): reuse one pooled client per node instead of rebuilding it (#6548)
    * perf(nodes): reuse one pooled client per node instead of rebuilding it
    
    The heartbeat probe asks for a client every 5s per node, and for skip, pin and
    mtls modes HTTPClientForNode built a client with its own transport each time:
    every tick paid a full TCP+TLS handshake per node, which is the CPU a 100-node
    fleet reports. Cache the client per node identity, close the previous one when
    that identity changes, and raise the idle pool caps above any real fleet size
    so a node's connection survives to its next tick.
    
    * perf(nodes): keep one client per node in the pooled cache
    
    Round-1 findings on this PR. The eviction dropped only entries whose key did not
    start with the current identity, so every proxy variant of that identity stayed
    for the life of the process. That variant is often a fresh loopback port:
    withOutboundBridge mints one per call and tears the bridge down on return, so
    each operator "test node" or remote-inbounds action added a client whose key can
    never be hit again, and a node switched to verify mode orphaned its old entry by
    returning before the loop. Replacing that filter with one entry per node bounds
    the cache at the fleet size, and the verify-mode return now clears the node too.
    
    TestHTTPClientForNodeKeepsOneClientPerNode fails without this -- watched red,
    "2, want 1" -- and pins the verify-mode cleanup on the same cache.
    
    * style(nodes): keep the eviction comment inside the two-line cap
  • fix(inbounds): check ports when an inbound is enabled, not only when it is saved (#6549)
    * fix(inbounds): check ports when an inbound is enabled, not only when it is saved
    
    The save-time guards compare enabled rows, so a row could be created while
    another disabled row held its port and only collide once the disabled one was
    switched on. Run the same checks before the flag moves: the refusal names the
    row that owns the port, the flag is left alone, and tcp/udp coexistence and
    node rows keep working.
    
    * docs(inbounds): state the real reason the enable path needs its own check
  • fix(xray): refuse a config the running core cannot bind (#6547)
    * fix(xray): refuse a config the running core cannot bind
    
    RestartXray stopped a working core before handing it a config whose listens
    collide, so the failed bind exited the whole process (main/run.go:94) and the
    one-second watchdog retried it in a loop: every protocol down, cause only in
    the logs. The save-time port guards cannot cover this -- SetInboundEnable, the
    AmneziaWG relay created on the first peer, template and bridge edits all reach
    a colliding config with no guard on that path.
    
    Probe the generated config at the single restart funnel instead. Collisions the
    running core already serves are excused, so an established setup is never
    refused by a static read being wrong about it, and the port-bucketed pass costs
    nothing on a clean config.
    
    * fix(xray): surface a refused config and re-key the bind excuse set
    
    Round-1 findings on this PR. Refusing the swap left the running core on its
    previous config with nothing but a log line to show for it, so the status
    response now carries the reason while the core runs and the overview marks it;
    the node list picks the same field up through that response. The excuse set is
    keyed on the two listens, the port and the shared transports instead of the tag
    pair, so a pair whose listen moves onto the other's address is refused again,
    while the same two sockets stay excused however the generator orders them.
    
    TestBindConflicts/excused_pair_whose_listen_changed_into_a_real_collision fails
    without the key change -- watched red first.