Commit Graph
31 Commits
  • feat(sub): add Incy app-management parameters (#6650)
    * feat(sub): add Incy app-management parameters
    
    The panel already pushes a set of Happ headers, but INCY documents its own
    lowercase header names and its own value domains, so a Happ-shaped payload gets
    ignored by the client (per-app mode is bypass|proxy, not on|bypass, and
    per-app-proxy-enable has no Happ counterpart at all). Add a sibling Incy path
    that emits exactly the documented headers.
    
    Covered, per https://docs.incy.cc/en/app-management/:
    - profile-description, sort-order, support-email, announce-url, premium-url
    - banner text/button/URL and the two hex colours
    - hide-url, hide-check, no-limit-enabled
    - per-app split tunnelling (enable/mode/list)
    - TCP fragmentation (enable/length/interval/packets)
    - UDP noise packets (enable/type/packet/delay)
    - DoH pre-resolution (enable/domain/IP)
    
    Each string setting is tri-state: an empty value omits the header, so an
    untouched panel never overrides the subscriber's own choice in the app. Values
    are validated against the documented domains and dropped when they do not
    match, and non-ASCII text is base64-wrapped the way the docs require for
    Cyrillic. INCY identifies itself as INCY/<version>/<platform>, which gates the
    headers behind the same auto-detect switch the Happ path uses.
    
    Headers the panel already emits for every client (Profile-Title, Support-Url,
    Profile-Web-Page-Url, Announce, Profile-Update-Interval, Subscription-Userinfo)
    and Incy's routing line are left as they are.
    
    The Premium API (theme, defaultPingProtocol, fallbackHosts, ...) is a separate
    encrypted endpoint and stays out of scope here.
    
    * fix(sub): keep Incy per-app list entries separate on the wire
    
    The Incy settings textarea takes one package per line, as Incy documents for
    per-app-proxy-list, but the header path ran the value through
    sanitizeHeaderValue, which deletes CR/LF. "com.google.chrome\norg.telegram.messenger"
    reached the client as the single bogus package
    "com.google.chromeorg.telegram.messenger", so per-app split tunnelling silently
    matched no app. Join comma- or line-separated entries as CSV instead.
    
    Also drop three tests that could not fail: TestIncyExcludesHappOnlyHeaders
    (ApplyIncyHeaders has no path that emits Happ headers, and the non-Happ UA
    gate is already pinned by TestApplyHappHeaders_Gating) and two UI tests that
    only asserted updateSetting received the key the JSX passes it.
    
    ---------
    
    Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): make external subscription fetch User-Agent configurable (#6613)
    * feat(sub): make external subscription fetch User-Agent configurable
    
    Some providers reject fetches that do not send a known client User-Agent.
    Expose externalSubUserAgent as a panel setting (default v2rayNG/1.8.5)
    and use it when fetching client external subscription URLs.
    
    Fixes #6383
    
    * 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.
    
    * fix(sub): fall back to the default UA when the DB is not initialised
    
    externalSubUserAgent read the setting through SettingService.getSetting,
    which calls Model() on database.GetDB() and panics on a nil *gorm.DB.
    The fetch path's other DB read, service.ExternalSubscriptionHwid, already
    treats a nil DB as unreachable and sends no header; the new UA lookup
    did not, so any fetch before InitDB panicked instead of sending the
    historical v2rayNG/1.8.5.
    
    Production initialises the DB before the sub server starts, but the
    internal/sub fetch tests run without one: under make test-go's
    -shuffle=on, whenever one of them ran before the first InitDB test the
    panic aborted the whole package. Reproduced deterministically with
    go test -run '^TestDoFetchSubscriptionLinks_RejectsOversizedBody$'.
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): make Happ require auth on its local SOCKS/HTTP proxy (#6628)
    Happ ships its local SOCKS5 (127.0.0.1:10808) and HTTP inbounds with
    authorization disabled by default. Any app on the same device can then
    connect to that proxy, bypassing Android's per-app VPN routing, and learn
    the VPN server address - the leak publicly described in March-April 2026
    for Happ, v2rayNG and other VLESS clients. Happ fixed its Xray API
    exposure, but the unauthenticated local proxy remained.
    
    Happ exposes a standard subscription header for this (no Provider ID
    required): socks-auth-mode / http-auth-mode = auto|manual|from-json|
    disable. A new subscription setting, subHappLocalProxyAuth (default
    "auto"), sends both headers to Happ clients. Like every other Happ header
    it is emitted only when Happ auto-detect is enabled and the User-Agent is
    Happ, so panels that never opted into the Happ integration see no change.
    An empty value sends nothing and keeps the client's own setting.
    
    Verified on Happ Android 4.4.1 (Xray 26.7.28): a subscription carrying
    socks-auth-mode manual + a test user/password switched the client's
    Inbounds screen to Manual with those credentials on "refresh subscription",
    and "auto" switched it to Auto with generated credentials.
    
    Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.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(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
  • feat(sub): add opt-in month-end expiry presentation (#6517)
    Offer monthly calendar subscriptions an explicit last-valid-second display
    without moving their real billing boundary or spending renewal allowances.
    
    Keep the option off by default and limit conversion to a shared fixed
    day-1 midnight cutoff at an actual month transition in the panel timezone.
    Use the authoritative client calendar mode when aggregating node traffic,
    and share the header formatter across raw, JSON, and Clash exports.
    
    Expose the setting in the existing settings API/UI, regenerate its schemas,
    and document that clients may report expiry one second early or format the
    date differently in another timezone. Add HTTP, settings, and DST coverage.
    Stored deadlines, access enforcement, info/remark expiry values, and renewal
    accounting remain unchanged.
    
    Refs: #6516
    
    Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
  • feat(settings): add setting for Reality scan candidates (#6471)
    * feat(settings): allow customizing Reality scan candidate list
    
    Persist a realityScanCandidates panel setting (defaulting to the previous
    hardcoded list), expose it in General Settings with i18n, and have the
    Find Targets scanner use it when the search box is empty.
    
    Fixes #5847
    
    * style(frontend): oxfmt realityScanCandidates in setting.ts
    
    * Fix locale JSON syntax
    
    This change removes the malformed duplicate key and missing comma in the Android per-app proxy translations across the bundled locale files. The JSON now parses correctly while preserving the translated labels for each language.
    
    * docs(i18n): update Happ translations
    
    Localize the remaining Happ subscription settings strings across the translation files and refine the English copy. This aligns the labels and descriptions with the current Happ behavior for notifications, TUN options, HWID enforcement, routing presets, and per-app proxy settings.
    
    * refactor(reality): drop test-only scaffolding from the candidate setting
    
    TestDefaultRealityScanCandidatesCSV compared the CSV against its own
    initializer and a defaultValueMap lookup, and
    TestRealityScanCandidateTokensFallsBackWithoutDB drove a no-database
    state no production caller reaches (the only caller is the
    scanRealityTargets handler, served after InitDB). The
    s != nil && GetDB() != nil guard existed only for that second test.
    None of them could fail except in lockstep with the code they restate.
    
    * docs(api): describe the setting-driven scanRealityTargets fallback
    
    An empty targets value now probes the realityScanCandidates setting,
    but the endpoint summary, parameter description and handler comment
    still promised the built-in seed list, so API consumers were told the
    wrong target set. Regenerated openapi.json and synced the docs copy,
    which also lacked the new AllSetting field in the settings reference.
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(discord): add Discord notification bot service (#6486)
    * feat(discord): add Discord notification bot service, settings UI, and event subscriber
    - internal/web/service/discord: implement lightweight Discord REST API v10 client and EventBus subscriber
    - internal/web/service/setting: add discordBotEnable, discordBotToken, discordChannelId, discordEnabledEvents, discordCpu, discordMemory settings and secret protection
    - internal/web/controller: register POST /panel/api/setting/testDiscord endpoint
    - frontend: add Discord settings tab, notifications configuration, sidebar navigation, and command palette integration
    - translation: add localization keys across all 13 locales
    - tests: add comprehensive unit tests with httptest server and verify route/i18n contracts
    
    * fix(discord): address PR review findings on concurrency, linting, i18n, and stories
    
    - subscriber: eliminate unbounded goroutines, sending inline per EventBus contract
    - discord: accept context.Context in SendMessage, SendEmbed, SendTest with http.NewRequestWithContext
    - format: apply gofumpt to controller and entity struct alignments
    - i18n: localize testDiscord controller responses across all 13 locales
    - storybook: add DiscordNotifications.stories.tsx component story
    
    * docs: add Discord bot setup and operations guide
    
    - add docs/content/docs/en/operations/discord-bot.mdx with setup steps, event indicators, settings, and troubleshooting
    - add docs/content/docs/ru/operations/discord-bot.mdx with localized instructions
    - update operations/meta.json across en, ru, zh, fa
    - link Discord bot from panel configuration overview
    
    * feat(discord): add discordLang, discordRunTime, discordBotBackup settings and update settings UI
    
    - internal/web/entity: add DiscordRunTime, DiscordBotBackup, DiscordLang fields to AllSetting
    - internal/web/service/setting: add defaultValueMap entries, getters, and setters
    - frontend: update AllSetting schema, model defaults, and generate OpenAPI / Zod contracts
    - frontend: extract shared NotifyTimeField component and update DiscordTab with General and Notifications tabs
    - translation: add localization keys across all 13 locales
    
    * feat(discord): implement scheduled status reports and database backup attachments
    
    - internal/web/service/discord: add SendMessageWithFiles supporting multipart uploads
    - internal/web/service/discord: implement BuildReport and SendReport generating rich status embeds
    - internal/web/service/discord: attach database backup (and config.json) when discordBotBackup is enabled
    - internal/web/job: implement DiscordNotifyJob scheduled via robfig/cron
    - internal/web/locale: add LocalizerFor and I18nForLang helpers
    - internal/web/controller: trigger reloadDiscordFunc to dynamically reschedule cron upon setting changes
    - internal/web/web: register and reschedule DiscordNotifyJob
    - tests: comprehensive unit tests for multipart uploads, status reporting, and job execution
    
    * feat(discord): add interactive bot commands via Gateway WebSocket and update documentation
    
    - internal/web/service/discord/gateway: connect to Discord Gateway v10 via WebSocket (gorilla/websocket)
    - internal/web/service/discord/gateway: handle heartbeat loop, reconnection, and command dispatch
    - commands: implement !status, !report, !backup, !usage <email>, !inbounds, !restart, !help (with ! and / prefixes)
    - internal/web/web: start/stop Gateway client with server and reload dynamically on setting updates
    - docs: update operations guide (en, ru) with scheduled reports, backups, commands, and privileged intents
    - tests: add end-to-end WebSocket Gateway test verifying command handling
    
    * style(discord): fix goimports formatting and add 3x-ui to gitignore
    
    * fix(discord): stop gateway panics, reconnect storms and proxy bypass
    
    The Gateway client wrote to its websocket from both the heartbeat ticker
    and the read loop answering server-requested op 1 heartbeats. gorilla
    panics on concurrent writes and neither goroutine recovers, so a colliding
    heartbeat took the whole panel process down; writes now share writeMu.
    
    It also reconnected every 5s forever after close codes Discord marks
    non-reconnectable (4004 bad token, 4010-4014, including 4014 when Message
    Content Intent is off), re-identifying and logging a warning each time.
    The loop now stops on those codes; the docs say to restart the panel.
    
    The gateway dialed with websocket.DefaultDialer, bypassing the panel
    egress proxy the REST client already uses, so where Discord is filtered
    notifications arrived but commands never connected.
    
    * fix(discord): deliver the scheduled report when the backup upload fails
    
    SendReport posted the report embed and the x-ui.db/config.json attachments
    in one multipart request. Once the database outgrows Discord's upload cap
    (20 MiB by default) the request is rejected and the report embed is lost
    with it on every run, leaving only a log warning. Send the embed first and
    the attachments as a second message.
    
    * chore(discord): delete tests that pass whether or not the code works
    
    TestDiscordNotifyJob_NilServiceNoPanic and TestHandleEvent_NilDiscordService
    feed a nil DiscordService that web.go never passes, and
    TestDiscordNotifyJob_DisabledNoPanic passes with or without the enable
    guard because Xray is not running under test.
    
    * fix(discord): require admin user IDs for bot commands and honor discordLang
    
    Any member who could post in the configured channel could run !backup
    (the whole x-ui.db and config.json, even with discordBotBackup off),
    !restart and !usage. Commands now run only for the Discord user IDs in
    the new discordAdminIds setting; an empty list turns commands off.
    
    discordLang was saved and offered in the UI, but nothing read it, so
    every embed stayed English. The test message, alerts, the scheduled
    report and command replies now render through I18nForLang in the chosen
    language, with a discord section in all 13 locales. InitLocalizer takes
    an fs.FS so tests load the real translation files.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(happ): generate Crypt5 subscription links locally (#6494)
    * feat(clients): add stateless Happ link generator
    
    Generate Happ provider links from the current effective subscription source without caching results. Reject unsafe provider responses and redact failure diagnostics.
    
    * fix(clients): reject duplicate Happ provider fields
    
    Parse Happ provider objects token by token so duplicate supported keys cannot be silently overwritten by encoding/json.
    
    * feat(clients): expose on-demand Happ link API
    
    Expose a no-store client endpoint backed by the Happ link generator and keep its generated OpenAPI contract synchronized.
    
    * fix(openapi): exclude service interfaces from generated types
    
    Keep dependency-injection interfaces out of the frontend API surface while preserving allowed response schemas.
    
    * feat(clients): add stateless Happ QR presentation
    
    Generate Happ links only for the active modal scope and retire late responses so Standard remains immediately available. Add focused component coverage and localized retry guidance across every locale.
    
    * fix(clients): cover overlapping Happ generations
    
    Prove the cancellation cleanup is required by resolving a retired request while its replacement remains pending. Also wait for Regenerate to leave loading state before exercising the existing action.
    
    * fix(clients): harden Happ link handling
    
    Validate generated responses before rendering and hide actions during unresolved requests. Strengthen route, redirect, timeout, and lint regression coverage with mutation-sensitive tests.
    
    * fix(clients): gate Happ link generation behind operator opt-in
    
    - add a fail-closed happLinkEnable setting
    - enforce the gate before and after provider requests
    - add locked Happ QR state with privacy disclosure and settings link
    - cover backend, frontend, settings, and i18n regressions
    
    * fix(frontend): guard oversized Happ QR codes
    
    Keep valid long crypt5 links copyable while suppressing QR rendering and image actions above the encoder's UTF-8 byte limit. Add localized guidance and boundary coverage.
    
    * fix(clients): log the sanitized transport error for Happ link failures
    
    Every fail() call in HappService.Generate passed a string literal as the
    detail, so the sanitizer written for provider errors only ever saw
    constants, and an operator following the QR modal's "check Logs" hint
    found nothing beyond reason=transport. Transport and body-read errors now
    flow through sanitizeHappDetail, which also redacts cookie/session pairs.
    
    Drop TestHappLinkEnableDefaultsOffWithoutPersistingRow: it pinned a getter
    and its constant default, which the Generate gate test already drives.
    
    * fix(frontend): size the Happ QR cap to level L and keep the QR modal mounted on close
    
    HAPP_QR_MAX_BYTES was the level-M capacity (2331) while QrPanel encodes at
    errorLevel "L", whose version-40 byte-mode capacity is 2953, so valid links
    between 2332 and 2953 bytes lost their QR. The cap now matches the encoder
    and a test renders the real QrPanel at the boundary.
    
    Keying the modal content on `open` remounted it on every close, which cut
    the Modal's exit transition and made the openSubId sync unreachable, so
    `loading` never turned on for the subLinks fetch and a client without a
    subscription link flashed noLinks on reopen. `open` leaves the key and the
    sync block now also resets the Happ state.
    
    * chore(clients): request Happ crypt5 links from api-v3
    
    crypto.happ.su serves api-v2.php and api-v3.php side by side. Probed with
    the same payloads, both take {"url"} over a JSON POST, answer
    {"encrypted_link":"happ://crypt5/..."} of identical length with the same
    crypt5 key marker, and fail the same way: 400 "No url provided.",
    500 "Invalid URL format.", 405 on GET. Happ's own generator page is
    branded "URL Encryption v3", so the panel follows it. The parser and the
    link validator are unchanged.
    
    * feat: add local generation of encrypted Happ links
    
    - Implemented functionality to generate encrypted Happ links locally without network dependency.
    - Added validation for URL length and format to ensure compliance with processing limits.
    - Introduced new error handling for invalid URLs and control characters.
    - Updated translations for various languages to reflect changes in Happ link generation.
    - Created unit tests to validate the encryption process and ensure session keys and nonces are unique.
    
    * fix(frontend): match the tuic memo deps to the non-optional subSettings
    
    The Happ branch reads subSettings non-optionally in ClientQrModalContent
    (happLinkEnable and the WireGuard/AmneziaWG publicHost memos), so React
    Compiler infers subSettings.publicHost. The TUIC memo merged in from main
    still listed subSettings?.publicHost, which fails oxlint's
    preserve-manual-memoization rule and makes the compiler skip optimizing
    the component. make verify stopped at lint-fe on the branch head.
    
    * chore(happ): trim the pinned-key provenance comment to two lines
    
    CLAUDE.md caps a comment block at two lines. The bare URL line repeated
    the repository and file the next line already names, so it is folded
    into that line (review LOW on happ_crypto.go).
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): let the panel set the JSON subscription DNS servers (#6485)
    * feat(sub): let the panel set the JSON subscription DNS servers
    
    A baked routing profile (#6402) carries only the DNS its preset defines, so an
    operator who wants their own resolvers has to override the whole profile or
    patch the subscription behind a proxy.
    
    Add the subJsonDns setting: either a full xray dns block or a bare array of
    servers. It wins over the profile's DNS while leaving the profile's routing
    rules intact, and reaches per-inbound, balancer and info-node documents alike.
    
    The value is validated with xray's own schema (internal/xray/dnsconf): a block
    the client could not load is rejected when the settings are saved and ignored
    with a warning at request time, instead of being baked into every document.
    Both the sub server and the settings API share that validator, so a stored
    value can never be silently dropped.
    
    xray's Build() is deliberately not used for validation: it resolves geosite
    tokens from the geodata files and would reject valid configs whenever those
    are absent from the panel's working directory.
    
    * style(dnsconf): drop the ineffectual initial map assignment
    
    golangci's ineffassign flagged the zero-value map whose value both paths
    overwrite: the object branch now assigns the decoded map directly.
    
    * docs(sub): scope the DNS setting to the documents it rewrites
    
    The Routing header mirrored to Happ/INCY keeps the routing profile's own
    resolvers, so the setting description and the header-source comment now say
    so instead of claiming the profile's DNS is replaced everywhere.
    
    Also trims two comments in the new dnsconf package to the repo's two-line cap.
  • feat(sub): bake Happ/INCY routing profiles into the JSON subscription (#6402)
    * feat(sub): parse generic Happ/INCY routing payloads for the JSON subscription
    
    Accepts the routing-rules format emitted for Happ and INCY (inline JSON,
    happ:// or incy:// deeplink, or a remote https:// URL resolved through the
    existing remote routing cache). The JSON subscription will bake these
    rules into its documents so header-ignoring clients still get routing.
    
    * feat(sub): bake Happ/INCY routing profiles into JSON subscription documents
    
    When subJsonRoutingRules is set, every emitted document (per-inbound and
    balancer alike) carries the profile's dns and routing rules baked in, so
    header-ignoring clients like Happ and INCY still get routing; the legacy
    simple-rules merge only applies when no profile is set. The balancer
    document builder keeps rewriting proxy-tag rules to the balancer.
    
    * feat(sub): add the subJsonRoutingRules setting
    
    Plumbed from the settings store through the subscription server into
    SubJsonService, so admins can set a routing profile once and every JSON
    subscription document carries it.
    
    * chore(api): regenerate OpenAPI artifacts for subJsonRoutingRules
    
    * feat(web): routing profile editor for the JSON subscription
    
    A textarea inside the JSON card accepts the routing profile (inline JSON,
    happ/incy deeplink, or https URL) with a remote-source badge; the badge
    helper moves to a shared module. Keys added to all 13 locales.
    
    * fix(sub): warm and lazily resolve the baked JSON routing source
    
    The routing profile was resolved once at service construction: a remote
    URL that was cold at that moment baked default routing forever, and the
    cron job never warmed it. The job now warms the subJsonRoutingRules URL,
    and the profile resolves per request with an in-memory memo (a failed
    resolve is not cached), so a warmed cache takes effect without a restart.
    
    * feat(sub): fall back to the JSON routing profile for the Routing header
    
    Happ and INCY download the geo files a routing profile references
    through the Routing response header. When the Happ header setting was
    blank the header stayed unset, and clients fetched no geo files even
    though a JSON routing profile was configured. A blank setting now falls
    back to the JSON profile: happ/incy deeplinks pass through, inline JSON
    and remote URLs are normalized to a happ:// deeplink; an unusable or
    oversized value leaves the header unset. Locale captions mention the
    fallback.
    
    * fix(sub): pass routingRules arg at call sites added by main
    
    Main gained four NewSubJsonService call sites after this branch forked;
    update them to the five-arg signature so internal/sub builds again.
    
    * fix(sub): address code review findings on the baked JSON routing
    
    The memoised baked template never invalidated, so an edited remote
    profile kept serving the superseded dns/routing subtrees until a panel
    restart; bakedTemplate now re-resolves the spec per request and rebuilds
    only when the payload actually changed (regression-tested).
    
    subJsonRoutingRules shared the happ persistence row with
    subRoutingRules, so only the last-written setting survived a restart;
    it now resolves under its own jsonhapp kind with the same validation
    and size caps. The setting also joins validateSettingsURLs, so remote
    values are canonicalised and bad URLs are rejected on save.
    
    Also: drop the unreachable half of the remote-source guard, cut the
    overlong comment blocks to the two-line convention, and deduplicate
    remoteSourceBadge in the General tab. Merges upstream/main (call sites
    for the widened NewSubJsonService signature).
    
    * style(sub): gofumpt the json_routing imports
    
    * fix(sub): accept happ add/ deeplinks and bound the routing warning
    
    The baked-JSON routing parser only recognised happ://routing/onadd/, but
    normalizeHappRouting treats happ://routing/add/ as an equally valid routing
    deeplink. An operator pasting the add/ form got the Routing header set, so
    the panel looked configured, while every JSON subscription document silently
    carried the default routing instead of their profile.
    
    resolveJsonRoutingSpec logged one warning per call and bakedTemplate calls it
    once per emitted document, so a single fetch of an unusable profile wrote one
    identical warning per document. On the public subscription server that floods
    the 10240-entry buffer the panel's log view reads, evicting real entries. Log
    only when the message changes, and reset on a successful resolve so a profile
    that recovers and fails again is still reported.
    
    Also resolve the template once in buildBalancerConfig: two resolves could
    straddle a profile refresh and pair one revision's dns with the other's
    routing.
  • feat(sub): add Happ client integration, routing presets, and app management (#6434)
    * feat(sub): add Happ client integration, routing presets, and app management
    
    Implement comprehensive Happ proxy client integration according to official developer specifications.
    
    - Fix header emission on disabled routing and hidden settings to send explicit '0' headers rather than omitting, allowing Happ clients to reset cached settings.
    - Add support for 'happ://routing/off' deeplink in routing validation.
    - Preserve '?serverDescription=' query parameters in link fragments without escaping to support Happ server subtitles across VMess, VLESS, Trojan and SS.
    - Add Happ application management headers: ProviderID, New-Url, Fallback-Url, Sub-Info banners, Sub-Expire notifications, No-Limit mode, hardware ID enforcement, TUN modes/types, route exclusions, APNS exclusions, and per-app proxy settings.
    - Add curated routing presets (Iran Bypass, China Direct, AdBlock, Global) and interactive visual rule generator in frontend settings.
    - Synchronize all 13 translation locales with native Persian, Russian, and Chinese translations.
    
    * fix(sub): keep Happ header overrides behind the auto-detect opt-in
    
    The Routing-Enable/Hide-Settings off values were emitted on the
    User-Agent alone, so every panel that upgraded would push
    "Routing-Enable: 0" — documented by happ.su as disabling routing
    globally — to every Happ client without the operator enabling anything.
    They now ride subHappAutoDetect like every other Happ header.
    
    Two further mismatches against the vendor spec:
    
    - serverDescription was written as a key of the VMess base64 JSON
      object. happ.su documents it as a "#Title?serverDescription=<base64>"
      link parameter or a JSON "meta" entry, so the caption never reached
      Happ while every other VMess consumer received an unknown key.
      Dropped rather than moved: emitting the documented form is unsafe
      here because our own parser base64-decodes the whole VMess body
      (internal/util/link/outbound.go).
    
    - The TUN Mode dropdown stored the literal "default", forwarded as
      "Tun-Mode: default", where happ.su documents system|gvisor only. It
      now stores the unset value so no header is sent. TUN Type "default"
      is a documented value and is unchanged.
    
    Each fix carries a test that fails without it.
  • feat(sub): add dummy info node and status configs for subscriptions (#6412)
    * feat(settings): add subInfoNodeEnable and status template settings
    
    * feat(sub): add dummy info node and status configs for raw links
    
    * feat(sub): support dummy info node in clash and json subscriptions
    
    * feat(ui): add subscription info node switch and status templates to settings
    
    * style: apply gofumpt formatting
    
    * fix(sub): address review feedback on subscription info node
    
    - Restore GetSubs contract to avoid unintended remark expansions on non-subscription-body calls.
    - Exclude dummy info node from Clash PROXY select group when active server nodes exist.
    - Track hasEnabledClient and set traffic.Enable in JSON and Clash paths so status tokens evaluate correctly.
    - Deterministically sort client emails across subscriptions before selecting primaryEmail.
    - Consolidate duplicated info-node evaluation logic into resolveInfoNodeRemark helper.
    - Remove redundant pure-getter test from setting_sub_info_node_test.go.
    
    Co-Authored-By: Claude Code <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Code <noreply@anthropic.com>
  • feat(sub): client-side balancers for the JSON subscription (#6243)
    * feat(sub): add SubBalancer model and migration
    
    Client-side JSON-subscription balancer row: remark, strategy, member inbound ids, sort order, enabled. Registered in allModels and migrationModels so AutoMigrate and SQLite->Postgres copy pick it up.
    
    * feat(sub): add SubBalancer service
    
    List/Get/Create/Update/Delete over the sub_balancers table with remark trim, strategy allowlist (leastLoad/leastPing/random) and sort-order floor. Rows are read per request by the subscription builder, so mutations need no xray restart.
    
    * feat(sub): add SubBalancer API controller and routes
    
    GET/POST /panel/api/sub-balancers, POST /:id (update), DELETE /:id and POST /:id/del alias. inboundIds bind from repeated form keys. Mounted under the /panel/api group so the existing API token + CSRF middleware cover it.
    
    * feat(sub): emit client-side balancers in JSON subscription
    
    For each enabled balancer, append one config document whose outbounds are the selected inbounds' proxy outbounds retagged under a per-balancer prefix, with routing.balancers + burstObservatory selecting it. Balancer entries interleave with inbound entries by sort order; on equal numbers the balancer follows the inbound. Skipped when disabled or no member outbound is present.
    
    * test(sub): cover SubBalancer service and JSON output
    
    Service: validation gates (remark/strategy/inbound ids/sort order) and CRUD round-trip. JSON: balancer document shape, sort interleaving with inbounds, disabled/empty skip, and member tag dedup.
    
    * feat(sub): add sub-balancers i18n keys
    
    pages.settings.subBalancers.* block (menu, title, add, desc, field labels, strategy names, sort-order help, validation messages) added to all 13 locales.
    
    * feat(sub): add SubBalancer schema and API queries
    
    Zod schema (entity + form, strategy enum, validation messages wired to i18n keys), react-query hooks for list/create/update/delete, and the sub-balancers query key.
    
    * feat(sub): add subscription balancers settings tab
    
    SubscriptionBalancersTab lists balancers (sort order, remark, strategy, inbound count, enabled toggle, edit/delete) with a form modal (remark, strategy, sort order, multi-select inbounds filtered to multi-client protocols, enabled). Wired into SettingsPage under #subscription-balancers, and the sidebar shows the entry only when JSON subscription is enabled.
    
    * test(sub): add SubBalancer form modal test
    
    Covers add-mode (no validation errors, confirm with parsed values) and edit-mode (seeds from the balancer, preserves strategy/sort order/enabled).
    
    * feat(sub): register sub-balancers in API docs and OpenAPI
    
    Adds the sub-balancers endpoint group to endpoints.ts (list/create/update/delete + POST del alias) and regenerates frontend/public/openapi.json from it.
    
    * docs: sync openapi.json with frontend
    
    docs/public/openapi.json had fallen behind frontend/public/openapi.json (fewer paths/schemas). Copy the current frontend spec so the docs site renders the full API.
    
    * docs: add subscription balancers API reference
    
    Registers the sub-balancers page (generated MDX) and adds the sub-balancers paths to docs/public/openapi.json so the page renders the list/create/update/delete operations.
    
    * feat(sub): accept roundRobin balancer strategy
    
    Add roundRobin to the model oneof tag and the service strategy allowlist, alongside leastLoad/leastPing/random. Covered by a service-level create test that fails on the old allowlist.
    
    * feat(sub): add roundRobin strategy label
    
    pages.settings.subBalancers.strategyRoundRobin added to all 13 locales.
    
    * feat(sub): expose roundRobin in balancer form
    
    Zod strategy enum, form modal label key, and table strategy colour for roundRobin.
    
    * docs(sub): list roundRobin in strategy description
    
    The create/update strategy param description now mentions roundRobin alongside the other three.
    
    * feat(sub): add subJsonObservatory setting
    
    Panel-wide JSON string carrying the burstObservatory ping config (destination, connectivity, interval, sampling, timeout, httpMethod) emitted into client-side balancer docs. Stored like subJsonMux/Rules/FinalMask.
    
    * feat(sub): wire observatory config through sub controller
    
    WithSUBJsonObservatory option; the controller calls SubJsonService.SetObservatoryConfig after construction.
    
    * feat(sub): emit observatory conditionally with configurable probes
    
    burstObservatory is emitted only for leastPing/leastLoad; random/roundRobin get none (no fallback, so an observatory would only probe for nothing). Probe params come from the subJsonObservatory setting, falling back to the built-in defaults when empty or partial. Test covers the conditional emit and the override.
    
    * feat(sub): add subJsonObservatory to AllSetting model
    
    Frontend AllSetting model and Zod schema carry the new panel-wide observatory config string.
    
    * feat(sub): add balancer observatory config card
    
    New Sub Formats tab editing destination/connectivity/interval/sampling/timeout/httpMethod, stored as JSON in subJsonObservatory. Toggle off clears the setting; the backend then falls back to defaults.
    
    * fix(sub): hide save/restart header on sub-balancers tab
    
    Sub-balancer mutations are incremental (own CRUD API, no Save, no restart), so the page-wide 'every change needs to be saved / restart the panel' banner is misleading there. The in-tab alert already explains it correctly.
    
    * feat(sub): add observatory config i18n keys
    
    pages.settings.subBalancers.observatory.* (title, desc, probe field labels and help texts) added to all 13 locales.
    
    * feat(sub): regenerate openapi for subJsonObservatory
    
    openapigen picks up the new AllSetting field; openapi.json synced into docs.
    
    * feat(sub): add observatory tab to sub-balancers
    
    Mirrors the Xray Balancers page: two tabs (Balancers + Observatory).
    Wires allSetting/updateSetting into the tab and adds tabBalancers /
    tabObservatory labels to all locales. The page Save header is shown
    again on this tab so the observatory config can be saved.
    
    * refactor(sub): drop observatory tab from sub-formats
    
    Now that the observatory config lives under sub-balancers, remove the
    duplicate tab plus its state and defaults from sub-formats.
    
    * fix(sub): add missing inboundsCount i18n key
    
    The sub-balancers table rendered the raw key path in the Inbounds
    column because pages.settings.subBalancers.inboundsCount was not
    defined. Added it to all 13 locales.
    
    * test(sub): pin disabled-inbound exclusion from balancer
    
    The balancer builds its members from the subscriber's already-filtered
    entry set, so an inbound disabled for that user can never surface as a
    member. Adds tests for both shapes (one of several disabled, and the
    only selected one disabled).
    
    * fix(sub): make observatory toggle honest, default connectivity off, add balancer fallback
    
    Three coupled defects on the balancer observatory surface, flagged in PR review:
    
    - The Observatory Switch wrote '' which the Go side treats as "use built-in defaults", so leastPing/leastLoad still shipped a burstObservatory the admin could no longer see or edit. The observatory is mandatory for these strategies (Xray refuses to start leastPing/leastLoad without one — verified against Xray 26.7), so the switch is relabelled to "customise probe parameters vs built-in defaults" rather than on/off: '' keeps the defaults, a stored JSON overrides them. An info Alert explains this.
    
    - Connectivity defaulted to http://www.google.com/generate_204 and an explicit {"connectivity":""} restored it, so the UI's "Leave empty to skip" was unreachable and the direct pre-check was dead on arrival on censored client networks. Default to "" and honour an explicit empty value.
    
    - routing.balancers had no fallbackTag, so a leastPing/leastLoad balancer whose probes all fail selects nothing and dispatch fails. Emit fallbackTag pointing at the first member so a probe outage degrades instead of breaking.
    
    Also skip balancer entries (kind!=0) in the member scan so a balancer can never match another balancer's row id. Tests cover each fix and fail without it.
    
    * fix(sub-balancer): localize controller toasts and reject malformed ids
    
    Route the new controller's user-facing messages through I18nWeb so non-English admins get localized toasts like every other controller, and switch parseID to strconv.Atoi rejecting ids < 1 so "12abc" and negative ids no longer coerce to a silent no-op delete that reports success.
    
    * fix(sub-balancer): enforce remark length cap server-side
    
    The model's validate:"max=256" tag was never enforced (parseSubBalancerForm binds an ad-hoc struct without validate.Struct), so a scripted API client could store an unbounded remark that is emitted verbatim as the remarks field of every affected subscriber's config. Reject len > 256 in validate() to match the frontend Zod cap.
    
    * fix(sub-balancer): exclude mtproto from balancer member picker
    
    SubJsonService.getConfig has no mtproto case, so an mtproto inbound's first outbound is "direct" and the buildBalancerConfig "tag != proxy" guard drops it — an admin could select it, save without error, and get a balancer that silently omits it (or no document at all). Drop it from the picker and fix the comment.
    
    * docs(sub-balancers): add nav entry, fix tab pointer, note mirror scope
    
    - Add "subscription-balancers" to the en reference/api meta.json pages array so the new MDX page is reachable from the sidebar (fa/ru/zh have no MDX — gen-openapi.ts emits into en only).
    
    - Fix the endpoints.ts section description from "Settings -> Subscription" to "Settings -> Sub Balancers" (the feature's own tab) and regenerate the OpenAPI spec + MDX.
    
    - Note in docs/lib/xray/subscription.ts that balancer documents are intentionally out of scope for that mirror.
    
    * style(model): trim SubBalancer comment to 2-line cap
    
    CLAUDE.md caps committed Go comment blocks at 2 lines; this one was 3.
    
    * fix(sub-balancer): parse enabled explicitly and preserve it on partial update
    
    parseSubBalancerForm treated any non-"false" value as true (so "bogus"
    silently enabled) and always overwrote Enabled on update, so a PATCH that
    omitted the toggle reset a disabled balancer back to enabled. Parse the
    field with strconv.ParseBool and return *bool: absent means "no change"
    on update and "true" on create; a malformed value is rejected as 400.
    Update keeps the stored Enabled when the pointer is nil.
    
    * fix(sub-balancer): clear deleted inbound from sub_balancers.InboundIds
    
    DelInbound cascaded hosts but left the deleted inbound id in every
    sub_balancers.InboundIds, so the balancer kept emitting a member no
    subscriber could resolve — a dangling outbound tag with no proxy behind it.
    Strip the id inside the existing delete transaction (same shape as the hosts
    cascade, #5648); with the last member gone the balancer stops emitting.
    
    * fix(sub-balancer): return not-found when deleting a missing balancer
    
    Delete returned the gorm result error only, which is nil when no row matched,
    so the controller reported success:true for an id that never existed — a stale
    UI row looked like a clean delete. Check RowsAffected and return a not-found
    error on 0 so the toast reflects reality.
    
    * style(sub): shorten leastPing/leastLoad observatory comments
    
    The observatory-emission guard comment and its test comment ran a few
    lines long; trim them to a couple of lines each without dropping the
    invariant that leastPing/leastLoad require a burst observatory.
    
    * fix(sub): validate observatory setting instead of silently dropping it
    
    SetObservatoryConfig applied whatever survived json.Unmarshal with no checks,
    so a bad probe URL ("not-a-url"), non-duration interval/timeout, or even
    unparseable JSON was either silently applied or silently ignored. Validate
    each field: parse durations with time.ParseDuration, require http(s) URLs for
    destination/connectivity, and log a warning naming the field and the bad value
    on every fallback — including the unmarshal error, which was a quiet return.
    Bad values now keep the built-in defaults instead of leaking into the emitted
    burstObservatory.
    
    * fix(sub): deduplicate burst-observatory defaults across Go and frontend
    
    The burst-observatory ping defaults lived in three places that had drifted:
    Go defaultSubBalancerObservatoryConfig (http probe, sampling 3), the Zod
    PingConfigSchema, and DEFAULT_BURST_OBSERVATORY (both with a connectivity
    pre-check URL). Align them to one set: https probe destination, sampling 2,
    and empty connectivity (skip the direct pre-check). The settings tab now
    parses the stored JSON through PingConfigSchema and seeds its default from
    DEFAULT_BURST_OBSERVATORY instead of carrying its own literal.
    
    * refactor(sub): extract proxy outbounds once before the balancer loop
    
    buildBalancerConfig unmarshalled every inbound document and re-extracted its
    first outbound on each balancer, so with B balancers and N inbound docs the
    same document was parsed B*N times. Pull each doc's proxy outbound in a single
    pre-pass over the entries and cache it per entry; buildBalancerConfig now
    clones the cached map before retagging, so one parse serves every balancer.
    Output is byte-for-byte unchanged.
    
    * fix(sub): form balancer member tags from the inbound protocol, not tcp→vless
    
    balancerTransport derived the bal-N tag suffix from the outbound's transport
    network and hard-coded tcp→vless, so a vmess/tcp or trojan/tcp member was
    mislabelled "vless" in every client config — the tag lied about the proxy
    type. Use the outbound's real protocol as the suffix (bal-1-vmess, bal-1-vless,
    bal-1-trojan, …) so the tag names the actual proxy; the selector prefix and
    dedup suffix are unchanged. Update the existing tag assertions and add a vmess
    case that fails under the old mapping.
    
    * fix(sub-balancer): default strategy to random in the create form
    
    The create-balancer form seeded strategy to 'leastLoad', but the service
    validate() defaults an empty strategy to 'random' and the API docs say the
    default is 'random' — so a freshly opened form showed leastLoad while saving
    without touching the field silently stored random. Align the form default to
    'random' so what the admin sees is what gets persisted.
    
    * feat(api-docs): document the SubBalancer response schema
    
    The five sub-balancer endpoints carried no responseSchema, so the API docs
    page rendered them without a typed example. Add example: tags to every
    SubBalancer field, allow the struct through openapigen, and point the list
    (responseSchemaArray) and single-row endpoints at 'SubBalancer'. Regenerate
    the Zod/JSON schemas and OpenAPI doc and mirror openapi.json into docs/.
    
    * style(sub-balancer): drop whitespace-only separator lines, add final newline
    
    subBalancer.ts and SubBalancerFormModal.tsx used single-space blank lines as
    separators between statements and had no trailing newline. Replace them with
    clean empty blank lines and end each file with a newline.
    
    * fix(i18n): translate sub-balancer toasts and observatory note
    
    The sub-balancer toast messages (list/create/update/delete/invalidId) and
    the observatory note were left in English across 11 non-English locales
    (ar, es, fa, id, ja, pt-BR, tr, uk, vi, zh-CN, zh-TW) while every other key
    in the subBalancers block was already translated. Translate them to match the
    meaning and terminology of the surrounding keys in each file; the JSON
    structure and keys are unchanged.
    
    * fix(sub-balancer): hide disabled inbounds from the member picker
    
    The picker offered every protocol-eligible inbound regardless of its enable
    flag, but getInboundsBySubId filters `AND inbounds.enable = true`. A disabled
    member is therefore dropped from every subscriber's entries, and when it was
    the balancer's only member the balancer document silently stops being emitted
    — with nothing in the UI explaining why. TestSubJson_BalancerSkippedWhenAll
    MembersDisabled already documents that backend behavior.
    
    Filter the way the sibling client picker has since #5645: hide disabled
    inbounds, but keep one that is already selected so editing an existing
    balancer cannot silently drop a member.
    
    Drop the `?? []` on the useWatch result so the new useMemo dependency stays
    referentially stable.
    
    * style(sub): trim the balancerMemberSuffix comment to the 2-line cap
    
    Comment blocks in committed Go are capped at 2 lines; the name already carries
    what the function picks, so keep only the why.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
    Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
  • fix: follow-ups from the post-merge reviews of #6221, #6227, #6230 and #6239 (#6250)
    * fix: follow-ups from the post-merge reviews of #6221, #6227, #6230 and #6239
    
    Six defects the automated reviews found after those PRs merged. Each is
    verified rather than taken on trust — two by experiment, the rest by
    reading the merged code.
    
    **Import restore never wrote an empty local value** (#6227). GORM builds
    the assignment map from the struct passed to Assign and drops zero-valued
    fields, so `Assign(model.Setting{Value: ""})` produced an empty Updates
    and the imported row survived. Empty is the normal state: UpdateAllSetting
    writes a row for every AllSetting field including the blank ones. That is
    exactly the case the PR existed for — a destination with no certificate
    inheriting the source machine's path. Confirmed with a throwaway test
    before changing anything: the value stayed "IMPORTED". Now uses
    saveSetting, which is not zero-filtered.
    
    **Import destroyed node mTLS material** (#6227). The "no local row means
    the default applied, so drop the import" branch fires for the five
    nodeMtls* keys, which are minted on demand and deliberately absent from
    AllSetting, so a fresh install has no row for them. Reinstall-then-restore
    therefore deleted the CA certificate and its private key — and the backup
    was the only copy, since neither is surfaced in the UI or the export.
    Those keys are now kept.
    
    **The clients-list enable toggle wiped renewal state** (#6239, #6238).
    setEnable hand-builds the update payload and carried reset but not
    resetDay or resetMax, so one click on the switch turned calendar mode off
    and lifted the renewal cap permanently. The form-modal tests could not
    catch it because that path does send both fields.
    
    **"Delete depleted clients" deleted calendar clients** (#6239). The
    predicate read `reset = 0` as "does not auto-renew", which is exactly the
    calendar shape, in two places. Both now share one constant that also
    requires `reset_day = 0`.
    
    **Allowlist validation and parsing disagreed** (#6230). Save used net,
    scan used netip, and they differ: `198.51.100.0/024` saves without
    complaint and is silently dropped at scan — the failure the PR set out to
    remove. Verified by running both parsers. An IPv4-mapped prefix parsed but
    could never match, because contains() unmaps the query while the prefix
    stayed 128-bit; it is unmapped at parse now. A test asserts the two
    acceptance sets agree.
    
    **A comment stated the opposite of the truth** (#6221). GetInbounds has no
    enable filter, so a node reports a disabled inbound normally; the row in
    that bug report was missing only because it was never delivered. Reworded
    to the real invariant.
    
    Also trims two comment blocks in ip_limit_allowlist.go to the repo's
    two-line maximum.
    
    Not included: the reviewer's suggestion to lift the node hand-off out of
    `if inbound.Enable` in AddInbound. It is the right root-cause fix, but it
    changes delivery behaviour on multi-node deployments and belongs in its
    own change with its own testing, not in a cleanup batch.
    
    One reported finding is not real: BulkCreate does call
    validateClientResetDay, validateClientResetMax and
    validateClientTrafficReset — verified in the merged tree.
    
    * fix(netsafe): wrap both errors so errorlint passes
    
    Unrelated to this PR's subject and in a file it does not otherwise touch.
    It is here only because CI lints the merge result, and `main` has been red
    since #6242 landed: `fmt.Errorf("%w; %v", ...)` wraps the first error and
    formats the second, which errorlint rejects. Go 1.20 allows more than one
    %w, so both are wrapped now and `errors.Is` works against either.
  • feat(limitip): let operators exempt trusted addresses from the IP limit (#6230)
    * feat(limitip): let operators exempt trusted addresses from the IP limit
    
    Behind a shared address — an office gateway, a campus NAT, a residential
    carrier — every user looks like the same client. One of them trips the IP
    limit and the address is disconnected and handed to fail2ban, taking the
    others with it. Today the only way out is editing jail.d by hand, which an
    update overwrites.
    
    Add an allowlist setting of addresses and networks. A matching address is
    neither banned nor counted towards the limit: counting it would still cut the
    shared network the entry exists to protect.
    
    Entries are validated on save rather than skipped at scan time — a typo would
    otherwise leave the address unprotected until someone noticed the bans.
    
    * fix(limitip): keep each doc comment on its function and one grammar for the list
    
    Three review follow-ups. loadAllowlist landed between hasLimitIp's doc comment
    and hasLimitIp itself, so godoc showed one function's rationale above another's
    body; it now sits after that function with its own comment.
    
    The parser advertised semicolons and whitespace as separators while the
    settings validator accepts commas only, making those forms unreachable through
    the panel and the API — a promise the software never keeps. Both sides now read
    the same comma-separated grammar.
    
    The dist stub was a build artifact and does not belong in the tree.
    
    * chore: drop the accidentally committed dist build stub
    
    internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
    it changes fresh-clone behaviour for everyone: today a bare go build fails
    loudly on //go:embed all:dist, which is the documented signal to run the stub
    target; with the file present the build succeeds and the panel serves an empty
    dist instead.
    
    * chore(i18n): translate the IP limit allowlist strings into the remaining locales
    
    Ten locales carried the English source text verbatim; only ru-RU and uk-UA
    were translated. The i18n dead-key test only checks that a key exists in every
    file, so an untranslated value passes it silently.
    
    Wording follows each locale's existing terms: the ipLimit noun already in the
    file, and the comma-separated IP/CIDR phrasing from trustedProxyCidrsDesc.
    
    * refactor(limitip): share one IP/CIDR list validator and read the allowlist only when enforcing
    
    The allowlist check in CheckValid was a line-for-line copy of the trusted-proxy
    loop directly above it. Both now call one helper, each passing its own message,
    so the two lists cannot drift apart.
    
    Run() read the allowlist on every 10s scan, including the majority of panels
    where no client carries an IP limit and the value is discarded. It is now read
    only once enforcement is known to apply.
    
    CheckValid had no test for either list. The new one pins that a malformed entry
    is rejected and that each list still names itself in the error, which is what
    the shared helper could otherwise break.
    
    ---------
    
    Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): allow identity tokens on every subscription link (#5935)
    Keep usage tokens first-link-only while adding an opt-in setting for repeating EMAIL and USERNAME in subscription-body remarks.
    
    Co-authored-by: x06579 <x06579@ai-dashboard>
  • feat(notifications): add a consecutive-failure threshold for outbound.down alerts (#5968)
    Problem: a flaky outbound produces hundreds of false-positive "outbound down"
    notifications overnight — each fires the moment xray's observatory reports a
    single failed probe, and the next successful probe fires an "up".
    
    applyObservatory forwarded every raw alive:true->false transition straight to
    EventOutboundDown; xray's observatory has effectively no hysteresis, and nothing
    on the panel side debounced it (the email/Telegram subscribers are pure
    formatters).
    
    Fix: debounce per outbound. outbound.down now fires only after
    outboundDownThreshold consecutive FAILED probes (new setting, default 3);
    outbound.up fires immediately on the first successful probe and only when a down
    was actually notified. The threshold gates the event itself, so email and
    Telegram share one knob (exposed next to the outbound.down toggle).
    
    The streak counts genuinely new probes (last_try_time advancing), not sampler
    polls — the sampler runs every 2s but the observatory re-probes per its
    probeInterval, so counting samples would trip the threshold instantly.
    outboundDownThreshold=1 reproduces the legacy notify-on-first-failure behaviour.
    
    Tuning the observatory's probe interval/timeout is not a workaround: those
    probes also drive the load balancer's outbound selection, so loosening them to
    quiet notifications would slow real failover away from a genuinely dead
    outbound. Notifications don't need observatory-grade latency, so the tolerance
    belongs at the notification layer, leaving the observatory (and balancer)
    untouched.
    
    Adds TestApplyObservatoryDebounce covering the threshold, probe-vs-sample
    counting, single-blip suppression and the legacy path.
    
    Co-authored-by: Yuriy Khachaturian <y.khachaturian@souzmult.ru>
    Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
  • Repo-wide self-correcting audit: 54 verified bug fixes (#5970)
    * fix(email): resolve a name-addr smtpFrom into bare envelope address and display name
    
    The save-time validator accepts any RFC 5322 address form, so a value
    like '3x-ui Panel <panel(at)example.com>' passes validation, but Send and
    TestConnection fed that raw string to MAIL FROM, which strict servers
    reject with 501, and buildMessage mangled it into a quoted local part.
    Parse the configured sender at the point of use: the envelope gets the
    bare address and, when no explicit sender name is set, the display name
    embedded in the setting is used for the From header.
    
    * fix(email): report a missing sender address from the SMTP connection test
    
    TestConnection skipped the empty-from guard that Send enforces, so with
    no sender and no username configured the test issued the null reverse-path
    and could report success against a lenient relay while every real
    notification send kept failing with the missing-sender error. Guard the
    test path the same way and surface a dedicated translated message.
    
    * fix(sub): fall back to the raw subscription when an auto-detected format has no content
    
    With format auto-detection enabled, a client whose User-Agent matched the
    Clash or JSON regex was routed straight to that format handler. For a
    subscription whose entries convert to neither format (an MTProto-only
    subscription, for example) the handler returns an empty document and the
    request ended as 404, breaking a URL that served the raw list before the
    toggle. The auto-detect branches now serve the detected format only when
    it produces content and otherwise continue to the raw response; the
    explicit format endpoints keep answering 404 for empty documents.
    
    * fix(node): match prefixed central tags when filtering a selected-mode node snapshot
    
    FilterNodeSnapshot compared a node snapshot's inbound tags against the
    raw selected-tag list with an exact match, while its two siblings
    (SnapshotHasUnadoptedInbounds and the reconcile tagToCentral map) expand
    each selected tag to both its bare node-side form and its n<id>- prefixed
    central form. A panel-created node inbound is recorded in the selected
    list under the central prefixed tag but reported by the node under the
    bare tag, so the exact match dropped it from every snapshot and the
    orphan sweep then deleted its central row one tick after creation. Expand
    the allowed set with the same prefix flip the siblings use.
    
    * fix(client): refuse a bulk quota reduction that would fall to or below zero
    
    BulkAdjust clamped a client's new traffic limit with max(total+addBytes, 0).
    Because 0 is the unlimited sentinel, reducing a client's quota by more than
    it had left silently granted that client unlimited traffic. The sibling
    expiry branch already refuses an over-reduction; mirror it for quota so the
    adjustment is skipped with a clear reason instead of crossing the sentinel.
    
    * fix(client): persist a bulk adjustment's applied field even when the sibling field is skipped
    
    In a mixed BulkAdjust (both a days delta and a bytes delta), a per-field
    planning skip such as "unlimited expiry" or "unlimited traffic" was recorded
    in the same map that gated the client_traffics write. The applied field was
    already written to the inbound JSON and the clients table, but the enforcement
    row was left untouched, so the depletion job cut the client on the old limit
    while the panel showed the new one. Gate the traffic-row write on an actual
    inbound-processing failure rather than on any planning-phase skip note.
    
    * fix(inbound): always create in AddInbound instead of overwriting a row whose id was posted
    
    The add controller binds the inbound model's id form field and never clears
    it, and AddInbound persisted with GORM Save, which updates in place when the
    primary key is non-zero. A client that reused an existing id (for instance by
    duplicating an inbound fetched from /get and changing the port) silently
    overwrote that stored row instead of creating a new inbound. Zero the id at
    the top of AddInbound, matching how it already zeroes the client-stat ids.
    
    * fix(inbound): accept WireGuard clients when creating an inbound
    
    AddInbound's per-client validation switch had cases for every protocol
    except WireGuard, so a WireGuard client fell through to the default branch
    that requires a non-empty id. WireGuard clients are keyed by their public
    key and carry no id, so importing a WireGuard inbound or re-adding one to a
    reconciling node was rejected with "empty client ID". Add a wireguard case
    that validates the client key, mirroring addInboundClient.
    
    * fix(client): stop holding the inbound-lock registry mutex while waiting on one inbound
    
    lockInbound acquired the global registry mutex and then blocked on the
    per-inbound mutex without releasing the registry first. A slow client
    operation holding one inbound's mutex (for example a bulk delete pushing to
    an unreachable node) made the next waiter park on that inbound while still
    holding the registry mutex, which in turn blocked lockInbound for every
    other inbound — freezing client mutations panel-wide. Release the registry
    mutex before taking the per-inbound lock.
    
    * fix(client): honor keepTraffic when deleting a client that is attached to inbounds
    
    Delete, DeleteByEmail and BulkDelete all pass keepTraffic to their final
    cleanup transaction, but each called the per-inbound delete helper with a
    hardcoded false. That helper purges the client's traffic, IP and stat rows
    before the gated cleanup runs, so keepTraffic=true still destroyed all
    traffic history for any client actually attached to an inbound (the pinned
    test only covered a record with no inbound mappings). Thread the caller's
    keepTraffic through to the per-inbound helper at all three call sites.
    
    * fix(inbound): defer a local MTProto inbound edit's sidecar push until after commit
    
    UpdateInbound applied a local MTProto inbound change by calling the runtime
    UpdateInbound (which stops/starts the mtg sidecar or talks to it) from inside
    runSerializedTx. That runs process and network I/O on the single traffic-writer
    goroutine while a DB transaction is open, so a slow sidecar stalls traffic
    accounting and every concurrent client mutation, and a later step failing the
    transaction leaves the sidecar ahead of the rolled-back row. Move the push into
    the post-commit hook, matching the xray branch. Adds a SetLocalRuntimeOverride
    test seam mirroring the existing node override so the deferral is regression
    tested.
    
    * fix(client): delete external-link rows when bulk-deleting clients
    
    The single-client Delete path removes a client's client_external_links rows,
    but BulkDelete (and the DelDepleted reaper that routes through it) deleted the
    record, mappings and traffic while leaving the external-link rows keyed by the
    now-dead client id, so they accumulated as orphans. Delete them in the same
    cleanup transaction, keyed by client id like the single path.
    
    * fix(inbound): request an xray restart when toggling a routed MTProto inbound
    
    AddInbound, DelInbound and UpdateInbound all flag needRestart when an inbound
    routes MTProto through xray, so the egress SOCKS bridge is regenerated. Only
    SetInboundEnable's local path omitted it, so toggling a routed MTProto inbound
    off then on left the bridge out of the running config while the sidecar dialed
    its loopback port, blackholing that inbound until an unrelated restart. Flag the
    restart on the local enable path too.
    
    * fix(client): apply enable-by-email to every inbound a client is attached to
    
    ToggleClientEnableByEmail (Telegram bot) and SetClientEnableByEmail (LDAP sync)
    resolved a single inbound via the legacy client_traffics pointer and flipped
    enable only there. A client attached to several inbounds kept connecting through
    the siblings' running Xray after being disabled, and the next edit could
    re-enable it everywhere from a stale sibling. Route both through the
    applyClientFieldByEmail fan-out (the #5039 fix path) so the whole multi-inbound
    identity is toggled at once, dropping the circular Set/Toggle dependency.
    
    * fix(traffic): commit a traffic tick even when a best-effort maintenance helper fails
    
    addTrafficLocked stages the inbound and client deltas, then runs three helpers
    (auto-renew, disable depleted clients, disable depleted inbounds) that are meant
    to log and continue. All three reused the function-scope err that the deferred
    commit/rollback inspects, so the last helper's error decided the whole tick: a
    failure in disableInvalidInbounds rolled back the already-staged traffic while
    AddTraffic reported success, and because xray had already advanced its counter
    baseline that traffic was lost for good. Give each best-effort helper its own
    error variable so only a genuine staging failure rolls the tick back.
    
    * fix(traffic): re-enable clients and serialize the write in Reset All Client Traffic
    
    ClientService.ResetAllTraffics zeroed up/down but, unlike every sibling reset
    path, never restored enable=true, so clients that had been auto-disabled for
    exceeding their quota stayed cut with zero usage after a reset. It also wrote
    client_traffics directly on the shared DB handle instead of through the serial
    traffic writer, reintroducing the cross-transaction lock-order deadlock the
    writer exists to prevent. Restore enable and run the reset inside
    submitTrafficWrite within one transaction.
    
    * fix(traffic): keep node reset propagation out of the serial traffic writer
    
    ResetAllTraffics and ResetInboundTraffic performed their remote-node reset HTTP
    calls inside submitTrafficWrite. Each call can block up to the remote timeout,
    and Reset All Traffics loops every node serially, so the single traffic-writer
    goroutine was held for seconds — long enough that the concurrent 5s traffic poll
    timed out submitting its own write and dropped the deltas it had already drained
    from xray. Do the DB reset inside the writer, then propagate to the nodes after
    it returns, matching how the mtproto quota reset is already sequenced.
    
    * fix(sub): stop the subscription from 500ing on valid-but-unusual stream settings
    
    The raw share-link generators used unchecked type assertions and unguarded
    array indexing: an empty Reality shortIds/serverNames array (random.Num(0)
    panics), a tcp-http header with no request block or an empty request.path, a
    grpc block missing its keys, empty stream settings, and a non-string Host
    header all panicked mid-generation. Because getSubs loops every client's link
    with no recover, one such client 500s the entire subscription for everyone. The
    sibling JSON, Clash and frontend generators already guard these; make the raw
    generators match with comma-ok assertions and length checks.
    
    * fix(sub): tolerate a hysteria inbound without hysteriaSettings in the JSON subscription
    
    genHy asserted stream["hysteriaSettings"].(map[string]any) without the comma-ok
    form, so a hysteria inbound whose StreamSettings omit the hysteriaSettings key
    (a valid, representable shape the raw generator renders fine) panicked and 500ed
    the entire JSON subscription. Use comma-ok; the downstream reads already guard
    each key, so a nil map degrades gracefully.
    
    * fix(sub): emit the pinned peer cert sha256 in Clash subscriptions
    
    The Clash stream builder computed tlsSettings["pin-sha256"] from the inbound's
    pinnedPeerCertSha256, but applySecurity's tls case never copied it onto the
    proxy, so it was written with no reader and silently dropped. Clash subscribers
    lost certificate pinning while JSON subscribers kept it. Surface pin-sha256 on
    the proxy in the tls case, matching the JSON emitter.
    
    * fix(link): parse the snake_case and extra-blob xhttp fields when importing a share link
    
    The panel's share-link emitters (Go and TS) carry advanced xhttp knobs as a
    snake_case x_padding_bytes plus an extra=<json> payload, but the Go parser's
    xhttp branch read only top-level camelCase params, so importing an xhttp link
    via the outbound-subscription feature dropped xPaddingBytes, scMaxEachPostBytes
    and the rest, silently reverting them to the stream defaults and producing a
    non-working outbound. Mirror the TS parser: read the snake_case alias, merge the
    extra JSON blob, then let explicit camelCase params win.
    
    * fix(frontend): decode URL-safe base64 when parsing an imported share link
    
    Base64.decode called window.atob directly, which rejects the base64url
    alphabet (- and _) and unpadded input. But the panel's own share-link emitter
    uses Base64.encode(x, true) (URL-safe, unpadded), and real SIP002 links do too,
    so importing a Shadowsocks link whose method:password encodes with a - or _ threw,
    fell back to the raw undecoded string, and produced a wrong method and garbage
    password (the vmess parser shared the same limitation). Normalize base64url and
    re-pad before atob so decode round-trips every emitted link.
    
    * fix(link): honor the vmess ws path and hysteria2 vcn params on import
    
    Two Go/TS parser parity gaps in the outbound share-link import path: parseVmess
    only applied a ws link's path when the inner JSON also carried a host key, so a
    generator that omits host dropped the path back to the default; and parseHysteria2
    hardcoded verifyPeerCertByName to empty, ignoring the vcn param the panel emits,
    so a hysteria2 outbound with a decoy SNI and a distinct cert name failed TLS
    verification after import. The TS parser handles both; make the Go parser match.
    
    * fix(ui): stop the sniffing form island from clobbering unrendered fields
    
    antd's Form.useWatch only reports registered fields, so while the
    sniffing toggle was off the island emitted { enabled: false } upward and
    replaced the full Sniffing object in form state. Saving a VLESS reverse
    outbound then crashed in sniffingToWire on the missing ipsExcluded
    array; the loopback outbound and the inbound sniffing tab shared the
    same hole. Watch the store with preserve: true so unrendered fields
    keep their values, and seed a missing value from the schema defaults
    instead of an empty cast.
    
    * fix(sub): drop empty remark segments instead of leaving a stray separator
    
    expandSegment dropped a "|" segment only when its tokens rendered the unlimited
    mark, so a segment whose only token resolved to the empty string (a client with
    no comment, an unlimited client's expiry date) was kept as bare decoration,
    leaving a trailing "|" or a dangling emoji on every share link's remark. Drop a
    token-bearing segment whenever none of its tokens produce a real value, while
    still keeping pure-literal segments.
    
    * fix(xray): keep source- and domains-scoped routing rules when an inbound is deleted
    
    removeInboundTagFromRules drops a routing rule whose inboundTag list becomes
    empty only if the rule has no other matcher, but routingMatcherKeys omitted
    xray-core's canonical source and domains keys. A rule scoped by source or domains
    (common in hand-authored or imported configs) therefore lost its whole body —
    including a security-relevant block — when its single listed inbound was deleted,
    instead of just having the tag trimmed. Recognize source and domains as live
    matchers.
    
    * fix(xray): guard RemoveUser against an uninitialized handler client
    
    Every XrayAPI handler method returns an error when HandlerServiceClient is nil,
    except RemoveUser, which dereferenced it directly. A depletion sweep runs Init
    with the port ignored and, during a restart window where the fresh process's
    api port is still 0, Init fails and leaves the client nil — so RemoveUser
    panicked (recovered by the traffic writer, but re-thrown every poll) instead of
    returning an error. Add the same nil guard the siblings have.
    
    * fix(xray): do not revive a manually stopped Xray on a background restart
    
    RestartXray cleared isManuallyStopped unconditionally at its top, so the @30s
    pending-config cron (and warp/ldap/outbound reconcile jobs) that call
    RestartXray(false) resurrected an Xray the admin had deliberately stopped —
    unlike the crash-detector, which honors the manual-stop flag. Skip a non-forced
    restart while the stop flag is set; only an explicit forced restart clears it.
    
    * fix(xray): retry a failed pending-restart instead of dropping the config change
    
    The 30s cron consumed the need-restart flag with IsNeedRestartAndSetFalse before
    calling RestartXray and only logged a failure. If RestartXray failed early (a
    transient GetXrayConfig DB error) the old process kept running the old config,
    the crash detector saw a running process and never retried, and the flag stayed
    cleared — so an admin's saved change silently never reached the core. Move the
    consume/restart/retry into ApplyPendingRestart, which re-arms the flag on
    failure so the next tick retries.
    
    * fix(xray): synchronize the process version and apiPort fields
    
    Start writes p.version and p.apiPort (via refreshVersion/refreshAPIPort) after
    flipping the process to running, while GetXrayVersion and GetAPIPort read them
    lock-free from the status and traffic poll goroutines. The struct mutex
    deliberately excluded these fields, so a restart racing a poll was a real data
    race — a torn read of the version string header can crash. Extend the mutex to
    cover version and apiPort, doing the blocking version probe before taking the
    lock.
    
    * fix(settings): detect a wildcard listen collision between the web and sub ports
    
    The web/sub same-port check compared the two listen addresses as raw strings, so
    binding both on all interfaces with different spellings (webListen 0.0.0.0 vs an
    empty subListen) slipped past validation and only failed at startup with an
    opaque bind error. Treat any wildcard listen ('', 0.0.0.0, ::) as overlapping so
    the clash is reported up front, while still allowing two distinct specific
    addresses to share a port.
    
    * fix(db): mark the IP-limit cleanup seeder done on a fresh install
    
    ResetIpLimitNoFail2ban is a one-time migration that, on a host without fail2ban,
    zeroes every existing client's limitIp because the limit can't be enforced. It
    was missing from the fresh-install fast-path seeder list, so on a brand-new DB it
    did not run on the first boot but fired on the second — wiping any IP limits the
    admin had set in between. Add it to the fast-path so a truly fresh install marks
    it done up front (there is nothing to clean), leaving later admin-set limits
    intact.
    
    * fix(security): dial outbound subscriptions through the SSRF guard
    
    The outbound-subscription fetch validated the URL host once (resolving DNS and
    rejecting private targets) but then fetched with a plain HTTP client that
    re-resolves the host at dial time, so a subscription domain the attacker controls
    could pass validation as a public IP and rebind to 127.0.0.1 / a cloud metadata
    endpoint / an internal host for the actual dial — a blind SSRF into the panel's
    network. Route the direct fetch (and its redirects) through
    netsafe.SSRFGuardedDialContext, which resolves, checks and dials the same IP
    atomically, carrying the subscription's AllowPrivate flag on the request context;
    a configured egress proxy still dials its loopback bridge unguarded.
    
    * fix(security): bound the login-limiter attempts map
    
    The login rate limiter keys its records on the caller-supplied username and only
    evicted a record when that exact key was revisited or the login succeeded. An
    unauthenticated attacker replaying one CSRF token while rotating a fresh username
    per request seeded a record that was never revisited, growing the map without
    bound until the panel OOMs. Cap the map: before inserting a new record, reclaim
    records whose block has lapsed and whose failures aged out, and if the map is
    still at the ceiling under a broad flood, drop one so memory can never grow past
    the cap.
    
    * fix(tgbot): require admin for privileged callbacks, not just the first switch
    
    answerCallback wraps only its first callback switch in an isAdmin guard; the
    second switch (server usage, inbound/online enumeration, database backup export,
    ban logs, mass traffic reset, client creation) ran for every caller. Telegram
    delivers a callback with the tapping user's id, so a non-admin who can see an
    admin's inline keyboard — as when the bot runs in a group — could tap Backup and
    receive the full database and config, or reset all traffic. Default-deny before
    the second switch: a non-admin may only run the per-user client_* callbacks that
    resolve their own data from their Telegram id.
    
    * fix(eventbus): dispatch each subscriber in its own goroutine
    
    The fan-out loop called every subscriber's handler sequentially on the
    single dispatch goroutine. The email and Telegram notifiers block on
    network I/O for tens of seconds (or minutes when the remote is slow), so
    one slow subscriber stalled the whole loop: the 256-slot channel then
    filled and Publish silently dropped later events — including high-value
    xray.crash and node.down notifications unrelated to the slow handler.
    
    Hand each delivered event to every handler in its own goroutine so a
    blocking subscriber can no longer stall delivery to the others. safeCall
    already recovers panics, so a detached handler cannot take down the bus.
    
    * fix(integration): cap WARP API response body size
    
    doWarpRequest read the response with an unbounded io.ReadAll, unlike the
    sibling NordVPN client which already caps every read at maxResponseSize.
    A hostile panel egress proxy or a MITM on the Cloudflare WARP endpoint
    could stream an arbitrarily large body and force the panel into an
    unbounded allocation. Wrap the body in an io.LimitReader(maxResponseSize)
    to match the NordVPN client.
    
    * fix(email): bound every SMTP step with a connection deadline
    
    The "starttls"/"none" transport delivered through net/smtp.SendMail, which
    dials with an untimed net.Dial and never sets a socket deadline. When an
    SMTP server accepted the TCP connection but then stalled (or was a
    blackhole), the caller was released by Send's 30s select, but the sender
    goroutine and its socket stayed blocked until the OS TCP timeout — minutes
    per notification, leaking a goroutine and a connection each time.
    sendWithTLS dialed with a timeout but likewise armed no deadline on the
    protocol phase, and TestConnection (called synchronously from the settings
    handler, with no select guard) could hang the request indefinitely.
    
    Replace SendMail with sendPlain, which dials with smtpConnectTimeout and
    arms conn.SetDeadline(smtpDeadline) before the greeting read, preserving
    SendMail's opportunistic STARTTLS upgrade. Arm the same deadline in
    sendWithTLS and TestConnection so every SMTP step is bounded.
    
    * fix(server): guard access-log parser against malformed lines
    
    GetXrayLogs split each Xray access-log line on whitespace and then read
    fixed offsets — parts[1] for the timestamp and parts[i+1] after the "from",
    "accepted" and "email:" markers — without checking the line had that many
    fields. A truncated or malformed line (the logged destination is
    attacker-influenced) indexed past the slice and panicked; the panel handler
    returned a 500 via Gin's recovery.
    
    Extract the per-line field parsing into parseAccessLogFields and length
    guard every positional lookup so a short line yields a partial entry
    instead of panicking.
    
    * fix(server): guard xray key-generator output parsing
    
    GetNewX25519Cert, GetNewmldsa65 and GetNewmlkem768 parsed xray's stdout by
    reading lines[0], lines[1] and each line's second colon-separated field
    without any length check — unlike GetNewEchCert, which already guards its
    line count. If the xray binary printed fewer than two lines or reformatted
    its labels (a version change, or a silent failure that emitted nothing),
    the fixed slice index panicked and the handler 500'd.
    
    Extract the shared parsing into parseXrayKeyPairOutput, which length guards
    the line count and each label split and returns an error instead of
    panicking, then route all three generators through it.
    
    * fix(tgbot): stop auto-deleted messages from resetting wizard state
    
    SendMsgToTgbotDeleteAfter spawns a goroutine that, after the display delay,
    deleted the transient message and then unconditionally cleared the chat's
    conversation state. Every caller that ends a wizard step already clears the
    state synchronously, so that call was redundant — and harmful: if within
    the delay the user advanced to the next step (a callback sets a fresh
    awaiting_* state), the late goroutine wiped it, and the user's next message
    fell through unrecognized, silently dropping their input.
    
    Move the delayed deletion into deleteMessageAfterDelay, which only removes
    the message and no longer touches the conversation state. Guard
    deleteMessageTgBot against a nil bot so the deletion path is unit-testable.
    
    * fix(frontend): refetch a fresh CSRF token on 403 instead of reusing the stale meta tag
    
    On a 403 to an unsafe method the client cleared its cached CSRF token and
    called ensureCsrfToken to retry. But ensureCsrfToken prefers the
    <meta name="csrf-token"> tag baked into the page, which the production
    panel always injects, so the "refresh" re-read the same stale token and the
    /csrf-token refetch was never reached — the retry re-sent the token that had
    just been rejected and the save failed with an error toast.
    
    The token lives in the session and rotates when the session is regenerated
    (for example re-login in another tab), leaving the tab's baked-in meta token
    stale. Fetch the current token straight from /csrf-token in the 403 branch so
    the retry uses the authoritative server value. The existing tests only passed
    because they strip the meta tag; the new test keeps a stale tag present.
    
    * fix(frontend): surface backend error text from failed requests
    
    HttpUtil.get/post read the thrown HttpError body as response.data.message,
    but the backend error envelope (entity.Msg) serializes its text as msg. On
    any non-2xx JSON response the real reason was therefore dropped and the
    operator saw only the generic "Request failed with status N" toast.
    
    Read response.data.msg first (keeping message and the native error text as
    fallbacks). The sibling test had pinned the wrong body shape ({ message });
    correct it to the real backend shape ({ success:false, msg }) so it exercises
    the actual envelope.
    
    * fix(frontend): share one WebSocket connection across bridge and hooks
    
    websocketBridge.ts and useWebSocket.ts each declared their own
    module-scoped sharedClient plus an identical getSharedClient, so the
    "shared" client was not shared between them: whenever a page using
    useWebSocket (Clients/Inbounds) mounted alongside the always-mounted
    bridge, the panel opened two sockets to /ws. The server then pushed every
    traffic/stats/nodes/inbounds snapshot to both, doubling WebSocket bandwidth
    and running two independent reconnect loops, and the hook's socket was never
    disconnected on unmount.
    
    Hoist a single getSharedWebSocketClient into api/websocket.ts and route both
    the bridge and the hook through it, so exactly one connection is opened.
    
    * fix(frontend): guard the outbounds WebSocket handler against non-array payloads
    
    onOutbounds wrote the raw WebSocket payload straight into the
    outboundsTraffic cache, unlike the sibling onNodes/onInbounds handlers which
    first check Array.isArray. A malformed non-array push (for example an object)
    would land in the cache with staleTime Infinity; consumers that call
    .find()/.map() on the outbounds list would then throw and crash the Outbounds
    tab. Add the same Array.isArray guard so a bad push is ignored.
    
    * fix(frontend): key the node table by the computed row key, not id
    
    The desktop node table used rowKey="id", but transitive sub-nodes (the
    read-only rows surfaced from downstream nodes) all carry id 0, so a topology
    with two or more transitive rows gave React duplicate keys. antd's rowKey
    prop overrides the row object's own computed `key` (`t-${guid}` for
    transitive rows, the numeric id otherwise), so the unique key the code
    already builds was ignored — causing row-state/DOM mis-association on any
    re-render (heartbeat refetch, address-eye toggle). The mobile card path
    already keyed by record.key.
    
    Key the table by "key" so transitive rows get their distinct t-${guid}
    identity; direct nodes keep key === id, so row selection (filtered to numeric
    keys) is unchanged.
    
    * fix(frontend): map routing row actions through the rule's real index
    
    The routing table hides balancer-loopback rules (`_bl_*`) but keeps each
    visible row's original index in `key`, then handed antd's positional row
    index straight to edit/delete/toggle/move/drag — all of which mutate the
    full, unfiltered routing.rules array. Once a hidden loopback rule precedes a
    visible one (e.g. a balancer whose fallback is another balancer, plus any
    rule added afterwards), the positional index no longer matches the array
    index, so deleting or editing a rule silently hit the wrong one — including
    destroying the loopback rule that keeps the balancer alive.
    
    Add originalRuleIndex to translate a positional row index back through the
    row's `key`, and route every mutating handler (openEdit, confirmDelete,
    toggleRule, moveUp/moveDown, drag) through it. When no loopback rows are
    hidden the mapping is the identity, so ordinary configs are unaffected.
    
    * fix(frontend): map outbound row actions through the outbound's real index
    
    The outbounds table hides balancer-loopback outbounds (`_bl_*`) but keeps
    each visible row's original index in `key`, then passed antd's positional
    row index to edit/delete/move and to the per-row probe (onTest) and its
    result lookup — all of which address the full, unfiltered outbounds array.
    Once a hidden loopback outbound precedes a visible one, the positional index
    diverges from the array index, so deleting or editing an outbound hit the
    wrong one (its deletion-impact plan and removal targeting the wrong entry),
    and the test button probed / showed results against the wrong outbound.
    
    Add originalOutboundIndex and route the mutating handlers through it; key
    the probe trigger and test-result columns by record.key. With no loopback
    rows hidden the mapping is the identity, so ordinary configs are unaffected.
    
    * fix(frontend): tolerate a malformed happyEyeballs value in the Xray Basics tab
    
    BasicsTab derived directHappyEyeballs by calling HappyEyeballsSchema.parse
    during render, guarding only against null/non-object. A wrong-typed field
    (e.g. happyEyeballs.tryDelayMs as a string) or any other shape mismatch —
    reachable via the Complete Template JSON editor or an imported config — threw
    straight out of render, white-screening the default Xray landing tab.
    
    Use safeParse and fall back to null so a bad value degrades to "no override"
    instead of crashing the page.
    
    * fix(frontend): preserve routing-rule fields the form does not surface
    
    The rule form rebuilt the rule from a fixed literal of only the fields it
    edits, and RoutingTab replaces the rule wholesale on confirm. Fields the
    form never exposes — localPort, localIP, process, ruleTag, webhook — are in
    the rule schema and can arrive via the advanced JSON editor or Import Rules;
    opening such a rule in the form and saving silently dropped them.
    
    Carry over every key of the original rule the form does not manage before
    applying the form-derived fields, so an edit only touches what it surfaces.
    
    * fix(frontend): re-sync the sniffing island when its value changes externally
    
    The sniffing config editor froze its seed value at mount and only watched
    its own inner AntD form, never reflecting a later change to the shared RHF
    `sniffing` path. Because the inbound form mounts every tab with
    forceRender, the friendly Sniffing tab and the Advanced JSON editor are live
    at once: editing sniffing in the JSON editor updated the RHF value but not
    the frozen island, so the next interaction with the friendly tab emitted the
    stale value and silently discarded the JSON edit.
    
    Add an effect that pushes an external value change into the inner form,
    guarded by the same lastEmitted marker the emit path uses so the island
    never re-seeds from its own echo and no update loop forms.
    
    * fix(frontend): don't drift a client's byte quota on a no-op save
    
    The quota field shows the total in GB rounded to two decimals; editing a
    client and saving converted that display value straight back to bytes. A
    byte total not aligned to 0.01 GB — one set via the API or an import — was
    therefore rewritten to the rounded value on any save that never touched the
    field, losing a few MB each time.
    
    Add resolveTotalBytes: keep the original byte total when the displayed GB
    still matches it, and only re-derive from GB when the user actually changed
    the field.
    
    * fix(eventbus): deliver events on a bounded per-subscriber worker
    
    The previous fix dispatched each event to every subscriber with a bare
    `go safeCall`. That unblocked the dispatch loop, but removed the bus's
    backpressure: under a login-attempt flood (which both notifier subscribers
    process without rate-limiting) with email/Telegram enabled, every attempt
    spawned handler goroutines that each block on network I/O for up to ~30s,
    with no bound — a goroutine and outbound-connection storm. It also let a
    subscriber's handler run concurrently with itself, racing the Telegram
    notifier's lazily-cached hostname.
    
    Give each subscriber its own bounded queue drained by a single worker
    goroutine. Dispatch does a non-blocking send per subscriber (dropping only
    that subscriber's event when its queue is full), so a slow subscriber still
    can't stall the others, concurrency is bounded to one in-flight handler per
    subscriber, per-subscriber event order is preserved, and Stop again waits
    for in-flight handlers to finish.
    
    * fix(frontend): map outbound mobile-card actions through the real index too
    
    The desktop outbounds table was keyed by the outbound's real index, but the
    mobile card list was left keying the probe trigger and every test-state
    lookup by the positional row index. With a hidden balancer-loopback outbound
    present, tapping Check on a mobile card probed the wrong outbound and the
    Test-All results landed on the wrong card. Key onTest and the
    testResult/isTesting reads by record.key, matching the desktop columns.
    
    * fix(frontend): meet WCAG AA contrast on the config-block link text
    
    The Storybook accessibility test flagged the share-link <code> block: with no
    explicit color it inherited a muted grey that renders as #888888 on the
    #f8f8f8 tertiary-fill background in CI's Chromium — a 3.33:1 contrast, below
    the 4.5:1 AA threshold. Set the text to the theme's primary text token so the
    colour is explicit and high-contrast in both light and dark themes instead of
    depending on an inherited value that varies by browser.
    
    * style(sub): simplify a negated conjunction to satisfy staticcheck QF1001
    
    golangci-lint (staticcheck QF1001) flagged the `!(a && b)` guard in
    expandSegment. Rewrite it via De Morgan's law to the equivalent
    `!a || !b` form so the linter passes; behavior is unchanged.
    
    * fix: close panics and races the audit's own fixes left nearby
    
    Second-pass review of the 54-commit self-correcting audit. Each item below
    was confirmed by reading the surrounding source (and, where practical, the
    pre-fix code) before being changed; regression tests are included for every
    behavioral fix.
    
    Concurrency:
    - eventbus: Bus.Subscribe called wg.Add with no synchronization against a
      concurrent Bus.Stop's wg.Wait, a real "WaitGroup misuse" panic risk (e.g. a
      Telegram-bot settings save racing panel shutdown/restart). Stop now flips a
      mu-guarded `stopped` flag before waiting, and Subscribe checks it under the
      same lock, so Add and Wait can no longer race.
    
    Security:
    - login_limiter: evictForRoom's fallback eviction picked an arbitrary map
      key, including ones still under an active cooldown - an attacker flooding
      /login with fresh usernames could evict their own (or anyone's) blocked
      record and reset the lockout. The fallback now skips actively-blocked
      records, only falling back to an unconditional evict if the map is
      somehow entirely full of active blocks (preserves the hard memory cap).
    
    Subscription-endpoint panics (reachable by any client hitting /sub):
    - internal/sub/service.go: applyPathAndHostParams/Obj (ws/httpupgrade/xhttp
      with no path settings object) and the TLS alpn readers in three places
      used unchecked type assertions - exactly the bug class abab7cd0 patched
      elsewhere in the same switch statements, just not these call sites.
    - internal/sub/json_service.go, clash_service.go: the externalProxy loops
      in the JSON and Clash generators used unchecked assertions on a
      legacy/admin-supplied field (missing "port", non-object entry, etc.).
    - internal/sub/json_service.go: realityData's shortId/serverName selection
      could assert a non-string array element.
    
    Other correctness:
    - client_traffic.go: ResetAllTraffics (touched by 3eb214d0) still skipped
      clearing NodeClientTraffic node-sync baselines, unlike its sibling reset
      paths in the same file - a node's next sync would re-add pre-reset delta
      on top of the freshly-zeroed counter.
    - inbound_traffic.go: the traffic-tick tx's Commit/Rollback errors were
      silently discarded; now logged so a backend-level commit failure (e.g. an
      aborted Postgres tx from a best-effort helper) doesn't masquerade as a
      successful tick.
    - outbound_subscription.go: the new subscriptionFetchClient doc comment was
      wedged between fetchAndStore's existing comment and fetchAndStore itself,
      leaving fetchAndStore undocumented and the comment describing the wrong
      function.
    
    Convention cleanup:
    - Removed narrative // comments added by the audit that violate this repo's
      no-inline-comment rule (mostly narrating the specific bug/fix rather than
      a lasting contract, and mostly on new Test functions, which this repo's
      existing tests never comment) - calibrated against this exact codebase's
      own pre-existing comment style so legitimate godoc-style doc comments
      were left alone.
    
    ---------
    
    Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
  • feat(sub): auto-detect subscription format by User-Agent (Updated) (#5826)
    * feat(settings): add subscription format controls
    
    * feat(sub): auto-detect subscription formats
    
    * fix(xray): validate balancer regexes before save
    
    * Revert "fix(xray): validate balancer regexes before save"
    
    This reverts commit 8a208ce71b7b3daed5d05607091203382d675e07.
    
    * doc(endpoints): align indent spaces
    
    * doc(settings): improve error message formatting in validateSubUserAgentRegex
    
    - Use NewErrorf with proper formatting instead of NewError with string concatenation
    - Add comment explaining the rationale for returning original pattern value
    - This preserves the intentional design where empty input is stored as empty
      in the DB and inherited as the runtime default at read time
    
    ---------
    
    Co-authored-by: Tomilla <5007859+Tomilla@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(email): build an RFC 5322 message with a proper From address and name (#5941)
    The notification/test email carried only From/To/Subject/MIME headers, and
    the From header was the raw SMTP username. Two problems:
    
    - When the SMTP login is not a bare email address (common with relays and
      submission services), the From header has no valid address and strict
      receivers reject the message — e.g. Gmail returns "550-5.7.1 ... Messages
      missing a valid address in From: header".
    - There was no Date (mandatory per RFC 5322 section 3.6) and no Message-ID,
      which also raises spam score.
    
    Add smtpFrom (sender address) and smtpFromName (display name) settings and
    assemble the message with net/mail: a name-addr From ("Name" <addr>), a
    Date, a Message-ID, and an RFC 2047 encoded Subject, in a deterministic
    header order. From falls back to the username when smtpFrom is empty, so
    existing setups keep working. Wire the settings through the model, the SMTP
    send and test paths, the Email settings UI, and all 13 locale files;
    regenerate the Zod/OpenAPI artifacts.
    
    Validate smtpFrom in AllSetting.CheckValid (reject anything net/mail cannot
    parse), which surfaces a bad address at configuration time and prevents CRLF
    header injection; strip CR/LF in buildMessage as defense in depth. Add
    buildMessage and CheckValid tests.
  • feat(hosts): bulk-add multiple hosts to multiple inbounds (#5677)
    * feat(hosts): bulk-add multiple hosts to multiple inbounds
    
    Allow users to select multiple inbound IDs and enter multiple host
    addresses (with optional per-host port override) in a single form
    submission.
    
    - Add BulkAddHostReq entity and POST /panel/api/hosts/bulk/add endpoint
    - Add AddHostsBulk service with GORM transaction safety
    - Add parseHostAndPort helper (IPv4, bracketed/bracketless IPv6, port)
    - Update HostFormModal to multi-select inbounds and tag-input hosts
    - Wire bulkCreate mutation in HostsPage with existing-host suggestions
    - Register endpoint in api-docs/endpoints.ts and regenerate OpenAPI/Zod
    
    * feat(hosts): group override records by group_id and support group editing
    
    * fix: import Popover in HostList
    
    * fix: use messageApi in HostFormModal
    
    * fix(hosts): resolve 4 bugs found in host-group code review
    
    - fix(schema): allow empty hosts array in BulkAddHostSchema so users can
      save a host without an address (inherits inbound endpoint). The old
      .min(1) was never enforced at runtime since the schema is only used for
      type inference, but the type was incorrect.
    
    - fix(service): validate new inbound IDs in UpdateHostGroup before deleting
      old rows, matching the same check already present in AddHostGroup. Prevents
      orphaned host rows when an invalid inbound ID is supplied on edit.
    
    - fix(service): replace full-table scan in GetHostsByInbound with two
      targeted queries (DISTINCT group_id WHERE inbound_id=?, then
      WHERE group_id IN ?) to avoid loading every host in the DB.
    
    - fix(mutations): remove unused createMut / create export from
      useHostMutations. The /hosts/add endpoint is identical to /hosts/bulk/add;
      only bulkCreate is used by the UI.
    
    * fix(hosts): address code review feedback (optimize bulk inserts, add validation tests, and remove comments)
    
    * fix(fmt): apply gofumpt formatting to model.go and db.go
    
    The previous merge commit incorrectly applied gofmt (tab-aligned) to
    these files. The repository's golangci config requires gofumpt+goimports
    which produces space-aligned struct fields. This commit restores the
    correct gofumpt formatting that matches upstream/main.
    
    * chore(frontend): regenerate API schemas and update lockfile
    
    * fix
    
    * refactor(hosts): dedupe host-group service and tidy frontend
    
    AddHostGroup and UpdateHostGroup shared an identical ~35-field
    model.Host construction and hand-rolled transaction boilerplate
    (tx.Begin plus a committed flag plus a deferred recover/rollback).
    Extract buildHostRows, validateInboundsExist and formatHostAddr, and
    run every mutation through db.Transaction. groupHosts collapses its
    duplicated address/port formatting and create/append fork into one
    path using slices.Contains. Behavior-preserving: host.go drops ~90
    lines with the existing service/controller tests green.
    
    Frontend: drop the Partial union and two as-casts in HostsPage.onSave
    (the modal always passes a full BulkAddHostValues), and remove the
    movable index map in HostList in favor of the table render index arg.
    
    ---------
    
    Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat: ldap skip tls verify (#5637)
    * feat(ldap): add InsecureSkipVerify field and tlsConfig helper
    
    Extract the inline TLS config at both LDAPS dial sites (FetchVlessFlags,
    AuthenticateUser) into a tlsConfig(cfg) helper, and add a new
    Config.InsecureSkipVerify bool that flows through to
    tls.Config.InsecureSkipVerify. This unblocks enterprise environments
    (e.g. Microsoft AD CS with internal CAs) where the server certificate
    chain cannot be imported into the system trust store.
    
    Behavior is identical when InsecureSkipVerify is false (the default) -
    pure refactor + plumbing. The helper is unit-testable without a live
    server, which is why it is extracted.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * feat(settings): add LdapInsecureSkipVerify setting
    
    Plumb the new LDAP skip-TLS-verify toggle through the settings stack:
    - AllSetting struct field (json/form tag: ldapInsecureSkipVerify)
    - defaultValueMap default ("false")
    - GetLdapInsecureSkipVerify() getter
    - ldap_sync_job wiring into ldaputil.Config (FetchVlessFlags path)
    - panel/user.go wiring into ldaputil.Config (AuthenticateUser path;
      the original issue's file list missed this)
    
    Persistence is handled by UpdateAllSetting's reflect loop, matching
    the existing pattern used by ldapUseTLS (no explicit setter).
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * feat(ui): add Skip TLS verification switch in LDAP settings
    
    Wire the new ldapInsecureSkipVerify setting into the hand-written
    frontend model and Zod schema, and render it as a new Switch in
    GeneralTab right under "Use TLS (LDAPS)". The switch is disabled
    when TLS is off (the setting is meaningless without LDAPS) and shows
    an insecure-warning description to make the security implication
    visible to operators.
    
    Also adds a Vitest round-trip test pinning schema acceptance and
    model default-to-false behavior.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * chore(i18n): add Skip TLS verification strings to all locales
    
    Add pages.settings.ldap.skipTlsVerify and skipTlsVerifyDesc to all 13
    backend-served translation files, matching the existing repo
    convention of keeping LDAP keys present in every locale (en-US, fa-IR,
    ru-RU, zh-CN, zh-TW, pt-BR, ar-EG, uk-UA, id-ID, tr-TR, vi-VN, ja-JP,
    es-ES). No translation-parity test exists in CI, but every other
    LDAP key is replicated across all files, so this keeps the
    invariant intact.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * chore(codegen): regenerate frontend artifacts
    
    Regenerate frontend/src/generated/{zod,types,schemas,examples}.ts
    and frontend/public/openapi.json via `npm run gen` to reflect the
    new ldapInsecureSkipVerify field. The codegen CI job runs
    `git diff --exit-code` on these files; failing to commit them would
    break the build.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
  • feat(sub): add Incy client integration and routing tab
    Add an Incy quick-import button (incy://add) to the Android and iOS app menus on the subscription page, and a new Incy settings tab with routing enable + rules. Incy routing is delivered by injecting an incy://routing/onadd line into the raw subscription body, avoiding a collision with Happ's Routing header. Includes backend settings, regenerated OpenAPI/zod schemas, and translations for all locales.
  • Use efficient APIs and simplify loops
    Minor refactors across the codebase to improve readability and use more efficient APIs: replace fmt.Sprintf+base64 encoding with fmt.Appendf when building Shadowsocks userInfo; compute elapsed using max(now-prev.at, window) to simplify logic; use strings.SplitSeq for splitting in two places; simplify test and goroutine loops to range-based iterations and use errgroup's Go helper; and align/clean up struct field formatting and test map literals. Mostly stylistic/efficiency changes with no intended behavior changes.
  • feat(memory): add memory threshold alerts (#5366)
    * feat(memory): add memory threshold alerts
    
    Add memory (RAM) threshold alerts following the same architecture as
    CPU alerts: CheckMemJob with @every 1m cadence, memoryAlarmWanted gate,
    tgMemory/smtpMemory per-subscriber settings (default 80%), EventBusCheckboxes
    with inline threshold input, i18n for en-US/ru-RU with English defaults.
    
    # Conflicts:
    #	internal/web/translation/ar-EG.json
    #	internal/web/translation/es-ES.json
    #	internal/web/translation/fa-IR.json
    #	internal/web/translation/id-ID.json
    #	internal/web/translation/ja-JP.json
    #	internal/web/translation/pt-BR.json
    #	internal/web/translation/ru-RU.json
    #	internal/web/translation/tr-TR.json
    #	internal/web/translation/uk-UA.json
    #	internal/web/translation/vi-VN.json
    #	internal/web/translation/zh-CN.json
    #	internal/web/translation/zh-TW.json
    
    * fix: address code review findings for memory alerts
    
    - Remove dead settingService field from CheckMemJob
    - Fix cpuThreshold double-emoji in 12 locale files (code prepends 🔴)
    - Align TgCpu/TgMemory fields in entity.go
    - Add missing SetTgMemory function
    
    * fix: restore settingService in CheckMemJob for consistency with CheckCpuJob
  • feat(sub): add option to hide server settings in subscription (happ) (#5433)
    * feat(settings): add option to hide server settings in subscription
    
    * chore: regenerate codegen and add translations for subHideSettings
    
    - Update frontend/src/generated/{types,schemas,zod,examples}.ts to include
      subHideSettings (bool) in AllSetting and AllSettingView
    - Add subHideSettings / subHideSettingsDesc translation keys to all 11
      remaining locales: ar-EG, fa-IR, es-ES, id-ID, ja-JP, pt-BR, uk-UA,
      tr-TR, zh-TW, zh-CN, vi-VN
    
    Co-authored-by: IgorKha <IgorKha@users.noreply.github.com>
    Co-authored-by: Sanaei <MHSanaei@users.noreply.github.com>
    
    * fix(sub): add subHideSettings default to settings map
    
    Every other sub* setting has an entry in defaultValueMap; subHideSettings was missing, so GetSubHideSettings hit the 'key not in defaultValueMap' error path on a fresh install (only masked by the false fallback in sub.go). Add the default for consistency.
  • feat(hosts): managed Hosts for per-host subscription link overrides (#5409)
    * test(sub): characterize current link output (externalProxy + single-link baselines)
    
    Phase 0 of the Hosts feature. Locks current subscription-link output for the
    externalProxy paths (vless/vmess/trojan/ss exact, reality/hysteria by Contains)
    so the upcoming ShareEndpoint refactor can be proven behavior-preserving. These
    must stay green and unedited through every later phase.
    
    * refactor(sub): unify external-proxy link building behind ShareEndpoint (TDD, snapshot-locked)
    
    Phase 1 of the Hosts feature. Collapse the duplicated externalProxy link
    builders (param-form for vless/trojan/ss, object-form for vmess) onto a single
    ShareEndpoint abstraction so Phase 4 can add Host-driven links with ~zero new
    branching.
    
    Design: an externalProxy-derived endpoint carries the original entry map and
    applies it through the UNCHANGED applyExternalProxyTLS{Params,Obj} helpers, so
    output is provably byte-identical. buildExternalProxyURLLinks /
    buildVmessExternalProxyLinks become thin adapters; the genVless/Trojan/SS/Vmess
    call sites are untouched. genHysteriaLink is deliberately left on its own path
    (hex pinSHA256, not pcs). The no-externalProxy default tails are unchanged.
    
    TDD: N1-N4 (externalProxyToEndpoint, inboundDefaultEndpoint, buildEndpointLinks,
    buildEndpointVmessLinks) written failing-first against stubs, then implemented.
    
    Mutation sanity (performed + reverted): dropping the ep-carry in
    externalProxyToEndpoint makes the Phase-0 C1/C2 characterization snapshots go
    red (TLS overrides vanish), proving the snapshots guard the emitted output.
    
    Gate: go test ./internal/sub/... and go test ./... green with ZERO edits to the
    Phase-0 snapshots; go build ./... green on linux and windows; go vet clean.
    
    * feat(model): Host entity + automigrate + openapi codegen (TDD)
    
    Phase 2 of the Hosts feature. Adds the Host GORM model: an override endpoint
    attached to an inbound (address/port + TLS/transport/clash overrides + sub
    scoping), superseding the legacy externalProxy array functionally while leaving
    it intact.
    
    - model.Host with snake_case column tags, json serializer for slices, text for
      free-JSON (mux/sockopt/xhttp), validate tags (remark 1-40, port 0-65535,
      security + mihomoIpVersion enums); TableName "hosts". NodeGuids column is added
      now but unused (host->node scoping deferred to v2).
    - Registered in BOTH initModels() (db.go) and migrationModels() (migrate_data.go);
      the latter is required for cross-DB migration and is easy to miss. PG sequence
      resync iterates the initModels slice, so it is covered automatically.
    - pruneOrphanedHosts() deletes hosts whose inbound_id has no inbound, called
      alongside pruneOrphanedClientInbounds().
    - openapigen manifest: Host added to StructAllow with MuxParams/SockoptParams/
      XhttpExtraParams -> KindAny; regenerated frontend/src/generated/* + openapi.json.
    
    TDD: TestHostTableName, TestHostValidation, TestHostAutoMigrateCreatesColumns
    (+ _Postgres), TestPruneOrphanedHosts written failing-first against a wrong-name,
    untagged, unregistered stub, then implemented.
    
    Gate: go test ./... green on SQLite AND a real Postgres DSN (local container);
    go build/vet/gofmt clean; npm run gen succeeds with the new Host type/schema/
    example/zod; npm run typecheck + npm run test (542) green.
    
    * feat(api): Host CRUD service + controller + routes (TDD)
    
    Phase 3 of the Hosts feature.
    
    - service/host.go (HostService, empty struct + database.GetDB() like
      ClientService): GetHosts, GetHostsByInbound, GetHost, AddHost (verifies the
      inbound exists — no hard FK), UpdateHost (inbound + sort order immutable here),
      DeleteHost, SetHostEnable, SetHostsEnable, DeleteHosts, ReorderHosts (single
      driver-safe transaction), GetAllTags.
    - controller/host.go mirrors NodeController: routes under /panel/api/hosts
      (list/get/byInbound/tags + add/update/del/setEnable/reorder + bulk/setEnable,
      bulk/del), binds via middleware.BindAndValidate so the model validate tags are
      enforced, {success,msg,obj} envelopes.
    - Wired the hosts group into api.go after nodes (inherits checkAPIAuth + CSRF).
    - DelInbound now cascades: deleting an inbound deletes its hosts.
    - Documented all 11 routes in api-docs endpoints.ts (referencing the generated
      Host schema) and regenerated openapi.json; extended TestAPIRoutesDocumented's
      controller->basePath switch for host.go. Backend en toast keys added.
    
    TDD: service tests (Add/GetByInbound, RejectsUnknownInbound, Reorder, Set/Bulk
    enable, DeleteHosts, DeleteInboundCascadesHosts, GetAllTags) written failing-
    first against a nil-returning stub; controller test (AddListGetDelete envelope
    round-trip + AuthInherited 401) added.
    
    Gate: go test ./internal/web/... + go test ./... green; npm run gen + typecheck
    + lint + test (542) + build green.
    
    * feat(sub): render subscription links from hosts; legacy fallback when none (TDD, mutation-checked)
    
    Phase 4 of the Hosts feature. Inserts host resolution between inbound and link
    across all three subscription formats.
    
    Mechanism: hostEndpoints(inbound, format) loads the inbound's enabled hosts
    (filtered by ExcludeFromSubTypes, ordered by sort_order then id) and projects
    each onto the externalProxy entry shape the raw/json/clash renderers already
    consume. So a host fans out one link/proxy reusing the exact existing rendering
    (address/port/security/sni/fp/alpn/pins/ech) with zero new TLS code. Host header
    and path overrides are applied additively in the raw builders (no-op for legacy
    externalProxy, which never carries those keys — characterization snapshots stay
    green). Clash ip-version (MihomoIpVersion) is set last on the proxy.
    
    Integration points:
    - getSubs (raw): per inbound, hostEndpoints AFTER projectThroughFallbackMaster;
      len>0 -> linkFromHosts (renders only the hosts), else legacy GetLink.
    - GetJson/GetClash: inject the host endpoints into the inbound's externalProxy
      before the existing getConfig/getProxies loop.
    - Precedence: hosts win over any legacy externalProxy (injection replaces it).
    
    Backward compat: a zero-host inbound takes the legacy path -> byte-identical
    output (all Phase-0 characterization snapshots unchanged).
    
    TDD: 9 cycles (zero-hosts identical, N-links-ordered with host/path override,
    disabled skipped, host-vs-externalProxy precedence, no-dedup, sort composes with
    SubSortIndex, host-over-fallback, resolve-via-client-inbounds, ExcludeFromSubTypes
    per format) written failing-first against unwired helpers, then wired green.
    
    Mutation sanity (performed + reverted, documented here):
    - zero-hosts fallback: flipping the len(hostEps)>0 guard to >=0 makes
      TestSub_ZeroHosts_IdenticalOutput go red (host path yields "" for no hosts).
    - no-dedup: adding a remark-dedup in hostEndpoints makes TestSub_NHosts_NoDedup
      go red (two distinct hosts collapse to one link).
    
    Gate: go test ./internal/sub/... + go test ./... green with ZERO edits to the
    Phase-0 snapshots; go build green on linux and windows; go vet + gofmt clean.
    
    * feat(migration): seed hosts from inbound externalProxy (TDD, idempotent, dual-driver)
    
    Phase 5 of the Hosts feature. One-time migration so existing installs surface
    their legacy externalProxy entries as first-class Host rows.
    
    - seedHostsFromExternalProxy() is self-gated on a HistoryOfSeeders
      "HostsFromExternalProxy" row (run-once) and wired into runSeeders. For each
      inbound it parses StreamSettings, reads externalProxy[], and creates one Host
      per entry: forceTls->Security (unknown->same), dest->Address, port->Port,
      remark->Remark (generated when blank, capped at 40), sni/fingerprint/alpn/
      pinnedPeerCertSha256/echConfigList copied; SortOrder=index; InboundId set.
    - Additive: externalProxy is left intact in StreamSettings (rollback-safe; the
      sub layer prefers hosts when present, §Phase 4).
    - Postgres: GORM db.Create advances hosts_id_seq via the sequence, so no extra
      resync is needed beyond the existing startup resync.
    
    TDD: field-mapping, idempotency (second run no-op), no-externalProxy->no-hosts,
    externalProxy-kept-intact written failing-first against a stub; plus a
    Postgres counterpart that skips without XUI_DB_DSN.
    
    Gate: go test ./internal/web/service/... ./internal/database/... green on SQLite;
    the *_Postgres tests green against a real Postgres container; go build green on
    linux and windows; go vet + gofmt clean. (Running the whole database package
    under XUI_DB_TYPE=postgres is not supported — the SQLite-path tests share the one
    DSN — so only the t.Skip-gated *_Postgres tests run with the env set.)
    
    * feat(ui): Hosts page + schema + query hooks + link preview helper (TDD on schema/helpers)
    
    Phase 6 of the Hosts feature — the admin UI.
    
    - schemas/api/host.ts: HostFormSchema (validation: remark 1-40, tags ^[A-Z0-9_:]+$
      ≤10×≤36, port 0-65535, security/mihomoIpVersion enums, alpn/fingerprint reused
      from the shared primitives) + a loose HostRecordSchema/HostListSchema for reads.
    - lib/hosts/host-link.ts: hostToExternalProxyEntry — the frontend mirror of the
      backend hostToExternalProxyMap (security->forceTls, sni override rules, port
      inherit), for share-link previews.
    - api/queries/useHostsQuery.ts + useHostMutations.ts (mirror the node hooks):
      list/get + add/update/del/setEnable/reorder/bulk; queryKeys.hosts.* added;
      mutations invalidate keys.hosts.root().
    - pages/hosts/{HostsPage,HostList,HostFormModal}.tsx (+CSS) mirroring pages/nodes:
      list with remark · address:port · inbound · security · tags · enable Switch ·
      per-inbound move up/down (reorder) · bulk enable/disable/delete; form grouped
      into Basic / Advanced / Clash / Subscription-scope sections.
    - Route '/hosts' + sidebar item (Global icon); menu.hosts + pages.hosts.* added to
      the en-US bundle (other locales fall back to English until translated).
    
    TDD: HostFormSchema (10 cases) and hostToExternalProxyEntry (6 cases) written
    failing-first, then implemented. UI verified by lint/typecheck/test/build.
    
    Deferred (documented enhancement): the live in-form share-link preview (needs
    inbound+client context) and a per-host host/path override in JSON/Clash output
    (raw already overrides; JSON/Clash inherit the inbound's host/path).
    
    Gate: cd frontend && npm run lint && npm run typecheck && npm run test (557) &&
    npm run build all green; go build ./... + go test ./... still green.
    
    * refactor(ui): remove the External Proxy form from the inbound stream settings
    
    Hosts supersede the legacy externalProxy: the subscription renders from hosts
    (hosts win when both exist) and the migration converts existing externalProxy
    entries to hosts. externalProxy's only real consumers were the subscription
    (now covered) and this form's preview — the backend per-client copy-link never
    used it — so removing the editor has no functional regression.
    
    - Drop ExternalProxyForm + toggleExternalProxy from InboundFormModal and delete
      the orphaned form component + its export; remove its block test + snapshot.
    - KEEP the externalProxy schema field and backend parsing/link-generation: an
      existing inbound's externalProxy still round-trips through the form (not
      silently destroyed on edit) and still renders if a host was removed.
    
    Gate: cd frontend && npm run typecheck + lint + test (556) + build green.
    
    * fix(ui): use Alert `title` instead of deprecated `message` (antd 6)
    
    Ant Design 6 deprecated <Alert message=> in favor of <Alert title=>; the panel
    was mid-migration (21 Alerts already on title). Renamed the 7 remaining stragglers
    across 5 files (SubLinksModal, InboundFormModal, sockopt, EmailTab, TelegramTab),
    silencing the runtime deprecation warning. description= is unchanged.
    
    Pre-existing warning, surfaced while testing Hosts — not introduced by it.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): align Hosts page with Clients/Inbounds cards + reorder columns
    
    - page-shell.css never listed .hosts-page, so the Hosts page got no content
      padding / transparent-layout / summary-card spacing. Add a .hosts-page shell
      block (background, dark/ultra vars, content-area + summary-card padding). This
      is the actual "card spacing" bug.
    - HostList: match the Clients/Inbounds list card — hoverable + the toolbar moved
      into the card title as a .card-toolbar (Add when nothing selected; selected
      count + bulk enable/disable/delete on selection). Re-declare .card-toolbar in
      HostList.css since the shared rule lives in a lazily-loaded page stylesheet.
    - Reorder table columns as requested: Actions, Enable, then Remark, Endpoint,
      Inbound, Security, Tags. Added scroll x for narrow screens.
    - HostsPage: add a summary card (Total / Enabled / Disabled) like the other
      pages. New i18n keys: pages.hosts.selectedCount + pages.hosts.summary.*.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): use Tabs instead of Collapse in the Add/Edit Host form
    
    The Basic / Advanced / Clash / Subscription-scope sections are now tabs. Each
    pane sets forceRender so all fields stay mounted — required because the form
    uses preserve=false, so an unmounted tab's values would otherwise be dropped on
    submit (and a required field on a hidden tab still blocks submit).
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): split Host form into Security + Advanced tabs; drop unused JSON fields
    
    - Remove the Mux/Sockopt/XHTTP raw-JSON fields from the Host form: they were not
      wired into link generation and the inbound's structured editors are inbound-
      specific (not reusable). The DB columns + read schema + generated type stay, so
      they can get proper editors later. (HostFormSchema drops them; HostRecordSchema
      keeps them.)
    - Reorganize tabs to Basic / Security / Advanced / Clash / Subscription scope:
      Security holds the TLS/cert fields (security, sni, sni-overrides, alpn,
      fingerprint, pins, verify-by-name, ech); Advanced now holds the transport
      overrides (host header, path).
    - i18n: add pages.hosts.sections.security; drop the 3 unused field labels.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): restore Mux/Sockopt/XHTTP fields in the Host Advanced tab
    
    Put the three free-JSON override fields back, in the Advanced tab next to host
    header / path (as JSON inputs — the inbound's structured editors aren't reusable
    here). Re-added to HostFormSchema + defaults + the i18n labels.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * feat(hosts): add allowInsecure (rendered) + serverDescription/mihomoX25519/vlessRouteId fields
    
    Closes most of the Remnawave-host gap analysis.
    
    - model.Host: + allowInsecure, serverDescription (≤64), vlessRouteId (0-65535),
      mihomoX25519. Auto-migrated (SQLite + Postgres verified); openapi regenerated.
    - allowInsecure is fully RENDERED into subscription output (TDD):
      - raw link: allowInsecure=1 (TLS/Reality, skipped for none) via the endpoint
        builder;
      - JSON/Clash: applyExternalProxyTLSToStream writes tlsSettings.settings.
        allowInsecure, and clash applySecurity now emits skip-cert-verify for the tls
        case (it previously only did so for Hysteria — a pre-existing gap, so inbound
        allowInsecure now renders for vless/trojan/ss clash too).
    - Frontend: the four fields added to the Host form (allowInsecure → Security,
      serverDescription → Basic, vlessRouteId → Advanced, mihomoX25519 → Clash);
      serverDescription shown under the remark in the list. Schema + i18n updated.
    
    serverDescription / vlessRouteId / mihomoX25519 are stored + editable; their
    deeper rendering (and per-host mux/sockopt/xhttp into JSON/Clash, plus a per-host
    xray JSON template) are tracked as follow-ups.
    
    Gate: go test ./... green (SQLite + Postgres for the host schema/migration);
    go build linux+windows; go vet + gofmt clean; npm run gen + typecheck + lint +
    test (556) + build green; generated files in sync.
    
    * feat(sub): render host sockopt + xhttp-extra params into JSON/Clash output (TDD)
    
    A host's sockoptParams and xhttpExtraParams (free-JSON) now take effect:
    applyHostStreamOverrides injects sockopt into the per-host stream (re-added since
    the base stream strips it) and merges xhttpExtraParams into xhttpSettings, called
    in both getConfig (JSON) and getProxies (Clash) right after the per-host TLS
    apply. No-op for legacy externalProxy entries (keys absent) — characterization
    snapshots unchanged.
    
    mux rendering is outbound-level (overrides outbound.Mux) and needs a genVless/
    genVnext/genServer signature change — deferred, along with the per-host xray
    JSON template.
    
    Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
    go build + vet + gofmt clean.
    
    * feat(sub): render host muxParams as a per-host JSON outbound mux override (TDD)
    
    genVnext/genVless/genServer take a muxOverride: a host's muxParams (when valid
    JSON) overrides the global mux on its JSON outbound; empty falls back to the
    panel mux (behavior unchanged for non-host configs). Completes the host
    mux/sockopt/xhttp trio. Test call sites updated for the new signature.
    
    Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
    go build + gofmt clean.
    
    * style(ui): show Host security fields conditionally per security (like externalProxy)
    
    * feat(sub): apply host SNI + fingerprint override for reality (TDD)
    
    A reality host now overrides SNI and fingerprint while inheriting publicKey/
    shortId from the inbound (reality keys can't be host-supplied). Previously the
    reality link kept the inbound's serverName because the TLS appliers are gated to
    security=="tls".
    
    - raw: applyEndpointRealityParams sets sni/fp on the params for reality;
    - JSON/Clash: applyHostStreamOverrides sets realitySettings.serverName +
      serverNames from the host SNI.
    
    Gated to host endpoints via an isHost marker on the synthesized ep, so the legacy
    externalProxy path stays byte-identical (characterization snapshots unchanged).
    The marker is internal and never emitted.
    
    Gate: go test ./internal/sub/... + go test ./... green; go build + vet + gofmt clean.
    
    * fix(ui): start the Host inbound select unselected instead of showing 0
    
    A new host left inboundId defaulting to 0, so the Select rendered "0". inboundId
    is now optional in the form (undefined until chosen), so it shows its
    placeholder ("Select an inbound"); the required rule still enforces a choice on
    save. Port keeps 0 (means "inherit the inbound's port").
    
    Gate: npm run typecheck + lint + build green.
    
    * fix(ui): drop redundant :port suffix from the Host inbound select label
    
    The inbound tag (e.g. in-59303-tcp) already carries the port, so the appended
    ":59303" was duplicated. Show just the remark/tag.
    
    Gate: npm run typecheck + lint + build green.
    
    * style(ui): apply the shared card hover shadows to the Hosts page
    
    page-cards.css scoped its card styling + hover shadows to each page class but
    not .hosts-page, so Hosts fell back to antd's default hoverable (a larger/blurry
    shadow + pointer cursor). Add a .hosts-page block matching the other pages.
    
    Gate: npm run build green.
    
    * feat(hosts): move Tags to Basic tab, add Nodes field, accept VLESS route ranges
    
    - Move the Tags field into the Host form's Basic tab and add a Nodes
      multi-select (visual-only assignment, backed by the existing node_guids
      column) so the Basic tab matches the reference layout.
    - Replace the single-port vlessRouteId integer with a free-form vlessRoute
      string that accepts comma-separated ports/ranges (e.g. 53,443,1000-2000);
      format-validated on the frontend, stored verbatim on the backend.
    - Regenerated frontend types/openapi from the changed model.
    
    * feat(hosts): structured editors for Mux/Sockopt/XHTTP + new Final Mask
    
    Replace the raw JSON textareas in the Host form's Advanced tab with the same
    structured editors used elsewhere, under a nested tabbed layout (General / Mux /
    Sockopt / XHTTP / Final Mask), mirroring the Sub-JSON settings tab:
    
    - Mux: the Sub-JSON mux editor (enable + concurrency/xudpConcurrency/xudp443).
    - Sockopt + XHTTP: reuse the outbound SockoptForm / XhttpForm, wrapped in an
      isolated form that serializes the edited subtree back to the host's JSON
      string (pruned so the override stays sparse).
    - Final Mask: new host field (model + column + JSON-render wiring that merges
      the masks into the host's JSON-subscription stream), edited via the shared
      FinalMaskForm like the Sub-JSON Final Mask editor.
    
    Each editor stays a controlled value/onChange component bound to its existing
    host JSON string field; backend rendering of mux/sockopt/xhttp is unchanged.
    
    * feat(hosts): drop XHTTP + Xray-JSON-template overrides; fix mobile form layout
    
    Remove the host's XHTTP extra-params and Xray-JSON-template overrides entirely
    (model fields + columns, JSON-subscription render paths incl. hostTemplateOutbound,
    schema, form tab/field, i18n, openapi codegen, and their tests) — they did not
    fit the host model. Mux, Sockopt and Final Mask stay as structured editors.
    
    Mobile fixes for the Edit Host modal:
    - responsive width (95vw on mobile, was a fixed 760px that overflowed the
      viewport and clipped the tabs/labels) + a scrollable body so the footer stays
      on screen;
    - Mux fields use responsive Row/Col (stack on mobile) instead of a fixed-width
      label grid.
    
    * fix(hosts): hide the spurious horizontal scrollbar in the Edit Host modal
    
    Setting overflowY:auto on the modal body forced overflow-x to auto too (CSS
    rule), so antd Row's negative gutter margins triggered a horizontal scrollbar.
    Pin overflowX:hidden.
    
    * feat(hosts): inbound-style responsive field layout + icon empty state
    
    - Host form (main form + Mux/Sockopt/Final Mask editors) now use the inbound
      form's label layout: label beside the input on desktop (labelCol sm span 8 /
      wrapperCol sm span 14, right-aligned), stacked label-above-input on mobile.
      Rewrote HostMuxForm onto an internal antd Form so it follows the same layout
      instead of a manual grid.
    - Empty hosts table now shows the host icon + the shared 'Nothing here yet'
      (noData) text, matching Nodes/Inbounds/Clients, replacing the bespoke
      'No hosts yet…' string.
    
    * fix(hosts): avoid nested <form> in the Edit Host modal
    
    The Mux/Sockopt/Final Mask editors each render their own antd Form inside the
    host's main Form, producing an invalid nested <form> DOM node (hydration
    warning). Render those inner forms with component={false} so they keep the form
    instance/context but emit no <form> element.
    
    * fix(hosts): make the Mux enable toggle work
    
    The Switch's checked state came from Form.useWatch('mux'), but the mux object
    field had no registered Form.Item while disabled, so setFieldValue never
    notified the watcher and the toggle stayed off. Bind the Switch to a real
    name='enabled' field (antd drives its checked state directly) and keep the
    sub-fields registered via hidden={!enabled}, serialized to the flat mux JSON.
    
    * refactor(hosts): reuse the outbound MuxForm instead of a bespoke Mux editor
    
    The Mux fields duplicated the outbound MuxForm. Reuse it through the same
    wrapper as Sockopt: generalize OutboundSubtreeJsonForm with defaultSubtree
    (pre-fill on enable) and a serialize hook, and have HostMuxForm render MuxForm
    at the ['mux'] path. The host keeps its inherit-when-off semantics by storing ''
    unless mux.enabled. Also drops the now-unused enableSwitch path from the
    wrapper (only the removed XHTTP editor used it).
    
    * style(hosts): use default-width Port input like the inbound form
    
    The host Port used width:100% (full width); the inbound's numeric inputs use
    antd's default width. Drop the override so Port matches. The Mux number inputs
    already use the default width via the reused MuxForm.
    
    * refactor(sockopt): readable customSockopt editor as a shared component
    
    The customSockopt rows were a single cramped Space.Compact line and duplicated
    verbatim in the inbound and outbound sockopt forms. Extract a shared
    CustomSockoptList that renders each entry as a titled group of labeled fields
    (System / Level / Opt / Type / Value), matching the rest of the form, and use it
    in both (and thus the host Sockopt editor).
    
    * fix(finalmask): drop the empty Custom Tables tag on a new sudoku mask
    
    The sudoku TCP-mask default seeded customTables: [''] (one empty string), which
    rendered as a blank removable tag. Seed [] instead.
    
    * fix(sockopt): make the outbound (and host) Sockopt client-only
    
    Per the XTLS sockopt docs, tproxy / acceptProxyProtocol / V6Only /
    trustedXForwardedFor only apply to an inbound (listening socket); they are
    meaningless on an outbound/dialer. Drop them from the outbound SockoptForm
    (which the host reuses). The Sockopt default object still seeds those keys, so
    the host also strips them on serialize, keeping its override honest to the
    server/client split. The inbound SockoptForm is left unchanged.
    
    * fix(sockopt): make the inbound Sockopt server-only
    
    Complete the server/client split: drop the outbound/dialer-only fields from the
    inbound SockoptForm — dialerProxy, domainStrategy, interface, addressPortStrategy,
    happyEyeballs, tcpMptcp (client-only since Go 1.24 auto-enables MPTCP on listen).
    mark stays (xray applies SO_MARK on inbound sockets too). Update the form-blocks
    snapshot to the server-side field set (intentional spec change).
    
    * feat(hosts): populate Sockopt dialerProxy with the panel's outbound tags
    
    The host Sockopt editor reused the outbound SockoptForm with outboundTags=[],
    so the dialerProxy dropdown was empty. Feed it the panel's outbound tags via
    the existing useOutboundTags hook (shares the cached xray-config query;
    blackhole excluded), so a host can chain through a subscription outbound by tag.
    
    * fix(hosts): empty-state styling on direct load + exclude balancers from dialerProxy
    
    - .card-empty was only defined in lazily-loaded Clients/Inbounds/Nodes
      stylesheets, so a direct /hosts refresh rendered the empty table state
      unstyled (faint + uncentered) until another page was visited. Re-declare it
      in HostList.css so it's correct on first load.
    - The Sockopt dialerProxy dropdown listed balancer tags (useOutboundTags merges
      them in for mtproto egress). dialerProxy chains a single outbound, so balancers
      aren't valid — switch to useOutboundTagGroups and use only the outbound group.
    
    * fix(outbounds): icon + 'Nothing here yet' empty state; stop fading other pages
    
    The Outbounds empty state was a faint '—', and OutboundsTab.css set the global
    .card-empty to opacity:0.4 — which leaked onto whichever page's empty state was
    shown after the Outbounds CSS had loaded (e.g. Hosts went faint after visiting
    Outbounds). Render the icon + noData ('Nothing here yet') like the other lists,
    and align .card-empty to the shared centered/secondary style (no opacity).
    
    * fix(outbounds): custom empty state on the desktop table too
    
    The desktop Outbounds Table had no locale.emptyText, so it showed antd's
    default 'No data' box. Add the same ExportOutlined + noData empty state as the
    card (mobile) view.
    
    * style(sidebar): use ExportOutlined for the Outbounds nav item
    
    The Outbounds sidebar item used UploadOutlined (an upload tray). Switch to
    ExportOutlined, matching the outbound icon now used in the routing target and
    the outbounds empty states.
    
    * feat(hosts): icons on the form tabs (icon-only on mobile)
    
    Wrap every Host form tab label (Basic/Security/Advanced/Clash/Subscription
    scope and the nested General/Mux/Sockopt/Final Mask) with catTabLabel, so the
    tabs show icon + text on desktop and just the icon (with a tooltip) on mobile,
    matching the Settings/Xray tab bars.
    
    * refactor(hosts): fold Exclude-from-formats into Advanced, drop the one-field tab
    
    The Subscription scope tab held only excludeFromSubTypes after Tags moved to
    Basic — a niche per-format scoping knob. Move it into the Advanced > General
    sub-tab and remove the standalone tab (and its now-unused subScope label/icon).
    
    * feat(sub): per-client remark template variables; drop the remark model & Show Usage Info
    
    * fix(migration): cap seeded host remark at the model's 256-char limit, not 40
  • feat(notifications): event bus architecture with Telegram and SMTP subscribers (#5326)
    * feat(notifications): event bus architecture with Telegram and SMTP subscribers
    
    - Event bus core with buffered channel, fan-out, panic recovery
    - Telegram subscriber with HTML formatting and rate limiting
    - Email subscriber with SMTP/TLS/STARTTLS support and stage diagnostics
    - 5 event types: outbound.down/up, xray.crash, cpu.high, login.attempt
    - CPU threshold checks per subscriber (tgCpu for TG, smtpCpu for Email)
    - SystemMetricData struct for raw metric values in events
    - i18n keys for en-US, ru-RU, and English defaults for other locales
    
    * fix
    
    * fix(notifications): repair crash/CPU alerts, harden secrets, add node alerts
    
    Bug fixes:
    - Xray crash notifications were permanently suppressed after the first crash:
      XrayStateTracker latched state="down" with no reset and no recovery event,
      so only the first crash per process lifetime ever notified. Removed the
      tracker; the existing 1/min rate limiter already dedupes crash-loop spam.
    - Email CPU alerts could never fire unless Telegram was also enabled, because
      the CPU job was registered only inside the tgbot block. Register it whenever
      either Telegram or SMTP wants cpu.high (new cpuAlarmWanted gate) and relax
      the cadence to @every 1m (cpu.Percent already samples over a full minute).
    - SMTP password (and, pre-existing, all other secrets) were shipped to the
      browser in plaintext: GetAllSettingView was dead code and /setting/all
      returned the raw model. Wire getAllSetting -> GetAllSettingView, redact
      smtpPassword with a hasSmtpPassword presence flag, and preserve it on blank
      save. Closes the leak for tgBotToken/ldapPassword/2FA token too.
    
    Polish:
    - email Send: use nil SMTP auth when no credentials (Go refuses PlainAuth over
      the unencrypted "none" transport).
    - Remove unused EventClientDepleted; fix inaccurate bus.go doc comments; drop
      stale tgBotLoginNotify from the frontend schema; gofmt alignment.
    
    Feature - node online/offline alerts:
    - Emit node.down/node.up from the heartbeat job on a real status transition
      (with a startup-spam guard), reusing NodeHealthData. Formatted by both the
      Telegram and email subscribers and selectable in the settings UI.
    
    Regenerated frontend types (hasSmtpPassword). New i18n keys added to en-US;
    other locales fall back to English (bundle default) until translated.
    
    * fix(settings): use antd Space orientation instead of deprecated direction
    
    Ant Design 6 deprecated Space's `direction` prop in favor of `orientation`,
    which logged a console warning from the Telegram/Email notification tabs. Brings
    these two tabs in line with the rest of the codebase, which already uses
    `orientation`.
    
    * i18n(notifications): translate the notification feature into all locales
    
    The notifications PR shipped ~99 new strings (SMTP settings, event labels,
    Telegram/email message templates) as English placeholders in every non-English
    locale. Translate them — plus the node-alert keys added during this review —
    into all 12 locales: Arabic, Spanish, Persian, Indonesian, Japanese,
    Portuguese-BR, Russian, Turkish, Ukrainian, Vietnamese, and Simplified/
    Traditional Chinese.
    
    Go-template placeholders ({{ .Tag }}, {{ .Name }}, etc.) are preserved exactly;
    tgbot message values carry no leading status emoji (the bot/email code adds
    those, so an emoji in the value would duplicate it); product/protocol names
    (SMTP, STARTTLS, TLS, CPU, Xray, Telegram) are kept as-is.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat: replace panel proxy URL with outbound-based egress bridge
    Instead of requiring a manual SOCKS5/HTTP URL, the panel now lets the
    admin pick an Xray outbound from a dropdown (same UX as Geodata
    Auto-Update). At runtime, injectPanelEgress appends a loopback SOCKS
    inbound (tag: panel-egress) and prepends a routing rule so the panel's
    own HTTP traffic — version checks, Telegram, normal geo-file updates —
    is routed through the chosen outbound. Xray-native Geodata Auto-Update
    is unaffected (it uses its own geodata.outbound inside Xray). Blackhole
    outbounds are excluded from both picker dropdowns since routing any
    download through one just drops it. Translations updated for all 13
    locales.
  • refactor: focused service files, leaf subpackages, and an internal/ layout (#5167)
    * refactor(service): split client.go into focused files
    
    client.go had grown to 4455 lines mixing ~10 responsibilities. Split it
    verbatim into cohesive same-package files (no behavior change):
    
      client.go            foundation: ClientService, ClientWithAttachments,
                           ClientCreatePayload, ErrClientNotInInbound, sqlInChunk
      client_locks.go      inbound mutation locks, delete tombstones, compactOrphans
      client_lookup.go     read-only lookups (GetByID, List, EffectiveFlow, ...)
      client_link.go       inbound association sync (SyncInbound, DetachInbound, ...)
      client_crud.go       single-client CRUD + validation + protocol defaults
      client_inbound_apply.go  low-level inbound-settings mutators + by-email setters
      client_bulk.go       bulk attach/detach/adjust/delete/create + DelDepleted
      client_traffic.go    traffic-reset paths
      client_groups.go     client group management
      client_paging.go     paged listing, filtering, sorting, summary
    
    Every declaration moved unchanged (verified: identical func/type/const/var
    signature set before vs after). Imports redistributed per file via goimports.
    go build ./..., go vet, and go test ./web/service/... all pass.
    
    * refactor(service): split inbound.go into focused files
    
    inbound.go was 4100 lines. Split it verbatim into cohesive same-package
    files (no behavior change):
    
      inbound.go             core inbound CRUD + InboundService (keeps pkg doc)
      inbound_protocol.go    protocol / stream capability helpers
      inbound_node.go        node/runtime/remote coordination + online tracking
      inbound_traffic.go     traffic accounting, reset, client stats
      inbound_client_ips.go  per-client IP tracking
      inbound_clients.go     client lookups within inbounds + copy-clients
      inbound_disable.go     auto-disable invalid inbounds/clients
      inbound_migration.go   DB migrations
      inbound_sublink.go     subscription link providers
      inbound_util.go        generic slice/string helpers
    
    Identical func/type/const/var signature set before vs after; package doc
    comment preserved on inbound.go. Imports redistributed via goimports.
    Build, vet, and go test ./web/service/... all pass.
    
    * refactor(service): split tgbot.go into focused files
    
    tgbot.go was 3738 lines dominated by a 1246-line answerCallback. Split it
    verbatim into cohesive same-package files (no behavior change):
    
      tgbot.go           lifecycle, bot setup, caches, small utils
      tgbot_router.go    incoming update / command / callback dispatch
      tgbot_send.go      outbound messaging primitives
      tgbot_client.go    client views, actions, subscription links
      tgbot_inbound.go   inbound listing / pickers
      tgbot_report.go    server usage, exhausted, online, backups, notifications
    
    Identical func/type/const/var signature set before vs after. Imports
    redistributed via goimports. Build, vet, and go test ./web/service/... pass.
    
    * refactor(client): dedupe single-field by-email setters
    
    ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, and
    ResetClientTrafficLimitByEmail shared an identical ~50-line body that
    resolves the inbound by email, confirms the client exists, rewrites a
    single-client settings payload, and delegates to UpdateInboundClient.
    
    Extract that into applyClientFieldByEmail(inboundSvc, email, mutate) and
    reduce each setter to a 3-line wrapper. Behavior is unchanged: same checks
    and error strings, same single-client payload contract, same totalGB guard.
    
    SetClientTelegramUserID (resolves by traffic id, different error text) and
    ToggleClientEnableByEmail/SetClientEnableByEmail (different return shape and
    a pre-read of the old state) intentionally keep their own bodies.
    
    * refactor(service): extract panel/ subpackage
    
    Move the panel-administration leaf services out of the flat service
    package into web/service/panel/ (package panel):
    
      user.go         UserService (auth / 2FA / LDAP)
      panel.go        PanelService (restart / self-update) + version helpers
      panel_other.go  non-unix RestartPanel
      panel_unix.go   unix RestartPanel
      api_token.go    ApiTokenService
      websocket.go    WebSocketService
      panel_test.go   version/shellQuote unit tests
    
    These are leaves: they depend on core (SettingService, Release) but no
    core file references them, so the extraction creates no import cycle.
    Core references are now qualified (service.SettingService, service.Release);
    callers in main.go, web/web.go, and web/controller/* updated to panel.*.
    Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract integration/ subpackage
    
    Move the external-provider integration leaves into web/service/integration/
    (package integration):
    
      warp.go        WarpService (Cloudflare WARP)
      nord.go        NordService (NordVPN)
      custom_geo.go  CustomGeoService (custom geo asset management)
      *_test.go      custom_geo / panel-proxy tests
    
    These depend on core (SettingService, ServerService, XraySettingService) but
    no core file references them. xray_setting.go stays in core because it calls
    the unexported SettingService.saveSetting. The shared isBlockedIP SSRF helper
    (used by core url_safety.go and by custom_geo) now has a small copy in each
    package rather than being exported. Core references qualified; callers in
    web/web.go, web/job/*, and web/controller/* updated to integration.*.
    Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract tgbot/ subpackage
    
    Move the Telegram bot (6 files + test) into web/service/tgbot/ (package
    tgbot). It is a leaf: it embeds five core services (Inbound/Client/Setting/
    Server/Xray) and the core never references it, so no import cycle.
    
    To support the package boundary without changing behavior:
      - core exposes XrayProcess() *xray.Process so tgbot keeps calling the
        exact same running-process methods it used via the package-level `p`;
      - three core methods tgbot calls are exported: ClientService.checkIs-
        EnabledByEmail -> CheckIsEnabledByEmail, InboundService.getAllEmails ->
        GetAllEmails (callers updated in-package);
      - tgbot's embedded-field types and the few core type refs (Status,
        ClientCreatePayload, SanitizePublicHTTPURL) are now service-qualified.
    
    Callers in main.go, web/web.go, web/job/*, and web/controller/* updated to
    tgbot.*. Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract outbound/ subpackage
    
    OutboundService (outbound.go) imports only neutral packages (config,
    database, model, xray) and its production code is referenced by no core or
    sibling service file — only by web/controller/xray_setting.go and
    web/job/xray_traffic_job.go. Move it to web/service/outbound/ (package
    outbound); no core qualification needed inside. Callers updated to outbound.*.
    
    The one coupling was a tiny pure test helper, outboundsContainTag, used by
    both outbound.go and the core outbound_subscription_test.go; it now has a
    small copy in that test file rather than being shared across the boundary.
    Build, vet, and go test ./web/... pass.
    
    * refactor(util): move wireguard into its own subpackage
    
    util/wireguard.go was the lone file of the root `util` package (24 lines,
    one exported func GenerateWireguardKeypair), while every other util concern
    lives in a focused subpackage (util/common, util/crypto, util/netsafe, ...).
    Move it to util/wireguard/ (package wireguard) for consistency; its only
    importer, web/service/integration/warp.go, is updated. The root `util`
    package no longer exists.
    
    * refactor(sub): drop redundant sub prefix from filenames
    
    Inside package sub the subXxx.go prefix just repeats the package name
    (like client_*.go did inside service). Rename for consistency; content and
    type names are unchanged:
    
      subController.go    -> controller.go
      subService.go       -> service.go
      subClashService.go  -> clash_service.go
      subJsonService.go   -> json_service.go
      (+ matching _test.go files)
    
    * refactor(controller): rename xui.go -> spa.go
    
    XUIController serves the panel's single-page-app shell; spa.go names that
    role plainly (the other controller files are domain-named). File rename only
    — the type stays XUIController. api_docs_test.go keys route base paths by
    filename, so its "xui.go" case is updated to "spa.go".
    
    * refactor: move backend packages under internal/
    
    Adopt the idiomatic Go application layout: the backend packages now live
    under internal/ (a boundary the toolchain enforces), signalling private
    implementation instead of a library-style flat root. No runtime behavior
    changes — only import paths and a few build/config paths move.
    
    Moved: config, database, logger, mtproto, sub, util, web, xray -> internal/.
    main.go stays at the repo root and tools/openapigen stays under tools/ (both
    still import internal/* because the internal rule keys off the module root).
    The module path github.com/mhsanaei/3x-ui/v3 is unchanged; 149 .go files had
    their import prefix rewritten to .../internal/<pkg>.
    
    Couplings the Go compiler can't see, updated to the new layout:
      - frontend i18n imports of web/translation (react.ts, setup.components.ts)
      - vite outDir + eslint/tsconfig ignore globs -> internal/web/dist
      - Dockerfile COPY paths for web/dist and web/translation
      - locale.go os.DirFS("web") disk fallback -> "internal/web"
      - .gitignore and ci.yml go:embed stub for internal/web/dist
      - api_docs_test.go repo-root relative walk (one level deeper)
      - tools/openapigen filesystem package paths; ApiTokenView repointed to the
        web/service/panel subpackage and codegen regenerated (clears a stale
        type the ci.yml codegen check was failing on)
    
    Verified: go build/vet/test (all packages), and frontend typecheck, lint,
    vitest (478 tests), and production build into internal/web/dist.
    
    * fix(config): keep test runs from writing logs into the source tree
    
    GetLogFolder() returns a CWD-relative "./log" on Windows. Under `go test`
    the working directory is each package's own folder, so InitLogger (called by
    tests in web/job, web/service, xray, web/websocket) created stray log/
    directories scattered through the source tree (e.g. internal/web/job/log/).
    
    Redirect to a shared temp folder when testing.Testing() reports a test run.
    Production behavior is unchanged: Windows still uses ./log next to the binary
    and Linux /var/log/x-ui. The log files were always gitignored (*.log) and
    never committed; this just stops the noise at the source.
    
    * docs: move subscription-template guide out of root into docs/
    
    sub_templates/ was a top-level folder holding only a README and no actual
    templates (3x-ui ships none by design), referenced nowhere and unlinked from
    any doc — it read like an empty placeholder cluttering the repo root.
    
    Move the guide to docs/custom-subscription-templates.md (a proper docs home),
    reword its intro to read as documentation rather than a folder note, link it
    from the Features list in README.md, and drop the empty sub_templates/ folder.
    
    * fix: update stale web/ path references after the internal/ move
    
    The internal/ migration rewrote Go import paths but left some references to
    the old top-level layout in docs, comments, and a few runtime disk paths.
    
    Functional (dev-mode only): the disk-serving fallbacks that read the Vite
    build from disk when running from source still pointed at web/dist/, which
    moved to internal/web/dist/ — so `os.DirFS`/`os.Stat`/`os.ReadFile` in
    internal/web/web.go and internal/sub/{sub,controller}.go are corrected.
    Production was unaffected (it serves the embedded FS; verified by the Docker
    build), but `go run` with a live frontend build silently fell back to embed.
    
    Docs/comments: frontend/README.md, CONTRIBUTING.md, the claude-issue-bot and
    release workflows, the openapigen -root help text, and assorted Go comments
    now reference internal/web, internal/database, internal/sub, internal/xray,
    etc. Package-name mentions (the "web" package), root paths (main.go,
    frontend/, install scripts, /etc/x-ui), routes (/panel/api/xray), and the
    historical "web/assets no longer exists" note were intentionally left as-is.
    
    * refactor(web): remove the legacy /xui -> /panel redirect middleware
    
    RedirectMiddleware existed only for backward compatibility with the old
    `/xui` URL scheme (301-redirecting /xui and /xui/API to /panel and
    /panel/api). That cutover was long ago, so drop the middleware, its
    registration in initRouter, and the now-inaccurate "URL redirection"
    mention in the middleware package doc. Old /xui URLs now 404 like any other
    unknown path. HTTPS auto-redirect and auth redirects are unrelated and stay.
    
    * build: fix .dockerignore for internal/ layout and exclude runtime dir
    
    - web/dist -> internal/web/dist: the embedded frontend moved under internal/,
      so the stale exclude no longer matched and the locally-built dist could be
      sent to the build context (the frontend stage rebuilds it fresh anyway).
    - exclude x-ui/: the local runtime directory (SQLite db, geo .dat files, xray
      binaries, certs — ~150MB) was being shipped into the build context for no
      reason. Verified the pattern excludes only the directory and still keeps
      x-ui.sh, which the Dockerfile copies to /usr/bin/x-ui.