Commit Graph
317 Commits
  • feat: customizable subscription page templates (#5079)
    * feat: add support for subscription-based outbounds with auto-update
    
    - New OutboundSubscription model (full support on both SQLite and PostgreSQL)
    - Go subscription link parser (vmess/vless/trojan/ss/hysteria2/wireguard) matching frontend behavior
    - Stable tag assignment across refreshes (designed for balancer + routing use)
    - Runtime merge of subscription outbounds into Xray config (additive only)
    - Full CRUD + manual refresh + preview API
    - Background auto-update job (per-subscription interval)
    - Frontend management UI in Outbounds tab (Subscriptions drawer) + tag integration in balancers/routing rules
    - Proper dual-database support including CLI migration path
    
    Review & hardening notes:
    - Fixed merge logic bug that could drop manual outbounds
    - Added SSRF/private-IP protection on subscription URLs using SanitizePublicHTTPURL
    - Improved update interval UX (hours + minutes)
    - Auto-fetch on first subscription creation
    - Added detailed comments on tag stability strategy and balancer implications when servers are added/removed/rotated
    - Updated migrationModels() for CLI migrate-db support
    
    * fix: resolve frontend lint/type errors and Go build break
    
    Frontend (eslint + tsc clean):
    - Destructure subscriptionOutboundTags prop in RoutingTab and
      BalancersTab. It was declared in the interface and used in useMemo
      but never destructured, so it resolved as an unresolved global
      (react-hooks warning + tsc "Cannot find name"). The prop is passed
      by XrayPage, so the feature was silently inert.
    - OutboundsTab: remove unused useEffect import, add an OutboundSub
      type to replace any[] state and the any/any table render signature,
      type the subscriptionOutbounds cast, and replace unused catch (e)
      bindings with parameter-less catch. Also type HttpUtil.post as
      OutboundSub so r.obj?.id type-checks.
    
    Backend (go build clean):
    - outbound_subscription_job: websocket.MessageTypeXray is undefined;
      use the existing MessageTypeOutbounds since the job refreshes
      outbound subscriptions.
    
    * fix(xray): make outbound subscription creation work end-to-end
    
    - Correct API paths from /panel/xray/outbound-subs to
      /panel/api/xray/outbound-subs. The controller is mounted under
      /panel/api, so the old paths hit the SPA page route (GET-only)
      and 404'd on POST.
    - Send the create-subscription body as a plain object instead of
      URLSearchParams. The axios request interceptor serializes bodies
      with qs.stringify, which can't read URLSearchParams' internal
      storage and produced an empty body, so the backend rejected it
      with "subscription URL is required".
    - Use message.useMessage() + context holder instead of the static
      antd message API (resolves the "Static function can not consume
      context" warning), matching XrayPage's pattern.
    - Migrate the subscriptions Drawer to antd v6 props: width -> size,
      destroyOnClose -> destroyOnHidden, and Space direction -> orientation.
    
    * feat(xray): show traffic/test for subscription outbounds; harden + test the feature
    
    Display (the reported issue):
    - Replace the flat read-only pills with a proper read-only table (desktop)
      and cards (mobile) in a new SubscriptionOutbounds component, showing
      Address, Protocol, Traffic (matched by tag — already collected by Xray),
      and a Test button with Latency. No edit/delete/move (read-only).
    - Test subscription outbounds via the existing /testOutbound endpoint, with
      results keyed by tag (subscriptionTestStates + testSubscriptionOutbound in
      useXraySetting, wired through XrayPage). Generalize isTesting/testResult to
      a string|number key so the same helpers serve index- and tag-keyed states.
    
    i18n:
    - Replace all hardcoded English subscription strings with t() calls and add
      pages.xray.outboundSub.* keys to en-US.json (other locales fall back).
    
    Backend hardening + tests:
    - xray.go: drop the tautological `subSvc != nil` check.
    - outbound_subscription: re-validate every redirect hop against private/
      internal addresses (CheckRedirect) and cap the redirect chain, closing an
      SSRF gap where only the initial host was checked.
    - Extract assignStableTags as a pure function and add unit tests for tag
      stability and SSRF rejection (the feature previously had no tests).
    
    Misc:
    - gofmt util/link/outbound.go (it was not gofmt-clean).
    
    * fix(xray): make outbound-subs feature pass CI (test compile, route docs, openapi)
    
    - outbound_test.go: remove unused `inner`/`lines` variables that broke the
      `util/link` test build (declared and not used).
    - Document the 7 outbound-subscription routes in endpoints.ts (list, create,
      update, delete, del alias, refresh, parse) so TestAPIRoutesDocumented passes.
    - Regenerate frontend/public/openapi.json (npm run gen) to include the new
      endpoints, satisfying the codegen freshness check.
    
    * feat(xray): per-subscription allow-private, gap-filled tags, UI tweaks, delete refresh
    
    Backend:
    - Add a per-subscription AllowPrivate flag (default off). Create/Update/refresh
      and the redirect check sanitize the URL with it, so localhost/LAN sources work
      only when explicitly opted in; the SSRF guard still blocks private targets by
      default. Controller reads the allowPrivate form field on create/update/parse.
    - Default outbound tag prefix now uses the smallest free "subN-" number instead
      of the auto-increment id, so deleting a subscription frees its number for reuse
      (a fresh start gives sub1) while staying stable per subscription. Extracted a
      pure defaultPrefixNumber() with unit tests.
    - deleteOutboundSub now signals SetToNeedRestart so xray drops the outbounds.
    
    Frontend:
    - "Allow private address" toggle in the add form (sends allowPrivate).
    - Delete now refreshes the xray view immediately (no manual page reload).
    - Subscriptions manager opens as a centered Modal instead of a right-side Drawer.
    - Move Outbounds to a top-level sidebar item under Nodes (out of Xray Configs).
    - Collapse WARP/NordVPN into a "more" dropdown.
    - Document the allowPrivate param in endpoints.ts.
    
    * i18n(xray): translate outbound-subscription UI into all locales
    
    - Translate the pages.xray.outboundSub.* strings (and allowPrivate label/hint)
      into all 12 non-English locales, matching each file's existing terminology.
    - Remove the unused outboundSub.add ("Add subscription") key from every locale.
    
    * feat: add custom subscription page template support
    
    Allow panel admins to use a custom HTML template for the subscription
    page instead of the default React-based SPA.
    
    Changes
    -------
    
    Backend
    - web/service/setting.go: Add subThemeDir setting (default: empty)
      with a getter GetSubThemeDir().
    - web/entity/entity.go: Add SubThemeDir field to AllSetting.
    - sub/subController.go: In serveSubPage, before falling back to the
      embedded SPA, check if subThemeDir is set and the directory exists.
      Look for sub.html first, then index.html. Parse with Go html/template
      and execute, injecting all standard page variables as template context.
      On any parse/execute error, log and fall through to the default page.
    
      Two backward-compat aliases added to the template data map:
      - result  = links    (for tx-ui v2 templates using {{ range .result }})
      - jsonUrl = subJsonUrl
    
    Frontend
    - frontend/src/models/setting.ts: Add subThemeDir = '' to AllSetting.
    - frontend/src/pages/settings/SubscriptionGeneralTab.tsx: Add a Sub
      Theme Directory input in Subscription settings.
    
    Templates
    - sub_templates/README.md: Full authoring guide with all variables.
    - sub_templates/tx-ui/index.html: The tx-ui subscription page template
      migrated from v2 to v3 data shape.
    
    Credits
    -------
    Bundled tx-ui template from AghayeCoder: https://github.com/AghayeCoder/tx-ui
    
    * chore: regenerate OpenAPI schemas and types for custom sub-template feature
    
    * feat(xray): subscription manager — edit, reorder/priority, status, preview, refresh-all
    
    Backend:
    - Per-subscription Priority + Prepend: subscriptions are ordered by Priority and
      placed before (Prepend) or after the manual template outbounds in the merge, so
      a subscription server can become the default. New Move(up/down) endpoint
      re-normalizes priorities; merge split into prepend/template/append.
    - List now returns a derived OutboundCount and orders by priority, and strips the
      heavy LastFetchedOutbounds/LinkIdentities blobs from the list payload.
    - Create/Update accept the prepend flag; new subs append at the end of priority.
    
    Frontend (Outbound Subscriptions modal):
    - Edit existing subscriptions (reuses the form + Update endpoint).
    - Inline enable/disable Switch, Status column (OK / error tooltip), Outbounds
      count column, per-row refresh spinner, "Refresh all" button.
    - Reorder (move up/down) controls + a "Before manual outbounds" toggle.
    - Preview button: fetch+parse a URL via /parse without saving.
    - Document the move route + prepend param in endpoints.ts; regenerate openapi.json.
    
    * i18n(xray): translate new subscription-manager strings into all locales
    
    Add the prepend/prependHint, preview/previewEmpty, refreshAll, statusOk and
    toastUpdated keys to all 12 non-English locales, matching each file's terminology.
    
    * refactor(sub): harden custom template rendering, drop bundled tx-ui template
    
    Builds on the custom subscription page template feature.
    
    Rendering hardening (sub/subController.go):
    - Render the custom template into a buffer and only write the response on
      success. Previously template.Execute wrote straight to the ResponseWriter,
      so a mid-render failure left a partially-written body and then fell through
      to the default page, corrupting the response (superfluous WriteHeader).
    - Cache parsed templates keyed by path, invalidated by file mtime, so each
      subscription page load no longer re-reads and re-parses the file from disk;
      admin edits are still picked up automatically.
    - Verify the configured path is a directory (IsDir) and log a Warning when it
      is set but unusable / an Error when a template fails to parse, instead of
      silently falling back.
    - Expose two new template variables: subTitle and subSupportUrl.
    
    Cleanup:
    - Remove the bundled tx-ui template and all tx-ui / AghayeCoder references
      (including the result/jsonUrl v2-compat aliases); use a generic my-theme
      example path in docs/UI/translation.
    - i18n the "Sub Theme Directory" setting (en-US subThemeDir/subThemeDirDesc)
      instead of hardcoded English.
    - Fix README: expire is seconds (not ms), lastOnline is ms; correct the
      settings tab name; note templates are admin-provided, not bundled/deployed.
    
    Tests:
    - Add sub/subController_test.go covering loadSubTemplate: render, sub.html
      precedence, fallback cases, malformed template, and mtime cache invalidation.
    
    Verified end-to-end in Docker: custom template renders with all variables,
    all fallback paths return the clean default page (no corruption), and the
    mtime cache reflects live edits.
    
    * i18n(settings): translate subThemeDir into all locales
    
    Add the subThemeDir / subThemeDirDesc keys (Sub Theme Directory setting) to
    all 12 non-English locales, matching each file's existing terminology. They
    previously fell back to en-US.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
    Co-authored-by: Rqzbeh <rqzbeh@users.noreply.github.com>
  • feat(nodes): add distinct purple indicator when panel is online but Xray core failed (#5040)
    * feat(nodes): add distinct purple indicator when panel is online but Xray core failed
    
    Currently nodes only show binary online/offline based on panel API reachability.
    
    This adds a third state:
    - Green: panel reachable + Xray healthy
    - Purple pulsing dot + "Online (Xray Error)": panel API works (management actions still available) but the node Xray process is in error or stopped. Tooltip shows the remote xrayError.
    - Red: unreachable (unchanged)
    
    Backend now captures xray.state + xray.errorMsg from /panel/api/server/status heartbeats and probes.
    New fields on Node + NodeSummary, forwarded for transitive nodes.
    Frontend Zod + NodeList rendering + dedicated .xray-error-dot CSS (color #722ED1) + i18n key.
    
    Color chosen purple per feedback after initial implementation.
    
    Refs: worktree xray-failed-in-nodes
    
    * fix: remove invalid JSON comment causing CI failures
    
    * chore: regenerate OpenAPI schemas and types for xray error indicators
    
    * chore: regenerate examples and schemas for xray error indicators
    
    * chore: regenerate missing openapi.json examples
    
    * fix
    
    ---------
    
    Co-authored-by: Rqzbeh <rqzbeh@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat: add support for subscription-based outbounds with auto-update (#5037)
    * feat: add support for subscription-based outbounds with auto-update
    
    - New OutboundSubscription model (full support on both SQLite and PostgreSQL)
    - Go subscription link parser (vmess/vless/trojan/ss/hysteria2/wireguard) matching frontend behavior
    - Stable tag assignment across refreshes (designed for balancer + routing use)
    - Runtime merge of subscription outbounds into Xray config (additive only)
    - Full CRUD + manual refresh + preview API
    - Background auto-update job (per-subscription interval)
    - Frontend management UI in Outbounds tab (Subscriptions drawer) + tag integration in balancers/routing rules
    - Proper dual-database support including CLI migration path
    
    Review & hardening notes:
    - Fixed merge logic bug that could drop manual outbounds
    - Added SSRF/private-IP protection on subscription URLs using SanitizePublicHTTPURL
    - Improved update interval UX (hours + minutes)
    - Auto-fetch on first subscription creation
    - Added detailed comments on tag stability strategy and balancer implications when servers are added/removed/rotated
    - Updated migrationModels() for CLI migrate-db support
    
    * fix: resolve frontend lint/type errors and Go build break
    
    Frontend (eslint + tsc clean):
    - Destructure subscriptionOutboundTags prop in RoutingTab and
      BalancersTab. It was declared in the interface and used in useMemo
      but never destructured, so it resolved as an unresolved global
      (react-hooks warning + tsc "Cannot find name"). The prop is passed
      by XrayPage, so the feature was silently inert.
    - OutboundsTab: remove unused useEffect import, add an OutboundSub
      type to replace any[] state and the any/any table render signature,
      type the subscriptionOutbounds cast, and replace unused catch (e)
      bindings with parameter-less catch. Also type HttpUtil.post as
      OutboundSub so r.obj?.id type-checks.
    
    Backend (go build clean):
    - outbound_subscription_job: websocket.MessageTypeXray is undefined;
      use the existing MessageTypeOutbounds since the job refreshes
      outbound subscriptions.
    
    * fix(xray): make outbound subscription creation work end-to-end
    
    - Correct API paths from /panel/xray/outbound-subs to
      /panel/api/xray/outbound-subs. The controller is mounted under
      /panel/api, so the old paths hit the SPA page route (GET-only)
      and 404'd on POST.
    - Send the create-subscription body as a plain object instead of
      URLSearchParams. The axios request interceptor serializes bodies
      with qs.stringify, which can't read URLSearchParams' internal
      storage and produced an empty body, so the backend rejected it
      with "subscription URL is required".
    - Use message.useMessage() + context holder instead of the static
      antd message API (resolves the "Static function can not consume
      context" warning), matching XrayPage's pattern.
    - Migrate the subscriptions Drawer to antd v6 props: width -> size,
      destroyOnClose -> destroyOnHidden, and Space direction -> orientation.
    
    * feat(xray): show traffic/test for subscription outbounds; harden + test the feature
    
    Display (the reported issue):
    - Replace the flat read-only pills with a proper read-only table (desktop)
      and cards (mobile) in a new SubscriptionOutbounds component, showing
      Address, Protocol, Traffic (matched by tag — already collected by Xray),
      and a Test button with Latency. No edit/delete/move (read-only).
    - Test subscription outbounds via the existing /testOutbound endpoint, with
      results keyed by tag (subscriptionTestStates + testSubscriptionOutbound in
      useXraySetting, wired through XrayPage). Generalize isTesting/testResult to
      a string|number key so the same helpers serve index- and tag-keyed states.
    
    i18n:
    - Replace all hardcoded English subscription strings with t() calls and add
      pages.xray.outboundSub.* keys to en-US.json (other locales fall back).
    
    Backend hardening + tests:
    - xray.go: drop the tautological `subSvc != nil` check.
    - outbound_subscription: re-validate every redirect hop against private/
      internal addresses (CheckRedirect) and cap the redirect chain, closing an
      SSRF gap where only the initial host was checked.
    - Extract assignStableTags as a pure function and add unit tests for tag
      stability and SSRF rejection (the feature previously had no tests).
    
    Misc:
    - gofmt util/link/outbound.go (it was not gofmt-clean).
    
    * fix(xray): make outbound-subs feature pass CI (test compile, route docs, openapi)
    
    - outbound_test.go: remove unused `inner`/`lines` variables that broke the
      `util/link` test build (declared and not used).
    - Document the 7 outbound-subscription routes in endpoints.ts (list, create,
      update, delete, del alias, refresh, parse) so TestAPIRoutesDocumented passes.
    - Regenerate frontend/public/openapi.json (npm run gen) to include the new
      endpoints, satisfying the codegen freshness check.
    
    * feat(xray): per-subscription allow-private, gap-filled tags, UI tweaks, delete refresh
    
    Backend:
    - Add a per-subscription AllowPrivate flag (default off). Create/Update/refresh
      and the redirect check sanitize the URL with it, so localhost/LAN sources work
      only when explicitly opted in; the SSRF guard still blocks private targets by
      default. Controller reads the allowPrivate form field on create/update/parse.
    - Default outbound tag prefix now uses the smallest free "subN-" number instead
      of the auto-increment id, so deleting a subscription frees its number for reuse
      (a fresh start gives sub1) while staying stable per subscription. Extracted a
      pure defaultPrefixNumber() with unit tests.
    - deleteOutboundSub now signals SetToNeedRestart so xray drops the outbounds.
    
    Frontend:
    - "Allow private address" toggle in the add form (sends allowPrivate).
    - Delete now refreshes the xray view immediately (no manual page reload).
    - Subscriptions manager opens as a centered Modal instead of a right-side Drawer.
    - Move Outbounds to a top-level sidebar item under Nodes (out of Xray Configs).
    - Collapse WARP/NordVPN into a "more" dropdown.
    - Document the allowPrivate param in endpoints.ts.
    
    * i18n(xray): translate outbound-subscription UI into all locales
    
    - Translate the pages.xray.outboundSub.* strings (and allowPrivate label/hint)
      into all 12 non-English locales, matching each file's existing terminology.
    - Remove the unused outboundSub.add ("Add subscription") key from every locale.
    
    * feat(xray): subscription manager — edit, reorder/priority, status, preview, refresh-all
    
    Backend:
    - Per-subscription Priority + Prepend: subscriptions are ordered by Priority and
      placed before (Prepend) or after the manual template outbounds in the merge, so
      a subscription server can become the default. New Move(up/down) endpoint
      re-normalizes priorities; merge split into prepend/template/append.
    - List now returns a derived OutboundCount and orders by priority, and strips the
      heavy LastFetchedOutbounds/LinkIdentities blobs from the list payload.
    - Create/Update accept the prepend flag; new subs append at the end of priority.
    
    Frontend (Outbound Subscriptions modal):
    - Edit existing subscriptions (reuses the form + Update endpoint).
    - Inline enable/disable Switch, Status column (OK / error tooltip), Outbounds
      count column, per-row refresh spinner, "Refresh all" button.
    - Reorder (move up/down) controls + a "Before manual outbounds" toggle.
    - Preview button: fetch+parse a URL via /parse without saving.
    - Document the move route + prepend param in endpoints.ts; regenerate openapi.json.
    
    * i18n(xray): translate new subscription-manager strings into all locales
    
    Add the prepend/prependHint, preview/previewEmpty, refreshAll, statusOk and
    toastUpdated keys to all 12 non-English locales, matching each file's terminology.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • 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
  • i18n(tr): Improve Turkish translation consistency and terminology (#5066)
    Thank you for this great project!
    
    I've made a comprehensive revision of the Turkish translation to improve consistency, grammatical accuracy, and natural flow for Turkish-speaking network administrators.
    
    **Key Improvements:**
    - **Unified "Client" Terminology:** Consistently translated as "Kullanıcı" (User) for human accounts and "İstemci" (Client) for software applications throughout the UI and Telegram Bot.
    - **Inbounds & Outbounds:** Replaced the literal translations with professional networking terms: "Bağlantı Noktaları" (Inbounds) and "Çıkış Noktaları" (Outbounds).
    - **Vowel Harmony Fixes:** Corrected several Turkish grammatical vowel harmony issues (e.g., *kullanıcısi* → *kullanıcısı*, *kullanıcılarini* → *kullanıcılarını*).
    - **Capitalization & Phrasing:** Fixed capitalization inconsistencies (e.g., "Son Çevrimiçi") and improved phrasing for terms like "camouflage" → "Maskeleme" and "transport" → "Aktarım".
    
    Technical English terms (SNI, TLS, REALITY, grpc, Vision, etc.) are intentionally kept in English as they are the standard in network engineering. 
    
    Hope this helps the Turkish community!
  • i18n: translate #4988 sockopt/REALITY-target/Freedom strings for all locales
    Commit 6ed6f57b (#4988) added tcpWindowClampHint, the four realityTarget* keys, and the three FreedomHappyEyeballs* keys to en-US only. Fill in the other 12 locales so the new sockopt hint, REALITY target validation messages, and Freedom Happy Eyeballs options are localized. Technical tokens (REALITY, Xray-core, IPv4/IPv6, Happy Eyeballs, port examples, ms) are kept literal.
  • feat(nodes): multi-hop node attribution for chained sub-nodes (#4983) (#5005)
    * feat(nodes): add stable panel GUID identity (multi-hop phase 0)
    
    Per-panel autoincrement node ids are meaningless one hop away, so in a chained topology (Node1 -> Node2 -> Node3) the master cannot attribute online clients or inbounds to the physical node that hosts them (#4983).
    
    Introduce a stable self-identifier: each panel generates and persists a panelGuid (settings table, mirroring GetSecret), returns it in panel/api/server/status, and the master learns it per node via the heartbeat into a new Node.Guid column. Guarded so an old-build node or a failed probe never clears a known GUID. No behavior change yet - this is the identity foundation Phases 1-2 key on.
    
    Refs #4983
    
    * feat(nodes): attribute inbounds to their origin node by GUID (multi-hop phase 1)
    
    Add Inbound.OriginNodeGuid: the GUID of the panel that physically hosts an inbound. Empty means this panel's own xray; set means it was synced from a node. SetRemoteTraffic now fills it per synced inbound - keeping a non-empty value the node forwarded from its own sub-node (so a transitive inbound stays attributed to the deepest node across hops), and otherwise attributing the node's own local inbounds to that node's GUID. Empty (old-build node without a GUID) leaves the existing node_id-based attribution untouched.
    
    The field rides the existing inbound JSON, so /list propagates it up the chain with no serve-side change. Phase 2 will key per-node online off this instead of the panel-local node_id.
    
    Refs #4983
    
    * feat(nodes): key online status by node GUID end-to-end (multi-hop phase 2)
    
    Replace the panel-local node-id keying of per-node online status with the stable panelGuid, so a client several hops down a node chain is attributed to the node that physically hosts it instead of the intermediate node it syncs through (#4983).
    
    xray/process.go stores each direct node's reported GUID-keyed subtree and merges them (correct at any depth); the service assembles GetOnlineClientsByGuid (own clients under this panel's GUID + every node under its GUID). FetchTrafficSnapshot fetches the new /clients/onlinesByGuid, falling back to the flat /onlines for old-build nodes (keyed under the node's GUID or a master-local synthetic id). The node rollup, the WS onlineByGuid/activeInbounds fields, and the inbounds-page rollup all scope by GUID; local inbounds get their OriginNodeGuid filled with the panel's GUID at serve time so the frontend keys uniformly.
    
    Old-build nodes degrade to the prior flat behaviour via the synthetic node:<id> key. Refs #4983
    
    Refs #4983
    
    * feat(nodes): surface transitive sub-nodes on the master (multi-hop phase 3a)
    
    Each panel publishes read-only summaries of the nodes it manages via GET /panel/api/server/descendants (node API token). The heartbeat job caches each direct node's summaries; GetNodeTree merges them as transitive model.Node projections (Id 0, Transitive=true, ParentGuid = their parent node's GUID) and recomputes InboundCount/OnlineCount/DepletedCount per origin GUID so a direct node shows only its own inbounds and each sub-node shows its own (#4983).
    
    The Nodes-page list endpoint and the heartbeat broadcast now return the tree; GetAll stays direct-only for probing/syncing. One transitive level is surfaced (covers Node1->Node2->Node3); deeper recursion is a follow-up. Backend only - the Nodes-page nested UI lands next.
    
    Refs #4983
    
    * feat(nodes): render transitive sub-nodes nested + read-only on the Nodes page (multi-hop phase 3b)
    
    The Nodes page now shows a node's downstream sub-nodes (learned via the descendants tree) as indented, read-only rows ordered right under their parent: no enable toggle, probe, edit, delete, update, selection, or history expander - just a 'Sub-node' tag whose tooltip names the parent it is reached through. Desktop table and mobile cards both handle it. Transitive rows are keyed by GUID (their Id is 0) so they don't collide with real nodes (#4983).
    
    Rows nest by parentGuid rather than AntD tree-children to avoid clashing with the existing per-row history expander. New labels added to en-US (other locales fall back until translated). Refs #4983
    
    Refs #4983
    
    * i18n(nodes): translate subNode/subNodeTip across all locales
    
    Phase 3b added these two Nodes-page keys (read-only sub-node tag + tooltip) only to en-US; fill in the other 12 locales so the multi-hop sub-node UI is fully localized. The {parent} placeholder is preserved in every translation.
    
    Refs #4983
  • fix(panel): normalize XHTTP/sockopt/Reality wire output and validate REALITY target (#4988)
    * fix(panel): normalize XHTTP/sockopt/Reality wire output and validate REALITY target
    
    Strip mode-specific XHTTP fields for stream-one, reset harmful sockopt defaults
    to 0, split server/client Reality fields on save, validate target host:port in
    the inbound form, and expose Happy Eyeballs for the direct freedom outbound.
    
    Co-authored-by: Cursor <cursoragent@cursor.com>
    
    * fix(panel): keep REALITY public key on the wire, guard freedom noises
    
    The REALITY server/client wire split deleted realitySettings.settings on save, but the panel stores the REALITY public key there and every share-link / subscription generator reads it back from that path (frontend inbound-link.ts, Go subService/subJsonService/subClashService). Stripping it produced empty pbk= links, breaking client connectivity after save+reload.
    
    Revert the reality normalization (drop normalizeRealityForWire and the key sets), restore the inbound REALITY form fields (uTLS, spiderX, publicKey, mldsa65Verify) while keeping the new validated target field, and restore the mldsa65Verify clear handler.
    
    Also guard freedomToWire against undefined noises/finalRules (same defensive treatment as the existing fragment guard, issue #4686) which the new freedom-outbound test surfaced as a crash. Tests now assert the public key is preserved.
    
    ---------
    
    Co-authored-by: Cursor <cursoragent@cursor.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(inbound-form): wrap long labels and shorten RU pinned-cert label
    Long TLS-tab labels overflowed their field in locales with wider strings (e.g. Russian 'Pinned Peer Cert SHA-256'). Add AntD labelWrap to the inbound and outbound form modals so any over-long label wraps onto a second line instead of overflowing, and shorten the Russian pinnedPeerCertSha256 label to fit.
    
    Closes #4986
  • fix(external-proxy): relabel "Host" as "Address", add per-entry ECH (#4935)
    The external proxy "Host" field was bound to dest (the connection address that becomes the link host) but labeled "Host", misleading users into thinking it set a transport host header. Relabel it to "Address" to match what it actually controls.
    
    Add per-entry ECH (echConfigList) to the external proxy schema, form (shown under Force TLS = TLS), the TS link generator, and the Go sub services: ech is emitted on share links and vmess objects, and written into the stream so the JSON subscription picks it up via the existing tlsData reader.
  • fix(node): keep client/inbound edits working when a node is offline (#4923, #4931)
    Node-backed client and inbound edits no longer hard-fail when the backing node is offline or disabled. Edits commit to the panel DB immediately and reconcile to the node when it reconnects (eventual consistency); the panel is the single source of truth for desired config.
    
    - Add Node.ConfigDirty/ConfigDirtyAt; mark a node dirty when an edit commits without reaching it (cleared via CAS on ConfigDirtyAt after a full reconcile).
    - nodePushPlan() reads node state fresh from the DB, skips the push for offline/disabled nodes (no 10s hang), and treats push failures as non-fatal across every mutation path (client add/update/del + bulk + attach/detach; inbound add/update/del/toggle/resetTraffic).
    - ReconcileNode() pushes the panel's desired config to a node on reconnect (refreshing the remote tag cache first) and prunes node-side orphans; runs before the traffic pull in the node sync job.
    - While a node is dirty the traffic pull applies only up/down deltas and node-initiated disables, never overwriting desired config from a stale node snapshot.
    - Surface a non-blocking 'saved; will sync on reconnect' warning to the UI.
    
    Validated with a two-panel Docker E2E: client delete/update, attach/detach, and inbound add/delete all reconcile correctly offline -> reconnect.
  • feat(sub): modern xray JSON format with unified finalmask editor (#4912)
    * feat(sub): add finalmask support to JSON subscriptions
    
    * feat(sub): modern xray JSON format with unified finalmask editor
    
    Drop the legacy JSON subscription format entirely and always emit the
    modern xray shape:
    
    - Flatten proxy outbounds (no vnext/servers) for vless/vmess/trojan/
      shadowsocks; hysteria was already flat.
    - Express fragment/noise via streamSettings.finalmask instead of the
      legacy direct_out freedom dialer + dialerProxy sockopt.
    
    The global finalmask (tcp/udp masks + quicParams) is stored as a single
    setting (subJsonFinalMask) and merged into every generated stream,
    replacing the separate subJsonFragment/subJsonNoises/subJsonQuicParams
    settings.
    
    Reuse the existing FinalMaskForm (used by inbound/outbound) for the
    settings UI via a small bridge component; add a showAll prop so all
    TCP/UDP/QUIC sections render for the global case. This supersedes the
    hand-rolled Fragment/Noises/quicParams tabs with the full mask editor
    (all mask types).
    
    Note: this is a breaking change — JSON subscriptions now require a
    recent xray client on the consumer side.
    
    * fix
    
    ---------
    
    Co-authored-by: biohazardous-man <biohazardous-man@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(Clash): Add routing rules and enable routing option for Clash subscriptions (#4904)
    * feat(clash): add routing rules and enable routing option for Clash/Mihomo subscriptions
    
    Allows adding custom YAML blocks and placeholders to Clash exports.
    
    Why: Shifting routing to the client prevents server IP exposure for
    DIRECT traffic and reduces unnecessary server bandwidth/CPU usage.
    
    * fix
    
    ---------
    
    Co-authored-by: Misfit-s <>
  • feat(migrate-db): SQLite <-> .dump conversion and Download Migration in Overview
    Binary: extend the migrate-db subcommand with --dump and --restore so a
    SQLite database can be exported to a portable SQL text dump and rebuilt from
    one, alongside the existing --dsn PostgreSQL copy. Implemented in Go via the
    bundled sqlite driver (new database/dump_sqlite.go); no external sqlite3 client
    is required. Add ExportPostgresToSQLite (reverse of MigrateData) to build a
    SQLite .db from live PostgreSQL data, reusing the shared copyAllModels helper.
    
    Overview: add a "Download Migration" item to Backup & Restore plus a
    getMigration endpoint/service that returns a .dump on SQLite or a .db on
    PostgreSQL, so the data can seed a panel on the other backend. Document the
    endpoint in api-docs and translate the three new strings across all locales.
    
    Tests: cover the destination-side copy (AutoMigrate + copyTable into SQLite)
    and the dump/restore round-trip including quoted values. Ignore *.dump.
    
    The x-ui.sh helper that drives this from the CLI is in PR #4910.
  • fix(api-token): hash tokens at rest and show plaintext only once
    Store API tokens as SHA-256 hashes instead of plaintext and return the token value only in the create response. List no longer exposes the token, and the UI drops the Show/Copy buttons in favor of a one-time reveal modal at creation.
    
    Match hashes the presented bearer token before the constant-time compare, and a migration hashes any pre-existing plaintext rows in place so existing tokens keep authenticating. Docs and translations updated.
  • i18n: translate connection-limit strings for all languages
    Adds connectionLimits/connIdle/bufferSize/seconds keys to the remaining 11 locales (ar, es, id, ja, pt, ru, tr, uk, vi, zh-CN, zh-TW); en-US and fa-IR shipped with the feature.
  • feat(xray): add connIdle and bufferSize policy controls
    Expose level-0 connection policies in the panel's Basics tab: idle timeout (connIdle) and per-connection buffer size (bufferSize). Empty fields delete the key so Xray falls back to its own defaults. Adds en-US/fa-IR strings and types policy.levels in the Zod schema.
  • feat(inbounds): per-proxy Pinned Peer Cert SHA-256 + labeled External Proxy form
    Redesign the Add Inbound -> Stream External Proxy section into labeled per-entry cards (Force TLS / Host / Port / Remark and, under TLS, SNI / Fingerprint / ALPN) and add a Pinned Peer Cert SHA-256 field with a generate-random-hash button to each entry.
    
    The pin flows end to end into share links: pcs for vmess/vless/trojan/ss (stripped when a proxy forces security off) and the hex-normalized pinSHA256 for Hysteria. JSON and Clash subscriptions emit the native pinnedPeerCertSha256 / pin-sha256 via the cloned stream. Adds the forceTls label across all 13 locales plus frontend and Go tests.
  • feat(dashboard): more System History metrics, persistence & localized labels
    - Sample swap %, TCP/UDP connection counts and disk-usage % on the host ticker
    - System History: Swap overlaid on the RAM tab, plus new Connections and Disk Usage tabs
    - Persist the host time-series across restarts: gob snapshot beside the DB, written on a timer and at shutdown, restored on boot
    - Live-refresh the open chart (2s for short ranges, 10s for longer)
    - Localize CPU/RAM/Swap and the new tab/chart titles across all 13 languages and route legend series names through i18n
  • feat(dashboard): richer System History & Xray Metrics charts
    - Collect disk read/write and network packet-rate metrics on the host sampler
    - Sparkline: optional 2nd/3rd overlaid series with a colored legend
    - System History: merge Bandwidth (up/down), Disk I/O (read/write) and Load (1m/5m/15m) into single multi-line tabs
    - Add a descriptive per-chart title and mobile-only tab icons to both modals
    - Localize every chart title and tab label across all 13 languages
  • fix(tls): correct pinned cert SHA-256 hint to hex, not base64
    xray-core hex-decodes pinnedPeerCertSha256 and the panel forwards the value as-is into share links and the JSON subscription, so clients hex-decode it too. The tooltip/placeholder wrongly said base64 (copied from the retired pinnedPeerCertificateChainSha256 field), and the "generate random hash" button emitted base64 via btoa, producing an unusable pin. Tooltip/placeholder now say hex across all locales and the generator emits hex.
    
    Closes #4793
  • feat(clients): show filtered count in clients list
    Surface a "Showing X of Y" counter in the clients filter bar that appears whenever a search term or any filter is active, using the server-provided filtered and total counts. Added the showingCount string across all 13 locales.
    
    Closes #4808
  • feat(outbounds): pick dialerProxy from other outbound tags for proxy chaining
    Turn the outbound sockopt dialerProxy free-text input into a searchable Select populated with the other outbound tags, so users can build a proxy chain (route one outbound through another) without typing tags by hand. The list excludes the current outbound, so self-reference cycles cannot be selected. A tooltip and placeholder explain the chaining concept. Adds dialerProxyPlaceholder and dialerProxyHint to all 13 locales.
    
    Closes #4446
  • feat(nodes): add per-node TLS verification mode for self-signed certs (#4757)
    Adds a per-node TLS verification mode to the Add/Edit Node dialog so the panel can reach nodes that serve HTTPS with a self-signed certificate:
    
    - verify (default): normal CA validation.
    - skip: InsecureSkipVerify, with a clear UI warning that it drops MITM protection.
    - pin: validates the leaf certificate's SHA-256 (base64 or hex) via VerifyConnection while bypassing the default chain/name check — keeps MITM protection for self-signed certs, the secure alternative to skip.
    
    New Node model fields tlsVerifyMode + pinnedCertSha256 (gorm auto-migrated). Probe() selects the HTTP client per node via nodeHTTPClientFor, keeping the SSRF-guarded dialer. A new POST /panel/api/nodes/certFingerprint endpoint (FetchCertFingerprint) lets the UI fetch and pin the node's current certificate in one click. Endpoint documented in api-docs/openapi; i18n added across all locales. Verified end-to-end in Docker (verify rejects, skip bypasses, fetch matches, pin accepts correct / rejects wrong).
  • feat(inbounds): support Unix domain socket path in Listen field (#4429)
    UDS listen already worked for proxying (the listen string is passed to xray verbatim and port 0 is accepted), and the Go sub/link layer already ignores the bind listen. The only gap was the frontend resolveAddr, which would put a socket-path listen into share/sub links (e.g. vless://uuid@/run/xray/x.sock:0). resolveAddr now treats a path-style listen (starting with / or @) as having no client-reachable address and falls back to hostOverride/hostname. Adds a test and a Listen-field help hint across all locales.
  • fix(fallbacks): allow free-form dest entries for external servers (#4748)
    Since v3.1.0 every fallback row had to reference a panel inbound via childId, so rows with only a free-form dest (e.g. 8080 or 127.0.0.1:8080 to an external Nginx) were silently dropped at three layers: the frontend save filter, the backend SetByMaster guard, and BuildFallbacksJSON. A row is now valid when it has a child OR an explicit dest; self-references normalize to childId 0, and BuildFallbacksJSON prefers an explicit dest (also fixing rows whose child was deleted). UI gains allowClear on the child picker; help text updated across all locales. Verified end-to-end in Docker: a free-form dest fallback now persists and is injected into the live xray config. Refs #4554, #4639.
  • feat(inbounds): attach existing clients to an inbound in one click
    Adds an 'Attach Existing Clients' row action on multi-user inbounds (shown even when the inbound is empty). It opens a modal listing the whole client pool with search and group filter, all attachable clients pre-selected, and attaches the selection to that inbound via the existing bulkAttach endpoint. Clients already on the inbound are shown disabled and skipped. Translations added for all 13 locales.
  • feat(nodes): bulk panel self-update with live online indicator
    Adds the ability to update node panels to the latest release from the Nodes
    page: select online, enabled nodes (checkboxes) and trigger their official
    self-updater, or use the per-row Update action. A node whose reported panel
    version trails the latest GitHub release is flagged with an 'update available'
    tag (compared via lib/panel-version, mirroring the Go isNewerVersion).
    
    Backend: Remote.UpdatePanel calls the node's existing
    POST /panel/api/server/updatePanel; NodeService.UpdatePanels fans out over the
    selected ids, skipping disabled/offline nodes with a per-node reason; exposed
    as POST /panel/api/nodes/updatePanel (documented in endpoints.ts + openapi.json).
    
    The bulk request sends a JSON body, so it sets Content-Type: application/json
    explicitly — axios defaults POST to form-urlencoded, which made ShouldBindJSON
    fail with 'invalid character i'.
    
    Also reuses the clients-page online cue on the Nodes page: a pulsing green dot
    plus green label for an online node. The .online-dot style moved to the shared
    styles/utils.css so both pages load it.
    
    Translations for all new node keys added across every language file.
  • feat(inbounds): clearer client validation errors on save
    When an inbound save fails Zod validation, the toast previously showed a
    raw path like `settings.clients.494.tgId: Invalid input`, which gave no
    hint which of hundreds of clients was at fault. Resolve the client array
    index back to the client email, name the field, and append a "(+N more)"
    count when several fields fail. console.error now logs a readable list of
    every issue instead of dumping the whole form.
    
    Adds the invalidClientField/invalidField/moreIssues toast strings across
    all 13 translations.
  • 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
  • i18n(nodes): translate basePath and apiToken labels
    Localize the node form 'basePath' (zh-CN, zh-TW, tr-TR) and 'apiToken'
    (zh-CN, zh-TW, uk-UA) labels that were still showing the English defaults.
  • feat(inbounds): add multi-select and bulk delete
    Mirror the clients page: checkbox selection on the desktop table and on
    mobile cards, with a danger Delete button in the toolbar that removes all
    selected inbounds in one call.
    
    Backend adds POST /panel/api/inbounds/bulkDel, which loops the existing
    DelInbound per id (xray restarts at most once) and returns {deleted,
    skipped}. Frontend shows a confirm modal plus a result toast, clears the
    selection on success, adds bulk-delete i18n keys across all 13 languages,
    and documents the endpoint in the in-panel API docs.
  • fix(clients): reject spaces, '/', '\' and control chars in subscription ID
    Like the client email, the subId is embedded directly in subscription
    URLs, so the same characters break it. Validate it on the backend
    (Create + Update) and the frontend (Zod), with a localized message
    across all 13 locales. An empty subId stays allowed (it is then
    auto-generated).
  • fix(clients): reject spaces, '/', '\' and control chars in client email
    Client emails containing a slash broke the path-param routes
    (edit/delete/view returned 404 / "client not found"), leaving stale
    records that could only be cleared with manual SQLite edits. Validate
    the email on both the backend (Create + Update, which also covers the
    bulk paths) and the frontend (Zod) so these characters are rejected at
    save time with a clear, localized message across all 13 locales.
    
    Closes #4695
  • feat(clients/inbounds): IP log popups, clearer titles, tag-based inbound labels
    Add an IP Log popup (view list + refresh + clear) to the client edit form and the Client Information modal, with IPs stacked vertically.
    
    Identify inbounds by their xray tag (not remark/protocol:port) across every picker and chip: attach/detach modals, the attached-inbounds column and field, the filter drawer, and bulk-add. Add the tag field to the InboundOption schema (the backend already returned it).
    
    Clarify modal titles/labels: Client Information (was More Information) and Inbound Information (was Inbound's Data); Client Information / QR Code titles now include the client email.
    
    i18n: rename keys moreInformation->clientInfo and inboundData->inboundInfo with proper translations in all languages; addTitle->addClient, editTitle->editClient, addToGroupPlaceholder->groupName.
  • fix(outbounds): support proxyProtocol on freedom outbound
    Xray's freedom outbound accepts a numeric proxyProtocol (0 disabled,
    1 or 2 for the PROXY protocol version), but the panel had no field for
    it and the typed form adapter dropped the key on save — so a value set
    via the JSON editor disappeared the moment the outbound was saved.
    
    Model proxyProtocol through the freedom wire schema, the form schema,
    and both adapter directions (clamped to 0/1/2, omitted from the wire
    when 0), and add a Select (none / v1 / v2) to the freedom section of
    the outbound form. Add round-trip test coverage and the proxyProtocol
    label across all locales.
    
    Closes #4486
  • feat(fallbacks): add per-rule dest override
    Operators can now type an explicit dest (e.g. "8443", "127.0.0.1:8443",
    "/dev/shm/x.sock") on each fallback row to override the auto-resolved
    child listen+port. Empty keeps the existing auto behavior.
    
    Adds the column to inbound_fallbacks (GORM AutoMigrate), threads it
    through the panel form, API docs, and translations.
  • feat(tls): surface pinnedPeerCertSha256 in panel, share links, and subs
    Adds a panel-only `pinnedPeerCertSha256` field on TLS settings with a tags input and a random-hash generator. The hashes ride share links as `pcs` (v2rayN-compatible), Clash sub as `pin-sha256`, and JSON sub as `pinnedPeerCertSha256`, while remaining stripped from the run-config sent to xray-core.
  • i18n(panel): translate Copy/Cancel buttons, Stream/Sniffing tabs, and All-Inbounds filenames
    - TextModal: route the Copy button label and the post-copy toast
      through t('copy')/t('copied') instead of hardcoded English.
    - PromptModal: route cancelText through t('cancel') and default okText
      through t('confirm') so the import-inbound prompt stops showing
      "Cancel" in non-English UI.
    - InboundsPage: pass the All-Inbounds and All-Inbounds-Subs download
      filenames through t(...) so each locale can localize them.
    - en-US.json: add pages.inbounds.exportAllLinksFileName and
      pages.inbounds.exportAllSubsFileName.
    - All 12 non-English locales: translate streamTab and sniffingTab
      (previously left as literal English) and add the two new filename
      keys with appropriate translations.
    
    All 13 locale files now have 1541 lines.
  • i18n(panel): migrate hardcoded panel strings to en-US and translate all locales
    Surface ~400 hardcoded English labels, tooltips, placeholders, dt/divider
    text, modal okText/cancelText, and Spin loading from the panel pages
    (clients/groups/inbounds/nodes/settings/xray/sub/index) into
    web/translation/en-US.json under existing pages.<page>.* namespaces, with
    JSX swapped to t(...). Brand and protocol identifiers (TLS, MTU, SNI,
    NordVPN, Cloudflare WARP, etc.) stay literal.
    
    Sync all 12 non-English locales (ar-EG, es-ES, fa-IR, id-ID, ja-JP,
    pt-BR, ru-RU, tr-TR, uk-UA, vi-VN, zh-CN, zh-TW) to match en-US's
    structure and translate the 521 new key paths per locale. Every locale
    file now has 1539 lines, mirroring en-US ordering.
    
    Also remove a dead duplicate "info": "Info" key under pages.inbounds
    that collided with the new pages.inbounds.info.* object.
    
    Backend: bulk attach/detach errors in web/service/client.go now route
    through logger.Warningf (so they appear under /panel/api/server/logs/)
    instead of only living on the response payload.
  • refactor(clients): coherent group management — rename, split, extract
    This bundles a set of group-related improvements that built up across
    one session and only make sense together.
    
    Terminology / API surface:
    - Rename "assign group" → "add to group" everywhere: i18n keys,
      callback names (bulkAddToGroup), component + file names
      (BulkAddToGroupModal, AddClientsToGroupModal), Go controller/struct
      names (bulkAddToGroup, AddToGroup), OpenAPI summaries. Nothing keeps
      the word "assign" anymore.
    - Move group routes under /panel/api/clients/groups/* (was
      /bulkAssignGroup at the clients root).
    - Split add and remove into two endpoints: /groups/bulkAdd now rejects
      empty group; new /groups/bulkRemove clears the label for the given
      emails. The old "submit empty to clear" UX is gone — Ungroup is its
      own action.
    
    UI affordances on Clients page:
    - Promote Group + Ungroup to visible bar buttons next to Attach +
      Detach. Group reuses BulkAddToGroupModal; Ungroup pops a danger
      confirm and calls bulkRemoveFromGroup.
    - Custom UngroupIcon (TagsOutlined with a diagonal strike) for the
      Ungroup button so the pairing reads at a glance.
    - Hide the Group column when no clients have a group label yet —
      removes a column of em-dashes on fresh installs.
    
    UI on Groups page:
    - New per-row Add clients… / Remove clients… actions backed by
      GroupAddClientsModal and GroupRemoveClientsModal: rich client picker
      (email / comment / current group / enable) with search and
      preserveSelectedRowKeys, mirroring the inbounds Attach modal UX.
    
    Controller split:
    - Move all /groups/* routes, handlers, and request bodies out of
      web/controller/client.go into a dedicated web/controller/group.go
      (GroupController with leaner clientService + xrayService
      dependencies). URLs are byte-identical because the new controller
      registers on the same parent gin.RouterGroup; api_docs_test.go gets
      a group.go → /panel/api/clients basePath entry so its route
      extraction keeps working.
    
    Invalidation dedup:
    - Removing a client from a group on the Groups page used to refetch
      /clients/groups and /clients/onlines three times: once from the
      mutation's onSuccess, once from a redundant invalidate() in the
      page's onSubmit, once from the WebSocket invalidate broadcast that
      the backend fires after every mutation. The manual invalidate() is
      gone, and a small invalidationTracker module lets websocketBridge
      skip WS-driven invalidates that arrive within 1.5s of a local
      invalidate — bringing the refetch count down to one. The WS path
      still works for changes made by another tab or user.
  • feat(clients): tidier bulk action toolbar
    When at least one client is selected, the toolbar now collapses to a
    small selection indicator plus the three most-used actions instead of
    spreading six count-suffixed buttons across the row:
    
    - Replaces every per-button "(N)" with a single closable "{N} selected"
      tag on the left — one click on its × clears the selection.
    - Hides "+ Add Clients" while a selection is active (focus mode).
    - Keeps Attach, Detach, and Delete as visible buttons; Delete is pushed
      to the right with auto margin so it doesn't sit flush against the
      non-destructive actions.
    - Folds Adjust, Group, and Sub links into the existing "more"
      dropdown, which is now context-aware: selection-scoped overflow when
      rows are picked, global actions (Add Bulk / Reset all / Del depleted)
      otherwise.
    
    On mobile the new buttons collapse to icon-only the same way as the
    rest of the toolbar.
  • feat(clients): selective bulk attach + new bulk detach
    Inbounds page:
    - AttachClientsModal now shows a per-client selection table (email,
      comment, enabled tag) with search and a live "selected of total"
      counter; all clients are pre-selected so the old "attach all"
      workflow stays a single OK click.
    - New DetachClientsModal on the inbound row menu lets you pick which
      clients to remove from that inbound (records are kept so they can be
      re-attached later; for full removal use Delete).
    
    Clients page:
    - New "Attach (N)" bulk-action button + BulkAttachInboundsModal that
      attaches selected clients to one or more multi-user inbounds.
    - New "Detach (N)" bulk-action button + BulkDetachInboundsModal that
      removes selected clients from chosen inbounds; (email, inbound) pairs
      where the client isn't attached are silently skipped.
    
    Backend adds POST /panel/api/clients/bulkDetach, wrapping the existing
    Detach service for each email and reporting per-email
    detached/skipped/errors. ClientRecord rows are kept on detach to match
    the single-client endpoint; bulkDel remains the path for full removal.
  • feat(inbounds): restore "Set Cert from Panel" / Clear buttons in TLS certs
    Bring back the per-certificate buttons in the inbound TLS section (File Path
    mode): "Set Cert from Panel" fetches the panel's own webCertFile/webKeyFile via
    /panel/setting/all and fills the cert's certificateFile/keyFile, warning when no
    panel cert is configured; "Clear" empties both paths.
    
    Reuses the existing pages.inbounds.setDefaultCert label and adds a
    setDefaultCertEmpty warning string.
  • feat(inbounds): bulk-attach & assign-group client actions + form defaults
    - Bulk-attach an inbound's clients onto other inbounds (same identity, shared traffic): new ClientService.BulkAttach + POST /clients/bulkAttach, an inbound row action, and AttachClientsModal.
    - Assign all of an inbound's clients to a group from the inbound page, reusing /clients/bulkAssignGroup and the existing BulkAssignGroupModal.
    - Default a random user/pass account for new Mixed and HTTP inbounds instead of an empty accounts list.
    - Capitalize the inbound Security toggle labels (None/TLS/Reality).
  • feat(settings): panel network proxy for the panel's own outbound requests
    Add a panelProxy setting that routes the panel's self-initiated HTTP requests (geo updates, Xray version/core download, panel update check) through an admin-configured socks5/http(s) proxy, to bypass server-side filtering of GitHub/Telegram. The Telegram bot falls back to it when tgBotProxy is empty (socks5 only). New util/netproxy.NewHTTPClient builds the proxied client.
    
    Also fix the Mixed-inbound SOCKS/HTTP share URLs that had host:port and user:pass in the wrong order, and consolidate the Telegram settings tab (move API server into the general tab, drop the empty Proxy & Server tab).
  • Client/inbound resilience + Postgres pool tuning + schema fixes (#4607)
    * fix(clients): fall back to inbound scan when ClientRecord is missing
    
    DeleteByEmail looked up the email in client_records and returned the
    raw "record not found" gorm error when nothing matched, even though
    the client could still live inside an inbound's settings.clients JSON
    (legacy entries that SyncInbound never picked up, or rows deleted out
    from under a stale inbound). The user-visible delete then fails
    mysteriously while xray happily keeps serving the client.
    
    When GetRecordByEmail returns ErrRecordNotFound, walk inbounds whose
    settings JSON references the email and run DelInboundClientByEmail on
    each. The traffic / IP rows are cleaned up at the end unless keepTraffic
    is set. If no inbound carries the email either, surface a clear
    "client %q not found in any inbound or client record" error instead.
    
    * chore(logging): include request + caller context in jsonMsgObj warnings
    
    The generic "X-UI: Something went wrong. Error: record not found" log
    gave no clue about which endpoint, client, or controller line emitted
    it. Prepend a context block:
    
      [POST /panel/api/clients/del/ADMIN ip=109.124.234.127
       handler=controller.(*ClientController).delete client.go:146]
    
    Handler frame is located by scanning the stack for the first caller
    outside util.go, so it points at the right controller method whether
    the path went through jsonMsg, jsonObj, or jsonMsgObj directly.
    
    * fix(clients): tolerate orphan client_inbounds rows in Delete
    
    DeleteByEmail's previous fix only covered the case where GetRecordByEmail
    returned ErrRecordNotFound. When the ClientRecord exists but a client_inbounds
    row points to an inbound that has been removed out-of-band (failed mid-delete,
    manual SQL, pre-SyncInbound migration), Delete bubbled the raw gorm
    "record not found" from inboundSvc.GetInbound and aborted before any cleanup
    ran — leaving the client un-deletable through the UI/API.
    
    Match the tolerance bulkDelInboundClients already has: when GetInbound
    returns gorm.ErrRecordNotFound for a join row, log a warning and continue.
    The unconditional Delete(&model.ClientInbound{}) later in the function then
    removes the stale row, and the ClientRecord delete succeeds.
    
    * fix(schemas): accept empty-string fingerprint on externalProxy
    
    The External Proxy form offers a "Default" option with value '' for the
    uTLS fingerprint dropdown, but UtlsFingerprintSchema.optional() rejects
    empty strings (only undefined or a valid enum member). Saving an inbound
    with externalProxy rows failed with `expected one of "360"|"chrome"|...`.
    
    Preprocess '' to undefined before the optional enum, matching the existing
    pattern used for VmessSecuritySchema.
    
    * chore(logging): drop noisy orphan client_inbounds warning
    
    Per-row WARNINGs spammed logs whenever a client referenced multiple
    already-deleted inbounds. The continue keeps the orphan-tolerant
    behavior; just no longer announces each skipped row.
    
    * feat(clients): per-client VMess security in client form
    
    Restores the VMess `security` selector on the client form (auto, aes-128-gcm,
    chacha20-poly1305, none, zero) and surfaces it only when at least one attached
    inbound is VMess. The value rides into the share link via the existing
    `scy=` field in genVmessLink; the panel persists it on ClientRecord and in
    the inbound's settings.clients so the link generator can read it back.
    
    Adds the pages.clients.vmessSecurity i18n key in en-US and fa-IR.
    
    * fix(xray-config): strip panel-only fields from inbound config
    
    Two fields the panel stores but Xray doesn't accept on the inbound side:
    
    - VMess clients[].security — panel persists it so the share-link generator
      can write `scy=...`, but xray's vmess inbound spec has no per-client
      security. The field was leaking into the inbound JSON pushed to xray-core.
    - VLESS settings.encryption — per the xray spec the inbound only takes
      `decryption`; `encryption` is for the matching client outbound. The panel
      keeps it for operator reference, but it must not appear in the inbound
      payload.
    
    Add two strip helpers next to HealShadowsocksClientMethods and wire them
    into GenXrayInboundConfig via a per-protocol switch, so both local and
    remote runtime paths get the cleaned config.
    
    * chore(db): backend-aware pool sizes with env overrides
    
    Per-backend defaults:
    - Postgres: 25 max open / 25 max idle. Matching idle to open removes
      pool churn under bursts (Postgres handles concurrency at the server,
      idle connections are cheap).
    - SQLite: 1 max open / 1 max idle. Single-writer model means a wider
      cap just queues behind busy_timeout; tight cap is honest.
    
    Both back ends share ConnMaxLifetime=1h and ConnMaxIdleTime=30m so
    stale connections (vault rotation, pgbouncer drops, load-balancer
    idle eviction) rotate out without operator intervention.
    
    Operators can override either default at boot via:
      XUI_DB_MAX_OPEN_CONNS=...
      XUI_DB_MAX_IDLE_CONNS=...
    
    envInt parses these; missing/empty/non-positive values fall back to
    the per-backend default.
    
    * fix(schemas): accept boolean acceptProxyProtocol on TCP stream
    
    TcpStreamSettingsSchema declared `acceptProxyProtocol: z.literal(true).optional()`,
    so saving an inbound where the AntD Switch sat in the off state failed
    validation with `Invalid input` because the Switch always emits a plain
    boolean.
    
    Switch to `z.boolean().default(false)` — same shape ws/sockopt/httpupgrade
    already use, and matches the actual wire payload (golden fixtures and
    other settings blocks all store `acceptProxyProtocol: false`).
    
    Snapshots for stream.test and inbound-full.test pick up the new defaulted
    field on TCP fixtures.
  • feat(inbounds): row action to delete all clients of an inbound
    Adds POST /panel/api/inbounds/:id/delAllClients that collects every
    client email from settings.clients[] and runs ClientService.BulkDelete
    in one pass. Row action lives in the More menu as a danger item, only
    shown for multi-user inbounds that currently have at least one client;
    confirmation modal displays the live client count.
  • feat(clients,groups): client groups + sub-links export + dedicated groups page
    Persistent client groups
    - New ClientGroup model + client_groups table that holds empty
      (placeholder) groups so a user can define a label before any client
      references it. ListGroups merges these with the distinct group_name
      values already stored on clients and reports {name, clientCount}.
    - ClientRecord gains group_name column; the model.Client wire shape
      gains a matching `group` JSON field that survives the
      inbound.settings → SyncInbound round-trip.
    - Rename/Delete on a group mutates client_groups (rename row / delete
      row) AND propagates to all matching clients in ClientRecord and in
      every owning inbound's settings JSON, all in one transaction.
    
    Bulk operations
    - AssignGroup(emails, group) updates clients.group_name + patches each
      affected inbound's settings JSON in one read-modify-write per inbound.
      Empty group clears the label. Auto-creates the client_groups row when
      the user assigns to a brand-new name.
    - BulkResetTraffic(emails) loops the existing single-reset path so the
      caller can zero traffic across a whole selection or a whole group.
    - EmailsByGroup(name) returns just the email list (used by the groups
      page to fan a single bulk action over every member).
    
    Endpoints (all under /panel/api/clients)
    - GET  /groups                         — summaries with counts
    - GET  /groups/:name/emails            — emails in a group
    - POST /groups/create                  — empty placeholder group
    - POST /groups/rename                  — rename (table + clients + JSON)
    - POST /groups/delete                  — drop label everywhere (clients survive)
    - POST /bulkAssignGroup                — assign N selected clients
    - POST /bulkResetTraffic               — reset traffic on a list
    
    Clients page UX
    - New Group column (Actions → Client → Group → Inbounds → …) with a
      click-to-filter chip.
    - FilterDrawer gains a multi-select Group filter whose options come
      from the new ClientPageResponse.groups field (sourced from ListGroups
      so empty/placeholder groups are pickable too).
    - Single-client and bulk-add forms gain a Group AutoComplete pre-loaded
      with all known group names.
    - New toolbar buttons when selection > 0: "Group ({n})" opens
      BulkAssignGroupModal, "Sub links ({n})" opens SubLinksModal.
    
    Sub-links export modal (new SubLinksModal.tsx)
    - Table of selected clients with their subscription URL (and JSON URL
      when subJsonEnable is on), per-row copy, Copy all, and Download as
      sub-links-<timestamp>.txt. Warns when subscription is disabled or
      none of the selected clients have a subId.
    
    Dedicated Groups page (new pages/groups/GroupsPage.tsx)
    - /groups route + sidebar entry (TagsOutlined icon) + page title key.
    - Card-based layout matching Clients/Inbounds/Nodes — summary card with
      Total/Grouped/Empty stats, main card with Add Group button + table.
    - Per-row More dropdown (icon-first column on the left): Sub links,
      Adjust (days+traffic), Reset traffic, Rename, Delete clients in
      group, Delete group (keep clients). Empty groups disable the
      client-targeted actions.
    - Reuses SubLinksModal and ClientBulkAdjustModal — emails for the
      group are fetched on demand from GET /groups/:name/emails.
    
    Other polish
    - /groups + groups-page selectors added to page-shell.css and
      page-cards.css so the new page inherits the same background, padding,
      card borders, hover shadow, and summary-card padding.
    - .card-toolbar gains a small vertical padding so the larger toolbar
      buttons (now default size, matching Inbounds) don't crowd the top of
      the card-head on Clients and Groups pages.
  • feat(clients): toolbar sort selector + preserve updated_at on unchanged rows
    Frontend
    - New Sort dropdown in the clients toolbar covering oldest/newest,
      recently updated, recently online, email A↔Z, most traffic, highest
      remaining, expiring soonest. Default is Oldest first.
    - Strip per-column sorter arrows from the Table — all sorting now flows
      through the single dropdown, so the column headers stop competing
      with it.
    - Empty state: TeamOutlined icon, t('noData'), text-secondary color
      (matching the inbound/node polish).
    
    Backend
    - sortClients: add createdAt, updatedAt and lastOnline cases (with id
      tie-break for stable ordering when timestamps collide).
    - Fix Recently updated: SyncInbound was calling tx.Save on every client
      in the inbound, and GORM's autoUpdateTime tag stamped updated_at to
      time.Now() each time — so editing one client bumped ALL of them.
      After the Save, restore each row's preserved updated_at via
      UpdateColumn (skips hooks). The actually-edited client gets its
      fresh stamp from the explicit UpdateColumn at the end of Update().
    - Fix periodic updated_at churn: adjustTraffics unconditionally set
      c["updated_at"] = now() for every client in any inbound that had a
      delayed-start expiry, every traffic-stats pass. Turn that into a
      backfill (only when the key is missing), matching the created_at
      treatment one line above.