Commit Graph
34 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): redesign the subscription page around usage, tabs and app imports
    The info page was a long key/value table followed by every link and two
    app dropdowns, and it rendered left-to-right even for Persian and Arabic.
    It now leads with a usage ring, the remaining quota and a stats grid, and
    splits the rest into Subscription / Apps / Configs tabs.
    
    - Status tells expired, data-used-up and disabled apart instead of one
      "Inactive", replacing the hard-coded English expiry chip.
    - The Apps tab keeps every Android and iOS app with its existing deep
      link, preselects the visitor's platform and adds Windows: Hiddify and
      Clash Verge Rev import directly, v2rayN copies the link.
    - fa-IR and ar-EG render right-to-left; URLs, IDs and sizes stay LTR.
    - The footer shows the support link and the client refresh interval, so
      subPageContext now carries subUpdates (also in ?format=info).
    - Status, days-left and app deep-link logic lives in subPageModel.ts,
      with unit tests pinning the deep links the page already shipped.
  • fix(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(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): add read-only HWID device-slot status endpoint (#6380)
    * feat(sub): add read-only HWID device-slot status endpoint
    
    Closes #6357
    
    A client with an HWID limit had no way to tell a subscriber how many device
    slots were left: /{subPath}/{subId} only exposes the gate as a boolean through
    X-Hwid-* headers on a 404, and ?format=info carries no limitHwid or registered
    count. Every "why can't I connect on my new phone" case therefore had to be
    answered by the operator by hand.
    
    GET /{subPath}/{subId}/hwid-status now returns the aggregate counters:
    
      {"active":true,"limit":2,"registered":1,"remaining":1,"full":false}
    
    - SELECT-only. It never registers an hwid, never touches last_seen and never
      calls the enforcement path, so asking about a slot cannot spend one.
    - Counters only: no hwid value or hash, no email, no device metadata, no IP,
      no User-Agent, and none of the X-Hwid-* gate headers.
    - The subscription id is already the bearer secret for /{subPath}/{subId}, so
      no admin token and no new auth mechanism.
    - Unknown and disabled subscriptions both answer a bare 404, with identical
      status, headers and body, so the route cannot be used to probe which
      subscription ids exist.
    - No HWID limit configured returns {"active":false,"limit":0,...}.
    - No schema change and no migration.
    
    Scoped to enabled clients exactly like effectiveHwidLimitForSubID, so the
    reported limit is always the limit the gate enforces on a shared sub_id, and
    remaining clamps at zero when the effective limit drops below the number of
    registered devices. A separate route leaves /{subPath}/{subId}, ?format=info
    and the JSON/Clash routes byte-for-byte unchanged.
    
    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
    
    * fix(sub): document hwid-status as the bare object it returns
    
    The OpenAPI operation for GET /{subPath}/{subId}/hwid-status inherited the
    {success,msg,obj} panel envelope from build-openapi.mjs's default 200
    response, while the handler writes the HwidSlotStatus struct bare. A client
    generated from the spec would read `obj` and never find the counters, and
    the description prose contradicted the schema with a hand-written example.
    
    HwidSlotStatus now sits in openapigen's StructAllow with example: tags, the
    entry references the generated schema through a `responses` block, and
    build-openapi.mjs attaches the generated example to any `responses` entry
    that $refs a generated schema, so no example is hand-written. The HEAD
    variant the controller registers is documented like its siblings, and the
    summary follows the "path prefix is configured by subPath" wording now that
    fresh panels randomise the prefix.
    
    Regenerated frontend/public/openapi.json, docs/public/openapi.json and the
    subscription-server MDX. openapi-runtime-contracts.test.ts pins the bare
    schema, the generated example and the HEAD operation.
    
    ---------
    
    Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): add legacy Clash subscription endpoint (#6338)
    * feat(sub): add legacy Clash subscription endpoint
    
    * fix(deps): update js-yaml to patched release
    
    Raise the Swagger UI js-yaml override to 4.3.2 and refresh the lockfile to resolve GHSA-2883-xcg3-v3hh without changing Swagger UI.
    
    * fix(sub): preserve client detection and normalize legacy cipher
    
    Keep the original Clash/Mihomo auto-detection default so existing subscription URLs continue returning YAML. Normalize the panel-supported chacha20-poly1305 alias when generating legacy Clash profiles, and cover both regressions through HTTP endpoint tests.
    
    * refactor(sub): drop an unreachable guard and make the alias test assert
    
    Review of the legacy Clash subscription endpoint left three LOW findings, all
    introduced by the change:
    
    - The comment above the routing merge ran to three lines, over CLAUDE.md's
      two-line cap.
    - validateClashRouteGraph on the legacy path could never fail: the legacy
      branch skips the routing merge, so it validated the literal config built a
      few lines above against itself. Dead code that reads as a guard.
    - TestClashAliasesSkipConfiguredPathConflicts asserted nothing — it could only
      fail on an escaping gin panic, so a regression that registered the alias
      handler on the configured path went unnoticed. It now drives each collision
      through the router and asserts which format answers each path.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • 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.
  • Feature/fix external subscription client expiry (#6333)
    * fix(sub): honor client expiry for external links
    
    * fix(ui): show client expiry on external links
    
    * fix(sub): address external expiry review
  • fix(sub): apply the device limit to ?view=raw
    subJsons and subClashs served the raw body and returned before enforceHwid ran,
    so appending ?view=raw to a JSON or Clash subscription URL handed out a complete,
    client-consumable config however many devices were already registered. The branch
    exists to stop a browser's Accept: text/html from being answered with the info
    page, not to skip the gate.
    
    Gate the raw branch and leave the other gate where it was, below
    maybeServeSubPage, so the HTML info page stays ungated as before.
  • 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>
  • Add remote routing URL support (#6168)
    * Add remote routing URL support
    
    * Harden remote routing refresh
    
    * fix(sub): harden remote routing fetch and accept Mihomo src rule flag
    
    Remote routing bytes reach the YAML/JSON parsers from goroutines that run
    outside Gin's recovery, so a parser panic on crafted input would take down
    the whole panel. Contain it in fetch() (a panic now degrades to a failed
    refresh that keeps the last-good value and releases the in-flight slot)
    and start the refresh, cache-load and startup-warm goroutines through
    common.GoRecover like the other background workers.
    
    The route-graph validator only skipped a trailing no-resolve flag, so a
    valid Mihomo rule like IP-CIDR,x,DIRECT,no-resolve,src was rejected as an
    unknown target; skip both option flags.
    
    Also deduplicate the HTTPS-source classification into
    common.ParseRemoteRoutingURL so the save-time validator and the resolver
    can never drift (internal/sub imports internal/web/service, so the copy
    existed only to avoid the import cycle), move the test-only
    mergeRemoteClashRulesYAML helper into the test file, and trim oversized
    comment blocks.
    
    ---------
    
    Co-authored-by: Duxxie <yelloduxx@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(sub): restore the subscription info page for browser visits
    Revert 43bc9153 and its follow-up 338822ab. The copy-only notice replaced the
    themed sub page for every browser request, so mobile users got a bare "This is
    a subscription link" screen instead of their traffic, expiry and links — and it
    left serveSubPage plus the custom-theme renderer as dead code.
  • fix(sub): keep copy page within mobile viewport
    Constrain the copy-only subscription page to the dynamic viewport, wrap long localized text, and infer text direction so mobile browsers cannot render a horizontally shifted desktop-width page. Add regression coverage for the responsive layout contract.
  • fix(sub): serve a copy-only page when a subscription URL is opened in a browser (#6183)
    * fix(sub): show copy-only page for browser subscription visits
    
    Browser navigation to /sub previously rendered the normal subscription page, which exposed subscription material in page data or raw base64 depending on request headers. Keep VPN clients on the raw subscription body, but classify browser document requests and return a neutral static copy-only HTML page with no embedded share links or page data.
    
    This preserves the C1 LimitIP parser fix in the same master candidate while avoiding a DE rollback of the browser subscription UX.
    
    * fix(sub): keep the themed page for an explicit html request
    
    Only implicit browser navigation is downgraded to the copy-only page. An
    operator who appends html=1 or view=html already holds the URL, so the
    themed subscription page keeps rendering for them and serveSubPage stays
    in use.
    
    * fix(sub): keep browser pages copy-only
  • feat(sub): add per-client subscription HWID limits (#5802)
    * feat(sub): add per-client subscription HWID limits
    
    * fix(sub): address HWID review on shared subId and bulk create
    
    * fix(sub): store HWID devices by sub_id and drop anchor client workaround
    
    * fix(sub): restore UA auto-detect and HTML page routing in subs()
    
    The cherry-pick of the HWID gate onto main's refactored SUBController
    had dropped main's UA-based format auto-detection and sub-page handling
    from subs(). Restore those branches, slotting enforceHwid after the
    HTML page and before format detection so the gate only applies to
    machine-readable subscription bodies.
    
    Also adapt tests to main's options-struct constructor and to the
    ClientService.Update signature extended with limitHwid.
    
    * fix(frontend): drop axios from HttpUtil.delete
    
    The bulk-delete rework's committed version still referenced axios,
    which this file no longer imports, breaking typecheck in CI. Use the
    httpRequest wrapper like the other verbs.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): expose last subscription fetch time (#6217)
    * feat(sub): expose last subscription fetch time
    
    Record successful GET subscription fetches per client and surface the timestamp in the client API and UI.
    
    * fix(frontend): include last subscription fetch in client traffic
    
    * Update sub_fetch_test.go
    
    ---------
    
    Co-authored-by: Hermes Agent <hermes-agent@localhost>
  • feat(sub): expose live online status and add ?format=info endpoint
    Custom subscription templates only received the lastOnline timestamp, so
    template authors had to fake an online indicator by comparing it against
    the current time, and the page was a one-shot server render with no way
    to refresh usage without reloading the whole HTML.
    
    The template context (and window.__SUB_PAGE_DATA__) now carries isOnline,
    computed from the panel's own online-client tracking (local xray plus
    remote nodes) at render time. The subscription URL also answers
    ?format=info with the page view-model as JSON — minus the links, with
    emails deduplicated — so templates can poll live status cheaply. The
    shared view-model construction moved into buildSubPageData/subPageContext
    so the HTML page, the SPA payload and the info JSON cannot drift apart.
    
    Also documents the previously injected but undocumented announce
    template variable.
  • feat(sub): add raw subscription download actions (#6017)
    * feat(sub): add raw subscription downloads
    
    * fix(sub): address review feedback
    
    * feat(sub): add download buttons to client subscriptions
    
    * fix(sub): fetch subscription before download
    
    ---------
    
    Co-authored-by: w3struk <w3struk@gmail.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>
  • feat(sub): show the announcement on the subscription info page
    The subAnnounce setting was only emitted as a base64 Announce response header, which most client apps ignore and browsers never see. Pass it into the sub page view-model and render it as an info alert at the top of the card; custom themes get the announce key for free.
    
    Closes #5276
  • feat(sub): serve the HTML info page for browser requests on JSON and Clash URLs
    Opening the /json or /clash subscription URL in a browser dumped raw JSON/YAML while the base64 URL rendered the info page. Extract the browser-detection and page-rendering branch from subs into maybeServeSubPage and run it first in all three handlers, so every subscription URL shows the same info page in a browser while client apps keep receiving the raw body.
    
    Closes #5348
  • style: adopt golangci-lint v2 and resolve all findings
    Add .golangci.yml (v2): the standard linters plus bodyclose, errorlint, noctx, misspell, rowserrcheck, sqlclosecheck, unconvert, usestdlibvars, with gofumpt + goimports formatters. Enable the std-error-handling exclusion preset for idiomatic Close/Remove/Setenv ignores; scope-exclude SA1019 (parser.ParseDir in tools/openapigen) and ST1005 (intentional capitalized user-facing error copy that tests assert verbatim). No inline nolint directives were introduced.
    
    Resolve all 217 findings behavior-preserving: gofumpt/goimports formatting, explicit blank assignment on intentionally ignored errors, errors.Is/errors.As and %w wrapping, context-aware stdlib calls (CommandContext/QueryContext/NewRequestWithContext/Dialer), staticcheck simplifications, removed redundant conversions, http.StatusOK and http.MethodGet, inlined the go:fix intPtr helper, and deferred sql rows Close. Add a golangci CI job mirroring the existing Go jobs.
  • 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.
  • 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.
  • fix(sub): {{INBOUND}} = inbound remark, fix {{TRAFFIC_LEFT}} across inbounds (#5443)
    Issue 1: the host endpoint remark no longer substitutes the inbound remark
    as the config name. {{INBOUND}} always resolves to the inbound's own remark
    and {{HOST}} to the host remark, so both can be shown side by side instead
    of the host name appearing twice. configName() drops hostRemark entirely;
    token help text updated in all locales.
    
    Issue 2: client_traffics.email is globally unique, so a client shared across
    several inbounds of one subscription has a single traffic row owned by one
    inbound. statsForClient only searched the current inbound's preloaded
    ClientStats, missing on every other inbound's link and falling back to
    Up=Down=0 -- so {{TRAFFIC_LEFT}} printed the full quota. Build a per-request
    email->stats map from all the subscription's inbounds (no extra queries) and
    fall back to it.
  • refactor(frontend): move form-item hints from extra to tooltip
    Switch reality target, node options, and WARP auto-update-IP hints from
    inline extra text to label tooltips for a cleaner form layout.
  • 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
  • fix(subscriptions): avoid shared mutable state during generation (#5270)
    * fix(subscriptions): avoid shared mutable state during generation
    
    * fix(subscriptions): serve external-link-only subs in JSON/Clash; load remark settings per request
    
    The ForRequest refactor added an early `len(inbounds) == 0` return to
    GetJson/GetClash that fired before external links were fetched, so a
    subscription whose only entries are external links (or whose inbounds are
    all disabled) rendered empty in the JSON and Clash formats. Drop the
    premature check — the existing inbounds+externalLinks empty guard already
    covers the truly-empty case.
    
    Also load datepicker/emailInRemark in PrepareForRequest rather than only in
    getSubs, so JSON and Clash remarks honor these settings instead of seeing
    the zero values (emailInRemark previously depended on the shared-state leak
    this PR fixes).
    
    Add a regression test covering an external-link-only sub across both formats.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • 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.